Output alists with dotted pair notation in .dir-locals.el
[emacs.git] / lisp / replace.el
blob00b2ceee356a757054538cc24fa6eab096fd0be6
1 ;;; replace.el --- replace commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2018 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
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 <https://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 (require 'text-mode)
32 (eval-when-compile (require 'cl-lib))
34 (defcustom case-replace t
35 "Non-nil means `query-replace' should preserve case in replacements."
36 :type 'boolean
37 :group 'matching)
39 (defcustom replace-char-fold nil
40 "Non-nil means replacement commands should do character folding in matches.
41 This means, for instance, that \\=' will match a large variety of
42 Unicode quotes.
43 This variable affects `query-replace' and `replace-string', but not
44 `replace-regexp'."
45 :type 'boolean
46 :group 'matching
47 :version "25.1")
49 (defcustom replace-lax-whitespace nil
50 "Non-nil means `query-replace' matches a sequence of whitespace chars.
51 When you enter a space or spaces in the strings to be replaced,
52 it will match any sequence matched by the regexp `search-whitespace-regexp'."
53 :type 'boolean
54 :group 'matching
55 :version "24.3")
57 (defcustom replace-regexp-lax-whitespace nil
58 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
59 When you enter a space or spaces in the regexps to be replaced,
60 it will match any sequence matched by the regexp `search-whitespace-regexp'."
61 :type 'boolean
62 :group 'matching
63 :version "24.3")
65 (defvar query-replace-history nil
66 "Default history list for query-replace commands.
67 See `query-replace-from-history-variable' and
68 `query-replace-to-history-variable'.")
70 (defvar query-replace-defaults nil
71 "Default values of FROM-STRING and TO-STRING for `query-replace'.
72 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
73 if there are no default values.")
75 (defvar query-replace-interactive nil
76 "Non-nil means `query-replace' uses the last search string.
77 That becomes the \"string to replace\".")
78 (make-obsolete-variable 'query-replace-interactive
79 "use `M-n' to pull the last incremental search string
80 to the minibuffer that reads the string to replace, or invoke replacements
81 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
83 (defcustom query-replace-from-to-separator " → "
84 "String that separates FROM and TO in the history of replacement pairs.
85 When nil, the pair will not be added to the history (same behavior
86 as in emacs 24.5)."
87 :group 'matching
88 :type '(choice
89 (const :tag "Disabled" nil)
90 string)
91 :version "25.1")
93 (defcustom query-replace-from-history-variable 'query-replace-history
94 "History list to use for the FROM argument of `query-replace' commands.
95 The value of this variable should be a symbol; that symbol
96 is used as a variable to hold a history list for the strings
97 or patterns to be replaced."
98 :group 'matching
99 :type 'symbol
100 :version "20.3")
102 (defcustom query-replace-to-history-variable 'query-replace-history
103 "History list to use for the TO argument of `query-replace' commands.
104 The value of this variable should be a symbol; that symbol
105 is used as a variable to hold a history list for replacement
106 strings or patterns."
107 :group 'matching
108 :type 'symbol
109 :version "20.3")
111 (defcustom query-replace-skip-read-only nil
112 "Non-nil means `query-replace' and friends ignore read-only matches."
113 :type 'boolean
114 :group 'matching
115 :version "22.1")
117 (defcustom query-replace-show-replacement t
118 "Non-nil means show substituted replacement text in the minibuffer.
119 This variable affects only `query-replace-regexp'."
120 :type 'boolean
121 :group 'matching
122 :version "23.1")
124 (defcustom query-replace-highlight t
125 "Non-nil means to highlight matches during query replacement."
126 :type 'boolean
127 :group 'matching)
129 (defcustom query-replace-lazy-highlight t
130 "Controls the lazy-highlighting during query replacements.
131 When non-nil, all text in the buffer matching the current match
132 is highlighted lazily using isearch lazy highlighting (see
133 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
134 :type 'boolean
135 :group 'lazy-highlight
136 :group 'matching
137 :version "22.1")
139 (defface query-replace
140 '((t (:inherit isearch)))
141 "Face for highlighting query replacement matches."
142 :group 'matching
143 :version "22.1")
145 (defvar replace-count 0
146 "Number of replacements done so far.
147 See `replace-regexp' and `query-replace-regexp-eval'.")
149 (defun query-replace-descr (string)
150 (setq string (copy-sequence string))
151 (dotimes (i (length string))
152 (let ((c (aref string i)))
153 (cond
154 ((< c ?\s) (add-text-properties
155 i (1+ i)
156 `(display ,(propertize (format "^%c" (+ c 64)) 'face 'escape-glyph))
157 string))
158 ((= c ?\^?) (add-text-properties
159 i (1+ i)
160 `(display ,(propertize "^?" 'face 'escape-glyph))
161 string)))))
162 string)
164 (defun query-replace--split-string (string)
165 "Split string STRING at a substring with property `separator'."
166 (let* ((length (length string))
167 (split-pos (text-property-any 0 length 'separator t string)))
168 (if (not split-pos)
169 string
170 (cons (substring string 0 split-pos)
171 (substring-no-properties
172 string (or (text-property-not-all
173 (1+ split-pos) length 'separator t string)
174 length)
175 length)))))
177 (defun query-replace-read-from (prompt regexp-flag)
178 "Query and return the `from' argument of a query-replace operation.
179 The return value can also be a pair (FROM . TO) indicating that the user
180 wants to replace FROM with TO."
181 (if query-replace-interactive
182 (car (if regexp-flag regexp-search-ring search-ring))
183 (let* ((history-add-new-input nil)
184 (separator-string
185 (when query-replace-from-to-separator
186 ;; Check if the first non-whitespace char is displayable
187 (if (char-displayable-p
188 (string-to-char (replace-regexp-in-string
189 " " "" query-replace-from-to-separator)))
190 query-replace-from-to-separator
191 " -> ")))
192 (separator
193 (when separator-string
194 (propertize separator-string
195 'display separator-string
196 'face 'minibuffer-prompt
197 'separator t)))
198 (minibuffer-history
199 (append
200 (when separator
201 (mapcar (lambda (from-to)
202 (concat (query-replace-descr (car from-to))
203 separator
204 (query-replace-descr (cdr from-to))))
205 query-replace-defaults))
206 (symbol-value query-replace-from-history-variable)))
207 (minibuffer-allow-text-properties t) ; separator uses text-properties
208 (prompt
209 (cond ((and query-replace-defaults separator)
210 (format "%s (default %s): " prompt (car minibuffer-history)))
211 (query-replace-defaults
212 (format "%s (default %s -> %s): " prompt
213 (query-replace-descr (caar query-replace-defaults))
214 (query-replace-descr (cdar query-replace-defaults))))
215 (t (format "%s: " prompt))))
216 (from
217 ;; The save-excursion here is in case the user marks and copies
218 ;; a region in order to specify the minibuffer input.
219 ;; That should not clobber the region for the query-replace itself.
220 (save-excursion
221 (minibuffer-with-setup-hook
222 (lambda ()
223 (setq-local text-property-default-nonsticky
224 (append '((separator . t) (face . t))
225 text-property-default-nonsticky)))
226 (if regexp-flag
227 (read-regexp prompt nil 'minibuffer-history)
228 (read-from-minibuffer
229 prompt nil nil nil nil (car search-ring) t)))))
230 (to))
231 (if (and (zerop (length from)) query-replace-defaults)
232 (cons (caar query-replace-defaults)
233 (query-replace-compile-replacement
234 (cdar query-replace-defaults) regexp-flag))
235 (setq from (query-replace--split-string from))
236 (when (consp from) (setq to (cdr from) from (car from)))
237 (add-to-history query-replace-from-history-variable from nil t)
238 ;; Warn if user types \n or \t, but don't reject the input.
239 (and regexp-flag
240 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
241 (let ((match (match-string 3 from)))
242 (cond
243 ((string= match "\\n")
244 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
245 ((string= match "\\t")
246 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
247 (sit-for 2)))
248 (if (not to)
249 from
250 (add-to-history query-replace-to-history-variable to nil t)
251 (add-to-history 'query-replace-defaults (cons from to) nil t)
252 (cons from (query-replace-compile-replacement to regexp-flag)))))))
254 (defun query-replace-compile-replacement (to regexp-flag)
255 "Maybe convert a regexp replacement TO to Lisp.
256 Returns a list suitable for `perform-replace' if necessary,
257 the original string if not."
258 (if (and regexp-flag
259 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
260 (let (pos list char)
261 (while
262 (progn
263 (setq pos (match-end 0))
264 (push (substring to 0 (- pos 2)) list)
265 (setq char (aref to (1- pos))
266 to (substring to pos))
267 (cond ((eq char ?\#)
268 (push '(number-to-string replace-count) list))
269 ((eq char ?\,)
270 (setq pos (read-from-string to))
271 (push `(replace-quote ,(car pos)) list)
272 (let ((end
273 ;; Swallow a space after a symbol
274 ;; if there is a space.
275 (if (and (or (symbolp (car pos))
276 ;; Swallow a space after 'foo
277 ;; but not after (quote foo).
278 (and (eq (car-safe (car pos)) 'quote)
279 (not (= ?\( (aref to 0)))))
280 (eq (string-match " " to (cdr pos))
281 (cdr pos)))
282 (1+ (cdr pos))
283 (cdr pos))))
284 (setq to (substring to end)))))
285 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
286 (setq to (nreverse (delete "" (cons to list))))
287 (replace-match-string-symbols to)
288 (cons 'replace-eval-replacement
289 (if (cdr to)
290 (cons 'concat to)
291 (car to))))
292 to))
295 (defun query-replace-read-to (from prompt regexp-flag)
296 "Query and return the `to' argument of a query-replace operation."
297 (query-replace-compile-replacement
298 (save-excursion
299 (let* ((history-add-new-input nil)
300 (to (read-from-minibuffer
301 (format "%s %s with: " prompt (query-replace-descr from))
302 nil nil nil
303 query-replace-to-history-variable from t)))
304 (add-to-history query-replace-to-history-variable to nil t)
305 (add-to-history 'query-replace-defaults (cons from to) nil t)
306 to))
307 regexp-flag))
309 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
310 (unless noerror
311 (barf-if-buffer-read-only))
312 (let* ((from (query-replace-read-from prompt regexp-flag))
313 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
314 (query-replace-read-to from prompt regexp-flag))))
315 (list from to
316 (or (and current-prefix-arg (not (eq current-prefix-arg '-)))
317 (and (plist-member (text-properties-at 0 from) 'isearch-regexp-function)
318 (get-text-property 0 'isearch-regexp-function from)))
319 (and current-prefix-arg (eq current-prefix-arg '-)))))
321 (defun query-replace (from-string to-string &optional delimited start end backward region-noncontiguous-p)
322 "Replace some occurrences of FROM-STRING with TO-STRING.
323 As each match is found, the user must type a character saying
324 what to do with it. For directions, type \\[help-command] at that time.
326 In Transient Mark mode, if the mark is active, operate on the contents
327 of the region. Otherwise, operate from point to the end of the buffer's
328 accessible portion.
330 In interactive use, the prefix arg (non-nil DELIMITED in
331 non-interactive use), means replace only matches surrounded by
332 word boundaries. A negative prefix arg means replace backward.
334 Use \\<minibuffer-local-map>\\[next-history-element] \
335 to pull the last incremental search string to the minibuffer
336 that reads FROM-STRING, or invoke replacements from
337 incremental search with a key sequence like `C-s C-s M-%'
338 to use its current search string as the string to replace.
340 Matching is independent of case if `case-fold-search' is non-nil and
341 FROM-STRING has no uppercase letters. Replacement transfers the case
342 pattern of the old text to the new text, if `case-replace' and
343 `case-fold-search' are non-nil and FROM-STRING has no uppercase
344 letters. (Transferring the case pattern means that if the old text
345 matched is all caps, or capitalized, then its replacement is upcased
346 or capitalized.)
348 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
349 ignore hidden matches if `search-invisible' is nil, and ignore more
350 matches using `isearch-filter-predicate'.
352 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
353 to be replaced will match a sequence of whitespace chars defined by the
354 regexp in `search-whitespace-regexp'.
356 If `replace-char-fold' is non-nil, matching uses character folding,
357 i.e. it ignores diacritics and other differences between equivalent
358 character strings.
360 Fourth and fifth arg START and END specify the region to operate on.
362 Arguments FROM-STRING, TO-STRING, DELIMITED, START, END, BACKWARD, and
363 REGION-NONCONTIGUOUS-P are passed to `perform-replace' (which see).
365 To customize possible responses, change the bindings in `query-replace-map'."
366 (interactive
367 (let ((common
368 (query-replace-read-args
369 (concat "Query replace"
370 (if current-prefix-arg
371 (if (eq current-prefix-arg '-) " backward" " word")
373 (if (use-region-p) " in region" ""))
374 nil)))
375 (list (nth 0 common) (nth 1 common) (nth 2 common)
376 ;; These are done separately here
377 ;; so that command-history will record these expressions
378 ;; rather than the values they had this time.
379 (if (use-region-p) (region-beginning))
380 (if (use-region-p) (region-end))
381 (nth 3 common)
382 (if (use-region-p) (region-noncontiguous-p)))))
383 (perform-replace from-string to-string t nil delimited nil nil start end backward region-noncontiguous-p))
385 (define-key esc-map "%" 'query-replace)
387 (defun query-replace-regexp (regexp to-string &optional delimited start end backward region-noncontiguous-p)
388 "Replace some things after point matching REGEXP with TO-STRING.
389 As each match is found, the user must type a character saying
390 what to do with it. For directions, type \\[help-command] at that time.
392 In Transient Mark mode, if the mark is active, operate on the contents
393 of the region. Otherwise, operate from point to the end of the buffer's
394 accessible portion.
396 Use \\<minibuffer-local-map>\\[next-history-element] \
397 to pull the last incremental search regexp to the minibuffer
398 that reads REGEXP, or invoke replacements from
399 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
400 to use its current search regexp as the regexp to replace.
402 Matching is independent of case if `case-fold-search' is non-nil and
403 REGEXP has no uppercase letters. Replacement transfers the case
404 pattern of the old text to the new text, if `case-replace' and
405 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
406 \(Transferring the case pattern means that if the old text matched is
407 all caps, or capitalized, then its replacement is upcased or
408 capitalized.)
410 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
411 ignore hidden matches if `search-invisible' is nil, and ignore more
412 matches using `isearch-filter-predicate'.
414 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
415 to be replaced will match a sequence of whitespace chars defined by the
416 regexp in `search-whitespace-regexp'.
418 This function is not affected by `replace-char-fold'.
420 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
421 only matches surrounded by word boundaries. A negative prefix arg means
422 replace backward.
424 Fourth and fifth arg START and END specify the region to operate on.
426 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
427 and `\\=\\N' (where N is a digit) stands for whatever matched
428 the Nth `\\(...\\)' (1-based) in REGEXP. The `\\(...\\)' groups are
429 counted from 1.
430 `\\?' lets you edit the replacement text in the minibuffer
431 at the given position for each replacement.
433 In interactive calls, the replacement text can contain `\\,'
434 followed by a Lisp expression. Each
435 replacement evaluates that expression to compute the replacement
436 string. Inside of that expression, `\\&' is a string denoting the
437 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
438 for the whole or a partial match converted to a number with
439 `string-to-number', and `\\#' itself for the number of replacements
440 done so far (starting with zero).
442 If the replacement expression is a symbol, write a space after it
443 to terminate it. One space there, if any, will be discarded.
445 When using those Lisp features interactively in the replacement
446 text, TO-STRING is actually made a list instead of a string.
447 Use \\[repeat-complex-command] after this command for details.
449 Arguments REGEXP, TO-STRING, DELIMITED, START, END, BACKWARD, and
450 REGION-NONCONTIGUOUS-P are passed to `perform-replace' (which see)."
451 (interactive
452 (let ((common
453 (query-replace-read-args
454 (concat "Query replace"
455 (if current-prefix-arg
456 (if (eq current-prefix-arg '-) " backward" " word")
458 " regexp"
459 (if (use-region-p) " in region" ""))
460 t)))
461 (list (nth 0 common) (nth 1 common) (nth 2 common)
462 ;; These are done separately here
463 ;; so that command-history will record these expressions
464 ;; rather than the values they had this time.
465 (if (use-region-p) (region-beginning))
466 (if (use-region-p) (region-end))
467 (nth 3 common)
468 (if (use-region-p) (region-noncontiguous-p)))))
469 (perform-replace regexp to-string t t delimited nil nil start end backward region-noncontiguous-p))
471 (define-key esc-map [?\C-%] 'query-replace-regexp)
473 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end region-noncontiguous-p)
474 "Replace some things after point matching REGEXP with the result of TO-EXPR.
476 Interactive use of this function is deprecated in favor of the
477 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
478 using `search-forward-regexp' and `replace-match' is preferred.
480 As each match is found, the user must type a character saying
481 what to do with it. For directions, type \\[help-command] at that time.
483 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
484 reference `replace-count' to get the number of replacements already made.
485 If the result of TO-EXPR is not a string, it is converted to one using
486 `prin1-to-string' with the NOESCAPE argument (which see).
488 For convenience, when entering TO-EXPR interactively, you can use `\\&'
489 to stand for whatever matched the whole of REGEXP, and `\\N' (where
490 N is a digit) to stand for whatever matched the Nth `\\(...\\)' (1-based)
491 in REGEXP.
493 Use `\\#&' or `\\#N' if you want a number instead of a string.
494 In interactive use, `\\#' in itself stands for `replace-count'.
496 In Transient Mark mode, if the mark is active, operate on the contents
497 of the region. Otherwise, operate from point to the end of the buffer's
498 accessible portion.
500 Use \\<minibuffer-local-map>\\[next-history-element] \
501 to pull the last incremental search regexp to the minibuffer
502 that reads REGEXP.
504 Preserves case in each replacement if `case-replace' and `case-fold-search'
505 are non-nil and REGEXP has no uppercase letters.
507 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
508 ignore hidden matches if `search-invisible' is nil, and ignore more
509 matches using `isearch-filter-predicate'.
511 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
512 to be replaced will match a sequence of whitespace chars defined by the
513 regexp in `search-whitespace-regexp'.
515 This function is not affected by `replace-char-fold'.
517 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
518 only matches that are surrounded by word boundaries.
519 Fourth and fifth arg START and END specify the region to operate on.
521 Arguments REGEXP, DELIMITED, START, END, and REGION-NONCONTIGUOUS-P
522 are passed to `perform-replace' (which see)."
523 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
524 for interactive calls, and `search-forward-regexp'/`replace-match'
525 for Lisp calls." "22.1"))
526 (interactive
527 (progn
528 (barf-if-buffer-read-only)
529 (let* ((from
530 ;; Let-bind the history var to disable the "foo -> bar"
531 ;; default. Maybe we shouldn't disable this default, but
532 ;; for now I'll leave it off. --Stef
533 (let ((query-replace-defaults nil))
534 (query-replace-read-from "Query replace regexp" t)))
535 (to (list (read-from-minibuffer
536 (format "Query replace regexp %s with eval: "
537 (query-replace-descr from))
538 nil nil t query-replace-to-history-variable from t))))
539 ;; We make TO a list because replace-match-string-symbols requires one,
540 ;; and the user might enter a single token.
541 (replace-match-string-symbols to)
542 (list from (car to) current-prefix-arg
543 (if (use-region-p) (region-beginning))
544 (if (use-region-p) (region-end))
545 (if (use-region-p) (region-noncontiguous-p))))))
546 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
547 t 'literal delimited nil nil start end nil region-noncontiguous-p))
549 (defun map-query-replace-regexp (regexp to-strings &optional n start end region-noncontiguous-p)
550 "Replace some matches for REGEXP with various strings, in rotation.
551 The second argument TO-STRINGS contains the replacement strings, separated
552 by spaces. This command works like `query-replace-regexp' except that
553 each successive replacement uses the next successive replacement string,
554 wrapping around from the last such string to the first.
556 In Transient Mark mode, if the mark is active, operate on the contents
557 of the region. Otherwise, operate from point to the end of the buffer's
558 accessible portion.
560 Non-interactively, TO-STRINGS may be a list of replacement strings.
562 Interactively, reads the regexp using `read-regexp'.
563 Use \\<minibuffer-local-map>\\[next-history-element] \
564 to pull the last incremental search regexp to the minibuffer
565 that reads REGEXP.
567 A prefix argument N says to use each replacement string N times
568 before rotating to the next.
569 Fourth and fifth arg START and END specify the region to operate on.
571 Arguments REGEXP, START, END, and REGION-NONCONTIGUOUS-P are passed to
572 `perform-replace' (which see)."
573 (interactive
574 (let* ((from (read-regexp "Map query replace (regexp): " nil
575 query-replace-from-history-variable))
576 (to (read-from-minibuffer
577 (format "Query replace %s with (space-separated strings): "
578 (query-replace-descr from))
579 nil nil nil
580 query-replace-to-history-variable from t)))
581 (list from to
582 (and current-prefix-arg
583 (prefix-numeric-value current-prefix-arg))
584 (if (use-region-p) (region-beginning))
585 (if (use-region-p) (region-end))
586 (if (use-region-p) (region-noncontiguous-p)))))
587 (let (replacements)
588 (if (listp to-strings)
589 (setq replacements to-strings)
590 (while (/= (length to-strings) 0)
591 (if (string-match " " to-strings)
592 (setq replacements
593 (append replacements
594 (list (substring to-strings 0
595 (string-match " " to-strings))))
596 to-strings (substring to-strings
597 (1+ (string-match " " to-strings))))
598 (setq replacements (append replacements (list to-strings))
599 to-strings ""))))
600 (perform-replace regexp replacements t t nil n nil start end nil region-noncontiguous-p)))
602 (defun replace-string (from-string to-string &optional delimited start end backward region-noncontiguous-p)
603 "Replace occurrences of FROM-STRING with TO-STRING.
604 Preserve case in each match if `case-replace' and `case-fold-search'
605 are non-nil and FROM-STRING has no uppercase letters.
606 \(Preserving case means that if the string matched is all caps, or capitalized,
607 then its replacement is upcased or capitalized.)
609 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
610 ignore hidden matches if `search-invisible' is nil, and ignore more
611 matches using `isearch-filter-predicate'.
613 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
614 to be replaced will match a sequence of whitespace chars defined by the
615 regexp in `search-whitespace-regexp'.
617 If `replace-char-fold' is non-nil, matching uses character folding,
618 i.e. it ignores diacritics and other differences between equivalent
619 character strings.
621 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
622 only matches surrounded by word boundaries. A negative prefix arg means
623 replace backward.
625 Operates on the region between START and END (if both are nil, from point
626 to the end of the buffer). Interactively, if Transient Mark mode is
627 enabled and the mark is active, operates on the contents of the region;
628 otherwise from point to the end of the buffer's accessible portion.
630 Use \\<minibuffer-local-map>\\[next-history-element] \
631 to pull the last incremental search string to the minibuffer
632 that reads FROM-STRING.
634 This function is usually the wrong thing to use in a Lisp program.
635 What you probably want is a loop like this:
636 (while (search-forward FROM-STRING nil t)
637 (replace-match TO-STRING nil t))
638 which will run faster and will not set the mark or print anything.
639 \(You may need a more complex loop if FROM-STRING can match the null string
640 and TO-STRING is also null.)"
641 (declare (interactive-only
642 "use `search-forward' and `replace-match' instead."))
643 (interactive
644 (let ((common
645 (query-replace-read-args
646 (concat "Replace"
647 (if current-prefix-arg
648 (if (eq current-prefix-arg '-) " backward" " word")
650 " string"
651 (if (use-region-p) " in region" ""))
652 nil)))
653 (list (nth 0 common) (nth 1 common) (nth 2 common)
654 (if (use-region-p) (region-beginning))
655 (if (use-region-p) (region-end))
656 (nth 3 common)
657 (if (use-region-p) (region-noncontiguous-p)))))
658 (perform-replace from-string to-string nil nil delimited nil nil start end backward region-noncontiguous-p))
660 (defun replace-regexp (regexp to-string &optional delimited start end backward region-noncontiguous-p)
661 "Replace things after point matching REGEXP with TO-STRING.
662 Preserve case in each match if `case-replace' and `case-fold-search'
663 are non-nil and REGEXP has no uppercase letters.
665 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
666 ignore hidden matches if `search-invisible' is nil, and ignore more
667 matches using `isearch-filter-predicate'.
669 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
670 to be replaced will match a sequence of whitespace chars defined by the
671 regexp in `search-whitespace-regexp'.
673 This function is not affected by `replace-char-fold'
675 In Transient Mark mode, if the mark is active, operate on the contents
676 of the region. Otherwise, operate from point to the end of the buffer's
677 accessible portion.
679 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
680 only matches surrounded by word boundaries. A negative prefix arg means
681 replace backward.
683 Fourth and fifth arg START and END specify the region to operate on.
685 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
686 and `\\=\\N' (where N is a digit) stands for whatever matched
687 the Nth `\\(...\\)' (1-based) in REGEXP.
688 `\\?' lets you edit the replacement text in the minibuffer
689 at the given position for each replacement.
691 In interactive calls, the replacement text may contain `\\,'
692 followed by a Lisp expression used as part of the replacement
693 text. Inside of that expression, `\\&' is a string denoting the
694 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
695 numeric values from `string-to-number', and `\\#' itself for
696 `replace-count', the number of replacements occurred so far, starting
697 from zero.
699 If your Lisp expression is an identifier and the next letter in
700 the replacement string would be interpreted as part of it, you
701 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
702 for this particular case you may also enter `\\#' in the
703 replacement text directly.
705 When using those Lisp features interactively in the replacement
706 text, TO-STRING is actually made a list instead of a string.
707 Use \\[repeat-complex-command] after this command for details.
709 Use \\<minibuffer-local-map>\\[next-history-element] \
710 to pull the last incremental search regexp to the minibuffer
711 that reads REGEXP.
713 This function is usually the wrong thing to use in a Lisp program.
714 What you probably want is a loop like this:
715 (while (re-search-forward REGEXP nil t)
716 (replace-match TO-STRING nil nil))
717 which will run faster and will not set the mark or print anything."
718 (declare (interactive-only
719 "use `re-search-forward' and `replace-match' instead."))
720 (interactive
721 (let ((common
722 (query-replace-read-args
723 (concat "Replace"
724 (if current-prefix-arg
725 (if (eq current-prefix-arg '-) " backward" " word")
727 " regexp"
728 (if (use-region-p) " in region" ""))
729 t)))
730 (list (nth 0 common) (nth 1 common) (nth 2 common)
731 (if (use-region-p) (region-beginning))
732 (if (use-region-p) (region-end))
733 (nth 3 common)
734 (if (use-region-p) (region-noncontiguous-p)))))
735 (perform-replace regexp to-string nil t delimited nil nil start end backward region-noncontiguous-p))
738 (defvar regexp-history nil
739 "History list for some commands that read regular expressions.
741 Maximum length of the history list is determined by the value
742 of `history-length', which see.")
744 (defvar occur-collect-regexp-history '("\\1")
745 "History of regexp for occur's collect operation")
747 (defcustom read-regexp-defaults-function nil
748 "Function that provides default regexp(s) for `read-regexp'.
749 This function should take no arguments and return one of: nil, a
750 regexp, or a list of regexps. Interactively, `read-regexp' uses
751 the return value of this function for its DEFAULT argument.
753 As an example, set this variable to `find-tag-default-as-regexp'
754 to default to the symbol at point.
756 To provide different default regexps for different commands,
757 the function that you set this to can check `this-command'."
758 :type '(choice
759 (const :tag "No default regexp reading function" nil)
760 (const :tag "Latest regexp history" regexp-history-last)
761 (function-item :tag "Tag at point"
762 find-tag-default)
763 (function-item :tag "Tag at point as regexp"
764 find-tag-default-as-regexp)
765 (function-item :tag "Tag at point as symbol regexp"
766 find-tag-default-as-symbol-regexp)
767 (function :tag "Your choice of function"))
768 :group 'matching
769 :version "24.4")
771 (defun read-regexp-suggestions ()
772 "Return a list of standard suggestions for `read-regexp'.
773 By default, the list includes the tag at point, the last isearch regexp,
774 the last isearch string, and the last replacement regexp. `read-regexp'
775 appends the list returned by this function to the end of values available
776 via \\<minibuffer-local-map>\\[next-history-element]."
777 (list
778 (find-tag-default-as-regexp)
779 (find-tag-default-as-symbol-regexp)
780 (car regexp-search-ring)
781 (regexp-quote (or (car search-ring) ""))
782 (car (symbol-value query-replace-from-history-variable))))
784 (defun read-regexp (prompt &optional defaults history)
785 "Read and return a regular expression as a string.
786 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
787 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
788 possibly preceded by the default result (see below).
790 The optional argument DEFAULTS can be either: nil, a string, a list
791 of strings, or a symbol. We use DEFAULTS to construct the default
792 return value in case of empty input.
794 If DEFAULTS is a string, we use it as-is.
796 If DEFAULTS is a list of strings, the first element is the
797 default return value, but all the elements are accessible
798 using the history command \\<minibuffer-local-map>\\[next-history-element].
800 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
801 is non-nil, we use that in place of DEFAULTS in the following:
802 If DEFAULTS is the symbol `regexp-history-last', we use the first
803 element of HISTORY (if specified) or `regexp-history'.
804 If DEFAULTS is a function, we call it with no arguments and use
805 what it returns, which should be either nil, a string, or a list of strings.
807 We append the standard values from `read-regexp-suggestions' to DEFAULTS
808 before using it.
810 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
811 in \":\", followed by optional whitespace), we add it to the prompt.
813 The optional argument HISTORY is a symbol to use for the history list.
814 If nil, uses `regexp-history'."
815 (let* ((defaults
816 (if (and defaults (symbolp defaults))
817 (cond
818 ((eq (or read-regexp-defaults-function defaults)
819 'regexp-history-last)
820 (car (symbol-value (or history 'regexp-history))))
821 ((functionp (or read-regexp-defaults-function defaults))
822 (funcall (or read-regexp-defaults-function defaults))))
823 defaults))
824 (default (if (consp defaults) (car defaults) defaults))
825 (suggestions (if (listp defaults) defaults (list defaults)))
826 (suggestions (append suggestions (read-regexp-suggestions)))
827 (suggestions (delete-dups (delq nil (delete "" suggestions))))
828 ;; Do not automatically add default to the history for empty input.
829 (history-add-new-input nil)
830 (input (read-from-minibuffer
831 (cond ((string-match-p ":[ \t]*\\'" prompt)
832 prompt)
833 ((and default (> (length default) 0))
834 (format "%s (default %s): " prompt
835 (query-replace-descr default)))
837 (format "%s: " prompt)))
838 nil nil nil (or history 'regexp-history) suggestions t)))
839 (if (equal input "")
840 ;; Return the default value when the user enters empty input.
841 (prog1 (or default input)
842 (when default
843 (add-to-history (or history 'regexp-history) default)))
844 ;; Otherwise, add non-empty input to the history and return input.
845 (prog1 input
846 (add-to-history (or history 'regexp-history) input)))))
849 (defalias 'delete-non-matching-lines 'keep-lines)
850 (defalias 'delete-matching-lines 'flush-lines)
851 (defalias 'count-matches 'how-many)
854 (defun keep-lines-read-args (prompt)
855 "Read arguments for `keep-lines' and friends.
856 Prompt for a regexp with PROMPT.
857 Value is a list, (REGEXP)."
858 (list (read-regexp prompt) nil nil t))
860 (defun keep-lines (regexp &optional rstart rend interactive)
861 "Delete all lines except those containing matches for REGEXP.
862 A match split across lines preserves all the lines it lies in.
863 When called from Lisp (and usually interactively as well, see below)
864 applies to all lines starting after point.
866 If REGEXP contains upper case characters (excluding those preceded by `\\')
867 and `search-upper-case' is non-nil, the matching is case-sensitive.
869 Second and third arg RSTART and REND specify the region to operate on.
870 This command operates on (the accessible part of) all lines whose
871 accessible part is entirely contained in the region determined by RSTART
872 and REND. (A newline ending a line counts as part of that line.)
874 Interactively, in Transient Mark mode when the mark is active, operate
875 on all lines whose accessible part is entirely contained in the region.
876 Otherwise, the command applies to all lines starting after point.
877 When calling this function from Lisp, you can pretend that it was
878 called interactively by passing a non-nil INTERACTIVE argument.
880 This function starts looking for the next match from the end of
881 the previous match. Hence, it ignores matches that overlap
882 a previously found match."
883 (interactive
884 (progn
885 (barf-if-buffer-read-only)
886 (keep-lines-read-args "Keep lines containing match for regexp")))
887 (if rstart
888 (progn
889 (goto-char (min rstart rend))
890 (setq rend
891 (progn
892 (save-excursion
893 (goto-char (max rstart rend))
894 (unless (or (bolp) (eobp))
895 (forward-line 0))
896 (point-marker)))))
897 (if (and interactive (use-region-p))
898 (setq rstart (region-beginning)
899 rend (progn
900 (goto-char (region-end))
901 (unless (or (bolp) (eobp))
902 (forward-line 0))
903 (point-marker)))
904 (setq rstart (point)
905 rend (point-max-marker)))
906 (goto-char rstart))
907 (save-excursion
908 (or (bolp) (forward-line 1))
909 (let ((start (point))
910 (case-fold-search
911 (if (and case-fold-search search-upper-case)
912 (isearch-no-upper-case-p regexp t)
913 case-fold-search)))
914 (while (< (point) rend)
915 ;; Start is first char not preserved by previous match.
916 (if (not (re-search-forward regexp rend 'move))
917 (delete-region start rend)
918 (let ((end (save-excursion (goto-char (match-beginning 0))
919 (forward-line 0)
920 (point))))
921 ;; Now end is first char preserved by the new match.
922 (if (< start end)
923 (delete-region start end))))
925 (setq start (save-excursion (forward-line 1) (point)))
926 ;; If the match was empty, avoid matching again at same place.
927 (and (< (point) rend)
928 (= (match-beginning 0) (match-end 0))
929 (forward-char 1)))))
930 (set-marker rend nil)
931 nil)
934 (defun flush-lines (regexp &optional rstart rend interactive)
935 "Delete lines containing matches for REGEXP.
936 When called from Lisp (and usually when called interactively as
937 well, see below), applies to the part of the buffer after point.
938 The line point is in is deleted if and only if it contains a
939 match for regexp starting after point.
941 If REGEXP contains upper case characters (excluding those preceded by `\\')
942 and `search-upper-case' is non-nil, the matching is case-sensitive.
944 Second and third arg RSTART and REND specify the region to operate on.
945 Lines partially contained in this region are deleted if and only if
946 they contain a match entirely contained in it.
948 Interactively, in Transient Mark mode when the mark is active, operate
949 on the contents of the region. Otherwise, operate from point to the
950 end of (the accessible portion of) the buffer. When calling this function
951 from Lisp, you can pretend that it was called interactively by passing
952 a non-nil INTERACTIVE argument.
954 If a match is split across lines, all the lines it lies in are deleted.
955 They are deleted _before_ looking for the next match. Hence, a match
956 starting on the same line at which another match ended is ignored."
957 (interactive
958 (progn
959 (barf-if-buffer-read-only)
960 (keep-lines-read-args "Flush lines containing match for regexp")))
961 (if rstart
962 (progn
963 (goto-char (min rstart rend))
964 (setq rend (copy-marker (max rstart rend))))
965 (if (and interactive (use-region-p))
966 (setq rstart (region-beginning)
967 rend (copy-marker (region-end)))
968 (setq rstart (point)
969 rend (point-max-marker)))
970 (goto-char rstart))
971 (let ((case-fold-search
972 (if (and case-fold-search search-upper-case)
973 (isearch-no-upper-case-p regexp t)
974 case-fold-search)))
975 (save-excursion
976 (while (and (< (point) rend)
977 (re-search-forward regexp rend t))
978 (delete-region (save-excursion (goto-char (match-beginning 0))
979 (forward-line 0)
980 (point))
981 (progn (forward-line 1) (point))))))
982 (set-marker rend nil)
983 nil)
986 (defun how-many (regexp &optional rstart rend interactive)
987 "Print and return number of matches for REGEXP following point.
988 When called from Lisp and INTERACTIVE is omitted or nil, just return
989 the number, do not print it; if INTERACTIVE is t, the function behaves
990 in all respects as if it had been called interactively.
992 If REGEXP contains upper case characters (excluding those preceded by `\\')
993 and `search-upper-case' is non-nil, the matching is case-sensitive.
995 Second and third arg RSTART and REND specify the region to operate on.
997 Interactively, in Transient Mark mode when the mark is active, operate
998 on the contents of the region. Otherwise, operate from point to the
999 end of (the accessible portion of) the buffer.
1001 This function starts looking for the next match from the end of
1002 the previous match. Hence, it ignores matches that overlap
1003 a previously found match."
1004 (interactive
1005 (keep-lines-read-args "How many matches for regexp"))
1006 (save-excursion
1007 (if rstart
1008 (if rend
1009 (progn
1010 (goto-char (min rstart rend))
1011 (setq rend (max rstart rend)))
1012 (goto-char rstart)
1013 (setq rend (point-max)))
1014 (if (and interactive (use-region-p))
1015 (setq rstart (region-beginning)
1016 rend (region-end))
1017 (setq rstart (point)
1018 rend (point-max)))
1019 (goto-char rstart))
1020 (let ((count 0)
1021 opoint
1022 (case-fold-search
1023 (if (and case-fold-search search-upper-case)
1024 (isearch-no-upper-case-p regexp t)
1025 case-fold-search)))
1026 (while (and (< (point) rend)
1027 (progn (setq opoint (point))
1028 (re-search-forward regexp rend t)))
1029 (if (= opoint (point))
1030 (forward-char 1)
1031 (setq count (1+ count))))
1032 (when interactive (message "%d occurrence%s"
1033 count
1034 (if (= count 1) "" "s")))
1035 count)))
1038 (defvar occur-menu-map
1039 (let ((map (make-sparse-keymap)))
1040 (bindings--define-key map [next-error-follow-minor-mode]
1041 '(menu-item "Auto Occurrence Display"
1042 next-error-follow-minor-mode
1043 :help "Display another occurrence when moving the cursor"
1044 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
1045 next-error-follow-minor-mode))))
1046 (bindings--define-key map [separator-1] menu-bar-separator)
1047 (bindings--define-key map [kill-this-buffer]
1048 '(menu-item "Kill Occur Buffer" kill-this-buffer
1049 :help "Kill the current *Occur* buffer"))
1050 (bindings--define-key map [quit-window]
1051 '(menu-item "Quit Occur Window" quit-window
1052 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
1053 (bindings--define-key map [revert-buffer]
1054 '(menu-item "Revert Occur Buffer" revert-buffer
1055 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
1056 (bindings--define-key map [clone-buffer]
1057 '(menu-item "Clone Occur Buffer" clone-buffer
1058 :help "Create and return a twin copy of the current *Occur* buffer"))
1059 (bindings--define-key map [occur-rename-buffer]
1060 '(menu-item "Rename Occur Buffer" occur-rename-buffer
1061 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
1062 (bindings--define-key map [occur-edit-buffer]
1063 '(menu-item "Edit Occur Buffer" occur-edit-mode
1064 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
1065 (bindings--define-key map [separator-2] menu-bar-separator)
1066 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
1067 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1068 :help "Go to the occurrence the current line describes, in another window"))
1069 (bindings--define-key map [occur-mode-goto-occurrence]
1070 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1071 :help "Go to the occurrence the current line describes"))
1072 (bindings--define-key map [occur-mode-display-occurrence]
1073 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1074 :help "Display in another window the occurrence the current line describes"))
1075 (bindings--define-key map [occur-next]
1076 '(menu-item "Move to Next Match" occur-next
1077 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
1078 (bindings--define-key map [occur-prev]
1079 '(menu-item "Move to Previous Match" occur-prev
1080 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
1081 map)
1082 "Menu keymap for `occur-mode'.")
1084 (defvar occur-mode-map
1085 (let ((map (make-sparse-keymap)))
1086 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1087 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1088 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
1089 (define-key map "e" 'occur-edit-mode)
1090 (define-key map "\C-m" 'occur-mode-goto-occurrence)
1091 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
1092 (define-key map "\C-o" 'occur-mode-display-occurrence)
1093 (define-key map "\M-n" 'occur-next)
1094 (define-key map "\M-p" 'occur-prev)
1095 (define-key map "r" 'occur-rename-buffer)
1096 (define-key map "c" 'clone-buffer)
1097 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1098 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1099 map)
1100 "Keymap for `occur-mode'.")
1102 (defvar occur-revert-arguments nil
1103 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1104 See `occur-revert-function'.")
1105 (make-variable-buffer-local 'occur-revert-arguments)
1106 (put 'occur-revert-arguments 'permanent-local t)
1108 (defcustom occur-mode-hook '(turn-on-font-lock)
1109 "Hook run when entering Occur mode."
1110 :type 'hook
1111 :group 'matching)
1113 (defcustom occur-hook nil
1114 "Hook run by Occur when there are any matches."
1115 :type 'hook
1116 :group 'matching)
1118 (defcustom occur-mode-find-occurrence-hook nil
1119 "Hook run by Occur after locating an occurrence.
1120 This will be called with the cursor position at the occurrence. An application
1121 for this is to reveal context in an outline-mode when the occurrence is hidden."
1122 :type 'hook
1123 :group 'matching)
1125 (put 'occur-mode 'mode-class 'special)
1126 (define-derived-mode occur-mode special-mode "Occur"
1127 "Major mode for output from \\[occur].
1128 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1129 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1130 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1132 \\{occur-mode-map}"
1133 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
1134 (setq next-error-function 'occur-next-error))
1137 ;;; Occur Edit mode
1139 (defvar occur-edit-mode-map
1140 (let ((map (make-sparse-keymap)))
1141 (set-keymap-parent map text-mode-map)
1142 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1143 (define-key map "\C-c\C-c" 'occur-cease-edit)
1144 (define-key map "\C-o" 'occur-mode-display-occurrence)
1145 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1146 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1147 map)
1148 "Keymap for `occur-edit-mode'.")
1150 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
1151 "Major mode for editing *Occur* buffers.
1152 In this mode, changes to the *Occur* buffer are also applied to
1153 the originating buffer.
1155 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1156 (setq buffer-read-only nil)
1157 (add-hook 'after-change-functions 'occur-after-change-function nil t)
1158 (message (substitute-command-keys
1159 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1161 (defun occur-cease-edit ()
1162 "Switch from Occur Edit mode to Occur mode."
1163 (interactive)
1164 (when (derived-mode-p 'occur-edit-mode)
1165 (occur-mode)
1166 (message "Switching to Occur mode.")))
1168 (defun occur-after-change-function (beg end length)
1169 (save-excursion
1170 (goto-char beg)
1171 (let* ((line-beg (line-beginning-position))
1172 (m (get-text-property line-beg 'occur-target))
1173 (buf (marker-buffer m))
1174 col)
1175 (when (and (get-text-property line-beg 'occur-prefix)
1176 (not (get-text-property end 'occur-prefix)))
1177 (when (= length 0)
1178 ;; Apply occur-target property to inserted (e.g. yanked) text.
1179 (put-text-property beg end 'occur-target m)
1180 ;; Did we insert a newline? Occur Edit mode can't create new
1181 ;; Occur entries; just discard everything after the newline.
1182 (save-excursion
1183 (and (search-forward "\n" end t)
1184 (delete-region (1- (point)) end))))
1185 (let* ((line (- (line-number-at-pos)
1186 (line-number-at-pos (window-start))))
1187 (readonly (with-current-buffer buf buffer-read-only))
1188 (win (or (get-buffer-window buf)
1189 (display-buffer buf
1190 '(nil (inhibit-same-window . t)
1191 (inhibit-switch-frame . t)))))
1192 (line-end (line-end-position))
1193 (text (save-excursion
1194 (goto-char (next-single-property-change
1195 line-beg 'occur-prefix nil
1196 line-end))
1197 (setq col (- (point) line-beg))
1198 (buffer-substring-no-properties (point) line-end))))
1199 (with-selected-window win
1200 (goto-char m)
1201 (recenter line)
1202 (if readonly
1203 (message "Buffer `%s' is read only." buf)
1204 (delete-region (line-beginning-position) (line-end-position))
1205 (insert text))
1206 (move-to-column col)))))))
1209 (defun occur--parse-occur-buffer()
1210 "Retrieve a list of the form (BEG END ORIG-LINE BUFFER).
1211 BEG and END define the region.
1212 ORIG-LINE and BUFFER are the line and the buffer from which
1213 the user called `occur'."
1214 (save-excursion
1215 (goto-char (point-min))
1216 (let ((buffer (get-text-property (point) 'occur-title))
1217 (beg-pos (get-text-property (point) 'region-start))
1218 (end-pos (get-text-property (point) 'region-end))
1219 (orig-line (get-text-property (point) 'current-line)))
1220 (list beg-pos end-pos orig-line buffer))))
1222 (defun occur-revert-function (_ignore1 _ignore2)
1223 "Handle `revert-buffer' for Occur mode buffers."
1224 (if (cdr (nth 2 occur-revert-arguments)) ; multi-occur
1225 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name))))
1226 (pcase-let ((`(,region-start ,region-end ,orig-line ,buffer)
1227 (occur--parse-occur-buffer))
1228 (regexp (car occur-revert-arguments)))
1229 (with-current-buffer buffer
1230 (when (wholenump orig-line)
1231 (goto-char (point-min))
1232 (forward-line (1- orig-line)))
1233 (save-excursion
1234 (if (or region-start region-end)
1235 (occur regexp nil (list (cons region-start region-end)))
1236 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name))))))))))
1238 (defun occur-mode-find-occurrence ()
1239 (let ((pos (get-text-property (point) 'occur-target)))
1240 (unless pos
1241 (error "No occurrence on this line"))
1242 (unless (buffer-live-p (marker-buffer pos))
1243 (error "Buffer for this occurrence was killed"))
1244 pos))
1246 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1247 (defun occur-mode-goto-occurrence (&optional event)
1248 "Go to the occurrence on the current line."
1249 (interactive (list last-nonmenu-event))
1250 (let ((buffer (when event (current-buffer)))
1251 (pos
1252 (if (null event)
1253 ;; Actually `event-end' works correctly with a nil argument as
1254 ;; well, so we could dispense with this test, but let's not
1255 ;; rely on this undocumented behavior.
1256 (occur-mode-find-occurrence)
1257 (with-current-buffer (window-buffer (posn-window (event-end event)))
1258 (save-excursion
1259 (goto-char (posn-point (event-end event)))
1260 (occur-mode-find-occurrence))))))
1261 (pop-to-buffer (marker-buffer pos))
1262 (goto-char pos)
1263 (when buffer (next-error-found buffer (current-buffer)))
1264 (run-hooks 'occur-mode-find-occurrence-hook)))
1266 (defun occur-mode-goto-occurrence-other-window ()
1267 "Go to the occurrence the current line describes, in another window."
1268 (interactive)
1269 (let ((buffer (current-buffer))
1270 (pos (occur-mode-find-occurrence)))
1271 (switch-to-buffer-other-window (marker-buffer pos))
1272 (goto-char pos)
1273 (next-error-found buffer (current-buffer))
1274 (run-hooks 'occur-mode-find-occurrence-hook)))
1276 (defun occur-mode-display-occurrence ()
1277 "Display in another window the occurrence the current line describes."
1278 (interactive)
1279 (let ((buffer (current-buffer))
1280 (pos (occur-mode-find-occurrence))
1281 window)
1282 (setq window (display-buffer (marker-buffer pos) t))
1283 ;; This is the way to set point in the proper window.
1284 (save-selected-window
1285 (select-window window)
1286 (goto-char pos)
1287 (next-error-found buffer (current-buffer))
1288 (run-hooks 'occur-mode-find-occurrence-hook))))
1290 (defun occur-find-match (n search message)
1291 (if (not n) (setq n 1))
1292 (let ((r))
1293 (while (> n 0)
1294 (setq r (funcall search (point) 'occur-match))
1295 (and r
1296 (get-text-property r 'occur-match)
1297 (setq r (funcall search r 'occur-match)))
1298 (if r
1299 (goto-char r)
1300 (user-error message))
1301 (setq n (1- n)))))
1303 (defun occur-next (&optional n)
1304 "Move to the Nth (default 1) next match in an Occur mode buffer."
1305 (interactive "p")
1306 (occur-find-match n #'next-single-property-change "No more matches"))
1308 (defun occur-prev (&optional n)
1309 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1310 (interactive "p")
1311 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1313 (defun occur-next-error (&optional argp reset)
1314 "Move to the Nth (default 1) next match in an Occur mode buffer.
1315 Compatibility function for \\[next-error] invocations."
1316 (interactive "p")
1317 (goto-char (cond (reset (point-min))
1318 ((< argp 0) (line-beginning-position))
1319 ((> argp 0) (line-end-position))
1320 ((point))))
1321 (occur-find-match
1322 (abs argp)
1323 (if (> 0 argp)
1324 #'previous-single-property-change
1325 #'next-single-property-change)
1326 "No more matches")
1327 ;; In case the *Occur* buffer is visible in a nonselected window.
1328 (let ((win (get-buffer-window (current-buffer) t)))
1329 (if win (set-window-point win (point))))
1330 (occur-mode-goto-occurrence))
1332 (defface match
1333 '((((class color) (min-colors 88) (background light))
1334 :background "yellow1")
1335 (((class color) (min-colors 88) (background dark))
1336 :background "RoyalBlue3")
1337 (((class color) (min-colors 8) (background light))
1338 :background "yellow" :foreground "black")
1339 (((class color) (min-colors 8) (background dark))
1340 :background "blue" :foreground "white")
1341 (((type tty) (class mono))
1342 :inverse-video t)
1343 (t :background "gray"))
1344 "Face used to highlight matches permanently."
1345 :group 'matching
1346 :group 'basic-faces
1347 :version "22.1")
1349 (defcustom list-matching-lines-default-context-lines 0
1350 "Default number of context lines included around `list-matching-lines' matches.
1351 A negative number means to include that many lines before the match.
1352 A positive number means to include that many lines both before and after."
1353 :type 'integer
1354 :group 'matching)
1356 (defalias 'list-matching-lines 'occur)
1358 (defcustom list-matching-lines-face 'match
1359 "Face used by \\[list-matching-lines] to show the text that matches.
1360 If the value is nil, don't highlight the matching portions specially."
1361 :type 'face
1362 :group 'matching)
1364 (defcustom list-matching-lines-buffer-name-face 'underline
1365 "Face used by \\[list-matching-lines] to show the names of buffers.
1366 If the value is nil, don't highlight the buffer names specially."
1367 :type 'face
1368 :group 'matching)
1370 (defcustom list-matching-lines-current-line-face 'lazy-highlight
1371 "Face used by \\[list-matching-lines] to highlight the current line."
1372 :type 'face
1373 :group 'matching
1374 :version "26.1")
1376 (defcustom list-matching-lines-jump-to-current-line nil
1377 "If non-nil, \\[list-matching-lines] shows the current line highlighted.
1378 Set the point right after such line when there are matches after it."
1379 :type 'boolean
1380 :group 'matching
1381 :version "26.1")
1383 (defcustom list-matching-lines-prefix-face 'shadow
1384 "Face used by \\[list-matching-lines] to show the prefix column.
1385 If the face doesn't differ from the default face,
1386 don't highlight the prefix with line numbers specially."
1387 :type 'face
1388 :group 'matching
1389 :version "24.4")
1391 (defcustom occur-excluded-properties
1392 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1393 yank-handler follow-link)
1394 "Text properties to discard when copying lines to the *Occur* buffer.
1395 The value should be a list of text properties to discard or t,
1396 which means to discard all text properties."
1397 :type '(choice (const :tag "All" t) (repeat symbol))
1398 :group 'matching
1399 :version "22.1")
1401 (defun occur-read-primary-args ()
1402 (let* ((perform-collect (consp current-prefix-arg))
1403 (regexp (read-regexp (if perform-collect
1404 "Collect strings matching regexp"
1405 "List lines matching regexp")
1406 'regexp-history-last)))
1407 (list regexp
1408 (if perform-collect
1409 ;; Perform collect operation
1410 (if (zerop (regexp-opt-depth regexp))
1411 ;; No subexpression so collect the entire match.
1412 "\\&"
1413 ;; Get the regexp for collection pattern.
1414 (let ((default (car occur-collect-regexp-history)))
1415 (read-regexp
1416 (format "Regexp to collect (default %s): " default)
1417 default 'occur-collect-regexp-history)))
1418 ;; Otherwise normal occur takes numerical prefix argument.
1419 (when current-prefix-arg
1420 (prefix-numeric-value current-prefix-arg))))))
1422 (defun occur-rename-buffer (&optional unique-p interactive-p)
1423 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1424 Here `original-buffer-name' is the buffer name where Occur was originally run.
1425 When given the prefix argument, or called non-interactively, the renaming
1426 will not clobber the existing buffer(s) of that name, but use
1427 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1428 if you always want a separate *Occur* buffer for each buffer where you
1429 invoke `occur'."
1430 (interactive "P\np")
1431 (with-current-buffer
1432 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1433 (rename-buffer (concat "*Occur: "
1434 (mapconcat #'buffer-name
1435 (car (cddr occur-revert-arguments)) "/")
1436 "*")
1437 (or unique-p (not interactive-p)))))
1439 ;; Region limits when `occur' applies on a region.
1440 (defvar occur--region-start nil)
1441 (defvar occur--region-end nil)
1442 (defvar occur--region-start-line nil)
1443 (defvar occur--orig-line nil)
1444 (defvar occur--final-pos nil)
1446 (defun occur (regexp &optional nlines region)
1447 "Show all lines in the current buffer containing a match for REGEXP.
1448 If a match spreads across multiple lines, all those lines are shown.
1450 Each match is extended to include complete lines. Only non-overlapping
1451 matches are considered. (Note that extending matches to complete
1452 lines could cause some of the matches to overlap; if so, they will not
1453 be shown as separate matches.)
1455 Each line is displayed with NLINES lines before and after, or -NLINES
1456 before if NLINES is negative.
1457 NLINES defaults to `list-matching-lines-default-context-lines'.
1458 Interactively it is the prefix arg.
1460 Optional arg REGION, if non-nil, mean restrict search to the
1461 specified region. Otherwise search the entire buffer.
1462 REGION must be a list of (START . END) positions as returned by
1463 `region-bounds'.
1465 The lines are shown in a buffer named `*Occur*'.
1466 It serves as a menu to find any of the occurrences in this buffer.
1467 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1468 If `list-matching-lines-jump-to-current-line' is non-nil, then show
1469 the current line highlighted with `list-matching-lines-current-line-face'
1470 and set point at the first match after such line.
1472 If REGEXP contains upper case characters (excluding those preceded by `\\')
1473 and `search-upper-case' is non-nil, the matching is case-sensitive.
1475 When NLINES is a string or when the function is called
1476 interactively with prefix argument without a number (`C-u' alone
1477 as prefix) the matching strings are collected into the `*Occur*'
1478 buffer by using NLINES as a replacement regexp. NLINES may
1479 contain \\& and \\N which convention follows `replace-match'.
1480 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1481 \"\\1\" for NLINES collects all the function names in a lisp
1482 program. When there is no parenthesized subexpressions in REGEXP
1483 the entire match is collected. In any case the searched buffer
1484 is not modified."
1485 (interactive
1486 (nconc (occur-read-primary-args)
1487 (and (use-region-p) (list (region-bounds)))))
1488 (let* ((start (and (caar region) (max (caar region) (point-min))))
1489 (end (and (cdar region) (min (cdar region) (point-max))))
1490 (in-region-p (or start end)))
1491 (when in-region-p
1492 (or start (setq start (point-min)))
1493 (or end (setq end (point-max))))
1494 (let ((occur--region-start start)
1495 (occur--region-end end)
1496 (occur--region-start-line
1497 (and in-region-p
1498 (line-number-at-pos (min start end))))
1499 (occur--orig-line
1500 (line-number-at-pos (point))))
1501 (save-excursion ; If no matches `occur-1' doesn't restore the point.
1502 (and in-region-p (narrow-to-region
1503 (save-excursion (goto-char start) (line-beginning-position))
1504 (save-excursion (goto-char end) (line-end-position))))
1505 (occur-1 regexp nlines (list (current-buffer)))
1506 (and in-region-p (widen))))))
1508 (defvar ido-ignore-item-temp-list)
1510 (defun multi-occur (bufs regexp &optional nlines)
1511 "Show all lines in buffers BUFS containing a match for REGEXP.
1512 This function acts on multiple buffers; otherwise, it is exactly like
1513 `occur'. When you invoke this command interactively, you must specify
1514 the buffer names that you want, one by one.
1515 See also `multi-occur-in-matching-buffers'."
1516 (interactive
1517 (cons
1518 (let* ((bufs (list (read-buffer "First buffer to search: "
1519 (current-buffer) t)))
1520 (buf nil)
1521 (ido-ignore-item-temp-list bufs))
1522 (while (not (string-equal
1523 (setq buf (read-buffer
1524 (if (eq read-buffer-function #'ido-read-buffer)
1525 "Next buffer to search (C-j to end): "
1526 "Next buffer to search (RET to end): ")
1527 nil t))
1528 ""))
1529 (cl-pushnew buf bufs)
1530 (setq ido-ignore-item-temp-list bufs))
1531 (nreverse (mapcar #'get-buffer bufs)))
1532 (occur-read-primary-args)))
1533 (occur-1 regexp nlines bufs))
1535 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1536 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1537 Normally BUFREGEXP matches against each buffer's visited file name,
1538 but if you specify a prefix argument, it matches against the buffer name.
1539 See also `multi-occur'."
1540 (interactive
1541 (cons
1542 (let* ((default (car regexp-history))
1543 (input
1544 (read-regexp
1545 (if current-prefix-arg
1546 "List lines in buffers whose names match regexp: "
1547 "List lines in buffers whose filenames match regexp: "))))
1548 (if (equal input "")
1549 default
1550 input))
1551 (occur-read-primary-args)))
1552 (when bufregexp
1553 (occur-1 regexp nil
1554 (delq nil
1555 (mapcar (lambda (buf)
1556 (when (if allbufs
1557 (string-match bufregexp
1558 (buffer-name buf))
1559 (and (buffer-file-name buf)
1560 (string-match bufregexp
1561 (buffer-file-name buf))))
1562 buf))
1563 (buffer-list))))))
1565 (defun occur-regexp-descr (regexp)
1566 (format " for %s\"%s\""
1567 (or (get-text-property 0 'isearch-regexp-function-descr regexp)
1569 (if (get-text-property 0 'isearch-string regexp)
1570 (propertize
1571 (query-replace-descr
1572 (get-text-property 0 'isearch-string regexp))
1573 'help-echo regexp)
1574 (query-replace-descr regexp))))
1576 (defun occur-1 (regexp nlines bufs &optional buf-name)
1577 (unless (and regexp (not (equal regexp "")))
1578 (error "Occur doesn't work with the empty regexp"))
1579 (unless buf-name
1580 (setq buf-name "*Occur*"))
1581 (let (occur-buf
1582 (active-bufs (delq nil (mapcar #'(lambda (buf)
1583 (when (buffer-live-p buf) buf))
1584 bufs))))
1585 ;; Handle the case where one of the buffers we're searching is the
1586 ;; output buffer. Just rename it.
1587 (when (member buf-name (mapcar 'buffer-name active-bufs))
1588 (with-current-buffer (get-buffer buf-name)
1589 (rename-uniquely)))
1591 ;; Now find or create the output buffer.
1592 ;; If we just renamed that buffer, we will make a new one here.
1593 (setq occur-buf (get-buffer-create buf-name))
1595 (with-current-buffer occur-buf
1596 (if (stringp nlines)
1597 (fundamental-mode) ;; This is for collect operation.
1598 (occur-mode))
1599 (let ((inhibit-read-only t)
1600 ;; Don't generate undo entries for creation of the initial contents.
1601 (buffer-undo-list t)
1602 (occur--final-pos nil))
1603 (erase-buffer)
1604 (let ((count
1605 (if (stringp nlines)
1606 ;; Treat nlines as a regexp to collect.
1607 (let ((bufs active-bufs)
1608 (count 0))
1609 (while bufs
1610 (with-current-buffer (car bufs)
1611 (save-excursion
1612 (goto-char (point-min))
1613 (while (re-search-forward regexp nil t)
1614 ;; Insert the replacement regexp.
1615 (let ((str (match-substitute-replacement nlines)))
1616 (if str
1617 (with-current-buffer occur-buf
1618 (insert str)
1619 (setq count (1+ count))
1620 (or (zerop (current-column))
1621 (insert "\n"))))))))
1622 (setq bufs (cdr bufs)))
1623 count)
1624 ;; Perform normal occur.
1625 (occur-engine
1626 regexp active-bufs occur-buf
1627 (or nlines list-matching-lines-default-context-lines)
1628 (if (and case-fold-search search-upper-case)
1629 (isearch-no-upper-case-p regexp t)
1630 case-fold-search)
1631 list-matching-lines-buffer-name-face
1632 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1633 list-matching-lines-prefix-face)
1634 list-matching-lines-face
1635 (not (eq occur-excluded-properties t))))))
1636 (let* ((bufcount (length active-bufs))
1637 (diff (- (length bufs) bufcount)))
1638 (message "Searched %d buffer%s%s; %s match%s%s"
1639 bufcount (if (= bufcount 1) "" "s")
1640 (if (zerop diff) "" (format " (%d killed)" diff))
1641 (if (zerop count) "no" (format "%d" count))
1642 (if (= count 1) "" "es")
1643 ;; Don't display regexp if with remaining text
1644 ;; it is longer than window-width.
1645 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp)
1646 regexp))
1648 (window-width))
1649 "" (occur-regexp-descr regexp))))
1650 (setq occur-revert-arguments (list regexp nlines bufs))
1651 (if (= count 0)
1652 (kill-buffer occur-buf)
1653 (display-buffer occur-buf)
1654 (when occur--final-pos
1655 (set-window-point
1656 (get-buffer-window occur-buf 'all-frames)
1657 occur--final-pos))
1658 (setq next-error-last-buffer occur-buf)
1659 (setq buffer-read-only t)
1660 (set-buffer-modified-p nil)
1661 (run-hooks 'occur-hook)))))))
1663 (defun occur-engine (regexp buffers out-buf nlines case-fold
1664 title-face prefix-face match-face keep-props)
1665 (with-current-buffer out-buf
1666 (let ((global-lines 0) ;; total count of matching lines
1667 (global-matches 0) ;; total count of matches
1668 (coding nil)
1669 (case-fold-search case-fold)
1670 (in-region-p (and occur--region-start occur--region-end))
1671 (multi-occur-p (cdr buffers)))
1672 ;; Map over all the buffers
1673 (dolist (buf buffers)
1674 (when (buffer-live-p buf)
1675 (let ((lines 0) ;; count of matching lines
1676 (matches 0) ;; count of matches
1677 (curr-line ;; line count
1678 (or occur--region-start-line 1))
1679 (orig-line (or occur--orig-line 1))
1680 (orig-line-shown-p)
1681 (prev-line nil) ;; line number of prev match endpt
1682 (prev-after-lines nil) ;; context lines of prev match
1683 (matchbeg 0)
1684 (origpt nil)
1685 (begpt nil)
1686 (endpt nil)
1687 (marker nil)
1688 (curstring "")
1689 (ret nil)
1690 (inhibit-field-text-motion t)
1691 (headerpt (with-current-buffer out-buf (point))))
1692 (with-current-buffer buf
1693 ;; The following binding is for when case-fold-search
1694 ;; has a local binding in the original buffer, in which
1695 ;; case we cannot bind it globally and let that have
1696 ;; effect in every buffer we search.
1697 (let ((case-fold-search case-fold))
1698 (or coding
1699 ;; Set CODING only if the current buffer locally
1700 ;; binds buffer-file-coding-system.
1701 (not (local-variable-p 'buffer-file-coding-system))
1702 (setq coding buffer-file-coding-system))
1703 (save-excursion
1704 (goto-char (point-min)) ;; begin searching in the buffer
1705 (while (not (eobp))
1706 (setq origpt (point))
1707 (when (setq endpt (re-search-forward regexp nil t))
1708 (setq lines (1+ lines)) ;; increment matching lines count
1709 (setq matchbeg (match-beginning 0))
1710 ;; Get beginning of first match line and end of the last.
1711 (save-excursion
1712 (goto-char matchbeg)
1713 (setq begpt (line-beginning-position))
1714 (goto-char endpt)
1715 (setq endpt (line-end-position)))
1716 ;; Sum line numbers up to the first match line.
1717 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1718 (setq marker (make-marker))
1719 (set-marker marker matchbeg)
1720 (setq curstring (occur-engine-line begpt endpt keep-props))
1721 ;; Highlight the matches
1722 (let ((len (length curstring))
1723 (start 0))
1724 ;; Count empty lines that don't use next loop (Bug#22062).
1725 (when (zerop len)
1726 (setq matches (1+ matches)))
1727 (when (and list-matching-lines-jump-to-current-line
1728 (not multi-occur-p))
1729 (or orig-line (setq orig-line 1))
1730 (or nlines (setq nlines (line-number-at-pos (point-max))))
1731 (when (= curr-line orig-line)
1732 (add-face-text-property
1733 0 len list-matching-lines-current-line-face nil curstring)
1734 (add-text-properties 0 len '(current-line t) curstring))
1735 (when (and (>= orig-line (- curr-line nlines))
1736 (<= orig-line (+ curr-line nlines)))
1737 ;; Shown either here or will be shown by occur-context-lines
1738 (setq orig-line-shown-p t)))
1739 (while (and (< start len)
1740 (string-match regexp curstring start))
1741 (setq matches (1+ matches))
1742 (add-text-properties
1743 (match-beginning 0) (match-end 0)
1744 '(occur-match t) curstring)
1745 (when match-face
1746 ;; Add `match-face' to faces copied from the buffer.
1747 (add-face-text-property
1748 (match-beginning 0) (match-end 0)
1749 match-face nil curstring))
1750 ;; Avoid infloop (Bug#7593).
1751 (let ((end (match-end 0)))
1752 (setq start (if (= start end) (1+ start) end)))))
1753 ;; Generate the string to insert for this match
1754 (let* ((match-prefix
1755 ;; Using 7 digits aligns tabs properly.
1756 (apply #'propertize (format "%7d:" curr-line)
1757 (append
1758 (when prefix-face
1759 `(font-lock-face ,prefix-face))
1760 `(occur-prefix t mouse-face (highlight)
1761 ;; Allow insertion of text
1762 ;; at the end of the prefix
1763 ;; (for Occur Edit mode).
1764 front-sticky t
1765 rear-nonsticky t
1766 occur-target ,marker
1767 follow-link t
1768 help-echo "mouse-2: go to this occurrence"))))
1769 (match-str
1770 ;; We don't put `mouse-face' on the newline,
1771 ;; because that loses. And don't put it
1772 ;; on context lines to reduce flicker.
1773 (propertize curstring 'mouse-face (list 'highlight)
1774 'occur-target marker
1775 'follow-link t
1776 'help-echo
1777 "mouse-2: go to this occurrence"))
1778 (out-line
1779 (concat
1780 match-prefix
1781 ;; Add non-numeric prefix to all non-first lines
1782 ;; of multi-line matches.
1783 (replace-regexp-in-string
1784 "\n"
1785 (if prefix-face
1786 (propertize
1787 "\n :" 'font-lock-face prefix-face)
1788 "\n :")
1789 match-str)
1790 ;; Add marker at eol, but no mouse props.
1791 (propertize "\n" 'occur-target marker)))
1792 (data
1793 (if (= nlines 0)
1794 ;; The simple display style
1795 out-line
1796 ;; The complex multi-line display style.
1797 (setq ret (occur-context-lines
1798 out-line nlines keep-props begpt
1799 endpt curr-line prev-line
1800 prev-after-lines prefix-face
1801 orig-line multi-occur-p))
1802 ;; Set first elem of the returned list to `data',
1803 ;; and the second elem to `prev-after-lines'.
1804 (setq prev-after-lines (nth 1 ret))
1805 (nth 0 ret)))
1806 (orig-line-str
1807 (when (and list-matching-lines-jump-to-current-line
1808 (null orig-line-shown-p)
1809 (> curr-line orig-line))
1810 (setq orig-line-shown-p t)
1811 (save-excursion
1812 (goto-char (point-min))
1813 (forward-line (- orig-line (or occur--region-start-line 1)))
1814 (occur-engine-line (line-beginning-position)
1815 (line-end-position) keep-props)))))
1816 ;; Actually insert the match display data
1817 (with-current-buffer out-buf
1818 (when orig-line-str
1819 (add-face-text-property
1820 0 (length orig-line-str)
1821 list-matching-lines-current-line-face nil orig-line-str)
1822 (add-text-properties 0 (length orig-line-str)
1823 '(current-line t) orig-line-str)
1824 (insert (car (occur-engine-add-prefix
1825 (list orig-line-str) prefix-face))))
1826 (insert data)))
1827 (goto-char endpt))
1828 (if endpt
1829 (progn
1830 ;; Sum line numbers between first and last match lines.
1831 (setq curr-line (+ curr-line (count-lines begpt endpt)
1832 ;; Add 1 for empty last match line
1833 ;; since count-lines returns one
1834 ;; line less.
1835 (if (and (bolp) (eolp)) 1 0)))
1836 ;; On to the next match...
1837 (forward-line 1))
1838 (goto-char (point-max)))
1839 (setq prev-line (1- curr-line)))
1840 ;; Flush remaining context after-lines.
1841 (when prev-after-lines
1842 (with-current-buffer out-buf
1843 (insert (apply #'concat (occur-engine-add-prefix
1844 prev-after-lines prefix-face)))))
1845 (when (and list-matching-lines-jump-to-current-line
1846 (null orig-line-shown-p))
1847 (setq orig-line-shown-p t)
1848 (let ((orig-line-str
1849 (save-excursion
1850 (goto-char (point-min))
1851 (forward-line (- orig-line (or occur--region-start-line 1)))
1852 (occur-engine-line (line-beginning-position)
1853 (line-end-position) keep-props))))
1854 (add-face-text-property
1855 0 (length orig-line-str)
1856 list-matching-lines-current-line-face nil orig-line-str)
1857 (add-text-properties 0 (length orig-line-str)
1858 '(current-line t) orig-line-str)
1859 (with-current-buffer out-buf
1860 (insert (car (occur-engine-add-prefix
1861 (list orig-line-str) prefix-face))))))))
1862 (when (not (zerop lines)) ;; is the count zero?
1863 (setq global-lines (+ global-lines lines)
1864 global-matches (+ global-matches matches))
1865 (with-current-buffer out-buf
1866 (goto-char headerpt)
1867 (let ((beg (point))
1868 end)
1869 (insert (propertize
1870 (format "%d match%s%s%s in buffer: %s%s\n"
1871 matches (if (= matches 1) "" "es")
1872 ;; Don't display the same number of lines
1873 ;; and matches in case of 1 match per line.
1874 (if (= lines matches)
1875 "" (format " in %d line%s"
1876 lines
1877 (if (= lines 1) "" "s")))
1878 ;; Don't display regexp for multi-buffer.
1879 (if (> (length buffers) 1)
1880 "" (occur-regexp-descr regexp))
1881 (buffer-name buf)
1882 (if in-region-p
1883 (format " within region: %d-%d"
1884 occur--region-start
1885 occur--region-end)
1886 ""))
1887 'read-only t))
1888 (setq end (point))
1889 (add-text-properties beg end `(occur-title ,buf current-line ,orig-line
1890 region-start ,occur--region-start
1891 region-end ,occur--region-end))
1892 (when title-face
1893 (add-face-text-property beg end title-face))
1894 (goto-char (if (and list-matching-lines-jump-to-current-line
1895 (not multi-occur-p))
1896 (setq occur--final-pos
1897 (and (goto-char (point-max))
1898 (or (previous-single-property-change (point) 'current-line)
1899 (point-max))))
1900 (point-min))))))))))
1901 ;; Display total match count and regexp for multi-buffer.
1902 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1903 (goto-char (point-min))
1904 (let ((beg (point))
1905 end)
1906 (insert (format "%d match%s%s total%s:\n"
1907 global-matches (if (= global-matches 1) "" "es")
1908 ;; Don't display the same number of lines
1909 ;; and matches in case of 1 match per line.
1910 (if (= global-lines global-matches)
1911 "" (format " in %d line%s"
1912 global-lines (if (= global-lines 1) "" "s")))
1913 (occur-regexp-descr regexp)))
1914 (setq end (point))
1915 (when title-face
1916 (add-face-text-property beg end title-face)))
1917 (goto-char (point-min)))
1918 (if coding
1919 ;; CODING is buffer-file-coding-system of the first buffer
1920 ;; that locally binds it. Let's use it also for the output
1921 ;; buffer.
1922 (set-buffer-file-coding-system coding))
1923 ;; Return the number of matches
1924 global-matches)))
1926 (defun occur-engine-line (beg end &optional keep-props)
1927 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1928 (text-property-not-all beg end 'fontified t))
1929 (if (fboundp 'jit-lock-fontify-now)
1930 (jit-lock-fontify-now beg end)))
1931 (if (and keep-props (not (eq occur-excluded-properties t)))
1932 (let ((str (buffer-substring beg end)))
1933 (remove-list-of-text-properties
1934 0 (length str) occur-excluded-properties str)
1935 str)
1936 (buffer-substring-no-properties beg end)))
1938 (defun occur-engine-add-prefix (lines &optional prefix-face)
1939 (mapcar
1940 #'(lambda (line)
1941 (concat (if prefix-face
1942 (propertize " :" 'font-lock-face prefix-face)
1943 " :")
1944 line "\n"))
1945 lines))
1947 (defun occur-accumulate-lines (count &optional keep-props pt)
1948 (save-excursion
1949 (when pt
1950 (goto-char pt))
1951 (let ((forwardp (> count 0))
1952 result beg end moved)
1953 (while (not (or (zerop count)
1954 (if forwardp
1955 (eobp)
1956 (and (bobp) (not moved)))))
1957 (setq count (+ count (if forwardp -1 1)))
1958 (setq beg (line-beginning-position)
1959 end (line-end-position))
1960 (push (occur-engine-line beg end keep-props) result)
1961 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1962 (nreverse result))))
1964 ;; Generate context display for occur.
1965 ;; OUT-LINE is the line where the match is.
1966 ;; NLINES and KEEP-PROPS are args to occur-engine.
1967 ;; CURR-LINE is line count of the current match,
1968 ;; PREV-LINE is line count of the previous match,
1969 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1970 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1971 ;; then concatenate them all together.
1972 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1973 curr-line prev-line prev-after-lines
1974 &optional prefix-face
1975 orig-line multi-occur-p)
1976 ;; Find after- and before-context lines of the current match.
1977 (let ((before-lines
1978 (nreverse (cdr (occur-accumulate-lines
1979 (- (1+ (abs nlines))) keep-props begpt))))
1980 (after-lines
1981 (cdr (occur-accumulate-lines
1982 (1+ nlines) keep-props endpt)))
1983 separator)
1985 (when (and list-matching-lines-jump-to-current-line
1986 (not multi-occur-p))
1987 (when (and (>= orig-line (- curr-line nlines))
1988 (< orig-line curr-line))
1989 (let ((curstring (nth (- (length before-lines) (- curr-line orig-line)) before-lines)))
1990 (add-face-text-property
1991 0 (length curstring)
1992 list-matching-lines-current-line-face nil curstring)
1993 (add-text-properties 0 (length curstring)
1994 '(current-line t) curstring)))
1995 (when (and (<= orig-line (+ curr-line nlines))
1996 (> orig-line curr-line))
1997 (let ((curstring (nth (- orig-line curr-line 1) after-lines)))
1998 (add-face-text-property
1999 0 (length curstring)
2000 list-matching-lines-current-line-face nil curstring)
2001 (add-text-properties 0 (length curstring)
2002 '(current-line t) curstring))))
2004 ;; Combine after-lines of the previous match
2005 ;; with before-lines of the current match.
2007 (when prev-after-lines
2008 ;; Don't overlap prev after-lines with current before-lines.
2009 (if (>= (+ prev-line (length prev-after-lines))
2010 (- curr-line (length before-lines)))
2011 (setq prev-after-lines
2012 (butlast prev-after-lines
2013 (- (length prev-after-lines)
2014 (- curr-line prev-line (length before-lines) 1))))
2015 ;; Separate non-overlapping context lines with a dashed line.
2016 (setq separator "-------\n")))
2018 (when prev-line
2019 ;; Don't overlap current before-lines with previous match line.
2020 (if (<= (- curr-line (length before-lines))
2021 prev-line)
2022 (setq before-lines
2023 (nthcdr (- (length before-lines)
2024 (- curr-line prev-line 1))
2025 before-lines))
2026 ;; Separate non-overlapping before-context lines.
2027 (unless (> nlines 0)
2028 (setq separator "-------\n"))))
2030 (list
2031 ;; Return a list where the first element is the output line.
2032 (apply #'concat
2033 (append
2034 (if prev-after-lines
2035 (occur-engine-add-prefix prev-after-lines prefix-face))
2036 (if separator
2037 (list (if prefix-face
2038 (propertize separator 'font-lock-face prefix-face)
2039 separator)))
2040 (occur-engine-add-prefix before-lines prefix-face)
2041 (list out-line)))
2042 ;; And the second element is the list of context after-lines.
2043 (if (> nlines 0) after-lines))))
2046 ;; It would be nice to use \\[...], but there is no reasonable way
2047 ;; to make that display both SPC and Y.
2048 (defconst query-replace-help
2049 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
2050 RET or `q' to exit, Period to replace one match and exit,
2051 Comma to replace but not move point immediately,
2052 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
2053 C-w to delete match and recursive edit,
2054 C-l to clear the screen, redisplay, and offer same replacement again,
2055 ! to replace all remaining matches in this buffer with no more questions,
2056 ^ to move point back to previous match,
2057 u to undo previous replacement,
2058 U to undo all replacements,
2059 E to edit the replacement string.
2060 In multi-buffer replacements type `Y' to replace all remaining
2061 matches in all remaining buffers with no more questions,
2062 `N' to skip to the next buffer without replacing remaining matches
2063 in the current buffer."
2064 "Help message while in `query-replace'.")
2066 (defvar query-replace-map
2067 (let ((map (make-sparse-keymap)))
2068 (define-key map " " 'act)
2069 (define-key map "\d" 'skip)
2070 (define-key map [delete] 'skip)
2071 (define-key map [backspace] 'skip)
2072 (define-key map "y" 'act)
2073 (define-key map "n" 'skip)
2074 (define-key map "Y" 'act)
2075 (define-key map "N" 'skip)
2076 (define-key map "e" 'edit-replacement)
2077 (define-key map "E" 'edit-replacement)
2078 (define-key map "," 'act-and-show)
2079 (define-key map "q" 'exit)
2080 (define-key map "\r" 'exit)
2081 (define-key map [return] 'exit)
2082 (define-key map "." 'act-and-exit)
2083 (define-key map "\C-r" 'edit)
2084 (define-key map "\C-w" 'delete-and-edit)
2085 (define-key map "\C-l" 'recenter)
2086 (define-key map "!" 'automatic)
2087 (define-key map "^" 'backup)
2088 (define-key map "u" 'undo)
2089 (define-key map "U" 'undo-all)
2090 (define-key map "\C-h" 'help)
2091 (define-key map [f1] 'help)
2092 (define-key map [help] 'help)
2093 (define-key map "?" 'help)
2094 (define-key map "\C-g" 'quit)
2095 (define-key map "\C-]" 'quit)
2096 (define-key map "\C-v" 'scroll-up)
2097 (define-key map "\M-v" 'scroll-down)
2098 (define-key map [next] 'scroll-up)
2099 (define-key map [prior] 'scroll-down)
2100 (define-key map [?\C-\M-v] 'scroll-other-window)
2101 (define-key map [M-next] 'scroll-other-window)
2102 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
2103 (define-key map [M-prior] 'scroll-other-window-down)
2104 ;; Binding ESC would prohibit the M-v binding. Instead, callers
2105 ;; should check for ESC specially.
2106 ;; (define-key map "\e" 'exit-prefix)
2107 (define-key map [escape] 'exit-prefix)
2108 map)
2109 "Keymap of responses to questions posed by commands like `query-replace'.
2110 The \"bindings\" in this map are not commands; they are answers.
2111 The valid answers include `act', `skip', `act-and-show',
2112 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
2113 `scroll-down', `scroll-other-window', `scroll-other-window-down',
2114 `edit', `edit-replacement', `delete-and-edit', `automatic',
2115 `backup', `undo', `undo-all', `quit', and `help'.
2117 This keymap is used by `y-or-n-p' as well as `query-replace'.")
2119 (defvar multi-query-replace-map
2120 (let ((map (make-sparse-keymap)))
2121 (set-keymap-parent map query-replace-map)
2122 (define-key map "Y" 'automatic-all)
2123 (define-key map "N" 'exit-current)
2124 map)
2125 "Keymap that defines additional bindings for multi-buffer replacements.
2126 It extends its parent map `query-replace-map' with new bindings to
2127 operate on a set of buffers/files. The difference with its parent map
2128 is the additional answers `automatic-all' to replace all remaining
2129 matches in all remaining buffers with no more questions, and
2130 `exit-current' to skip remaining matches in the current buffer
2131 and to continue with the next buffer in the sequence.")
2133 (defun replace-match-string-symbols (n)
2134 "Process a list (and any sub-lists), expanding certain symbols.
2135 Symbol Expands To
2136 N (match-string N) (where N is a string of digits)
2137 #N (string-to-number (match-string N))
2138 & (match-string 0)
2139 #& (string-to-number (match-string 0))
2140 # replace-count
2142 Note that these symbols must be preceded by a backslash in order to
2143 type them using Lisp syntax."
2144 (while (consp n)
2145 (cond
2146 ((consp (car n))
2147 (replace-match-string-symbols (car n))) ;Process sub-list
2148 ((symbolp (car n))
2149 (let ((name (symbol-name (car n))))
2150 (cond
2151 ((string-match "^[0-9]+$" name)
2152 (setcar n (list 'match-string (string-to-number name))))
2153 ((string-match "^#[0-9]+$" name)
2154 (setcar n (list 'string-to-number
2155 (list 'match-string
2156 (string-to-number (substring name 1))))))
2157 ((string= "&" name)
2158 (setcar n '(match-string 0)))
2159 ((string= "#&" name)
2160 (setcar n '(string-to-number (match-string 0))))
2161 ((string= "#" name)
2162 (setcar n 'replace-count))))))
2163 (setq n (cdr n))))
2165 (defun replace-eval-replacement (expression count)
2166 (let* ((replace-count count)
2167 (replacement
2168 (condition-case err
2169 (eval expression)
2170 (error
2171 (error "Error evaluating replacement expression: %S" err)))))
2172 (if (stringp replacement)
2173 replacement
2174 (prin1-to-string replacement t))))
2176 (defun replace-quote (replacement)
2177 "Quote a replacement string.
2178 This just doubles all backslashes in REPLACEMENT and
2179 returns the resulting string. If REPLACEMENT is not
2180 a string, it is first passed through `prin1-to-string'
2181 with the `noescape' argument set.
2183 `match-data' is preserved across the call."
2184 (save-match-data
2185 (replace-regexp-in-string "\\\\" "\\\\"
2186 (if (stringp replacement)
2187 replacement
2188 (prin1-to-string replacement t))
2189 t t)))
2191 (defun replace-loop-through-replacements (data count)
2192 ;; DATA is a vector containing the following values:
2193 ;; 0 next-rotate-count
2194 ;; 1 repeat-count
2195 ;; 2 next-replacement
2196 ;; 3 replacements
2197 (if (= (aref data 0) count)
2198 (progn
2199 (aset data 0 (+ count (aref data 1)))
2200 (let ((next (cdr (aref data 2))))
2201 (aset data 2 (if (consp next) next (aref data 3))))))
2202 (car (aref data 2)))
2204 (defun replace-match-data (integers reuse &optional new)
2205 "Like `match-data', but markers in REUSE get invalidated.
2206 If NEW is non-nil, it is set and returned instead of fresh data,
2207 but coerced to the correct value of INTEGERS."
2208 (or (and new
2209 (progn
2210 (set-match-data new)
2211 (and (eq new reuse)
2212 (eq (null integers) (markerp (car reuse)))
2213 new)))
2214 (match-data integers reuse t)))
2216 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data
2217 &optional backward)
2218 "Make a replacement with `replace-match', editing `\\?'.
2219 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
2220 After possibly editing it (if `\\?' is present), NEWTEXT is also
2221 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
2222 is made (to save time).
2223 MATCH-DATA is used for the replacement, and is a data structure
2224 as returned from the `match-data' function.
2225 In case editing is done, it is changed to use markers. BACKWARD is
2226 used to reverse the replacement direction.
2228 The return value is non-nil if there has been no `\\?' or NOEDIT was
2229 passed in. If LITERAL is set, no checking is done, anyway."
2230 (unless (or literal noedit)
2231 (setq noedit t)
2232 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
2233 newtext)
2234 (setq newtext
2235 (read-string "Edit replacement string: "
2236 (prog1
2237 (cons
2238 (replace-match "" t t newtext 3)
2239 (1+ (match-beginning 3)))
2240 (setq match-data
2241 (replace-match-data
2242 nil match-data match-data))))
2243 noedit nil)))
2244 (set-match-data match-data)
2245 (replace-match newtext fixedcase literal)
2246 ;; `query-replace' undo feature needs the beginning of the match position,
2247 ;; but `replace-match' may change it, for instance, with a regexp like "^".
2248 ;; Ensure that this function preserves the match data (Bug#31492).
2249 (set-match-data match-data)
2250 ;; `replace-match' leaves point at the end of the replacement text,
2251 ;; so move point to the beginning when replacing backward.
2252 (when backward (goto-char (nth 0 match-data)))
2253 noedit)
2255 (defvar replace-update-post-hook nil
2256 "Function(s) to call after query-replace has found a match in the buffer.")
2258 (defvar replace-search-function nil
2259 "Function to use when searching for strings to replace.
2260 It is used by `query-replace' and `replace-string', and is called
2261 with three arguments, as if it were `search-forward'.")
2263 (defvar replace-re-search-function nil
2264 "Function to use when searching for regexps to replace.
2265 It is used by `query-replace-regexp', `replace-regexp',
2266 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2267 It is called with three arguments, as if it were
2268 `re-search-forward'.")
2270 (defun replace-search (search-string limit regexp-flag delimited-flag
2271 case-fold &optional backward)
2272 "Search for the next occurrence of SEARCH-STRING to replace."
2273 ;; Let-bind global isearch-* variables to values used
2274 ;; to search the next replacement. These let-bindings
2275 ;; should be effective both at the time of calling
2276 ;; `isearch-search-fun-default' and also at the
2277 ;; time of funcalling `search-function'.
2278 ;; These isearch-* bindings can't be placed higher
2279 ;; outside of this function because then another I-search
2280 ;; used after `recursive-edit' might override them.
2281 (let* ((isearch-regexp regexp-flag)
2282 (isearch-regexp-function (or delimited-flag
2283 (and replace-char-fold
2284 (not regexp-flag)
2285 #'char-fold-to-regexp)))
2286 (isearch-lax-whitespace
2287 replace-lax-whitespace)
2288 (isearch-regexp-lax-whitespace
2289 replace-regexp-lax-whitespace)
2290 (isearch-case-fold-search case-fold)
2291 (isearch-adjusted nil)
2292 (isearch-nonincremental t) ; don't use lax word mode
2293 (isearch-forward (not backward))
2294 (search-function
2295 (or (if regexp-flag
2296 replace-re-search-function
2297 replace-search-function)
2298 (isearch-search-fun-default))))
2299 (funcall search-function search-string limit t)))
2301 (defvar replace-overlay nil)
2303 (defun replace-highlight (match-beg match-end range-beg range-end
2304 search-string regexp-flag delimited-flag
2305 case-fold &optional backward)
2306 (if query-replace-highlight
2307 (if replace-overlay
2308 (move-overlay replace-overlay match-beg match-end (current-buffer))
2309 (setq replace-overlay (make-overlay match-beg match-end))
2310 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2311 (overlay-put replace-overlay 'face 'query-replace)))
2312 (if query-replace-lazy-highlight
2313 (let ((isearch-string search-string)
2314 (isearch-regexp regexp-flag)
2315 (isearch-regexp-function (or delimited-flag
2316 (and replace-char-fold
2317 (not regexp-flag)
2318 #'char-fold-to-regexp)))
2319 (isearch-lax-whitespace
2320 replace-lax-whitespace)
2321 (isearch-regexp-lax-whitespace
2322 replace-regexp-lax-whitespace)
2323 (isearch-case-fold-search case-fold)
2324 (isearch-forward (not backward))
2325 (isearch-other-end match-beg)
2326 (isearch-error nil))
2327 (isearch-lazy-highlight-new-loop range-beg range-end))))
2329 (defun replace-dehighlight ()
2330 (when replace-overlay
2331 (delete-overlay replace-overlay))
2332 (when query-replace-lazy-highlight
2333 (lazy-highlight-cleanup lazy-highlight-cleanup)
2334 (setq isearch-lazy-highlight-last-string nil))
2335 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2336 (isearch-clean-overlays))
2338 ;; A macro because we push STACK, i.e. a local var in `perform-replace'.
2339 (defmacro replace--push-stack (replaced search-str next-replace stack)
2340 (declare (indent 0) (debug (form form form gv-place)))
2341 `(push (list (point) ,replaced
2342 ;;; If the replacement has already happened, all we need is the
2343 ;;; current match start and end. We could get this with a trivial
2344 ;;; match like
2345 ;;; (save-excursion (goto-char (match-beginning 0))
2346 ;;; (search-forward (match-string 0))
2347 ;;; (match-data t))
2348 ;;; if we really wanted to avoid manually constructing match data.
2349 ;;; Adding current-buffer is necessary so that match-data calls can
2350 ;;; return markers which are appropriate for editing.
2351 (if ,replaced
2352 (list
2353 (match-beginning 0) (match-end 0) (current-buffer))
2354 (match-data t))
2355 ,search-str ,next-replace)
2356 ,stack))
2358 (defun perform-replace (from-string replacements
2359 query-flag regexp-flag delimited-flag
2360 &optional repeat-count map start end backward region-noncontiguous-p)
2361 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2362 Don't use this in your own program unless you want to query and set the mark
2363 just as `query-replace' does. Instead, write a simple loop like this:
2365 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2366 (replace-match \"foobar\" nil nil))
2368 which will run faster and probably do exactly what you want. Please
2369 see the documentation of `replace-match' to find out how to simulate
2370 `case-replace'.
2372 This function returns nil if and only if there were no matches to
2373 make, or the user didn't cancel the call.
2375 REPLACEMENTS is either a string, a list of strings, or a cons cell
2376 containing a function and its first argument. The function is
2377 called to generate each replacement like this:
2378 (funcall (car replacements) (cdr replacements) replace-count)
2379 It must return a string.
2381 Non-nil REGION-NONCONTIGUOUS-P means that the region is composed of
2382 noncontiguous pieces. The most common example of this is a
2383 rectangular region, where the pieces are separated by newline
2384 characters."
2385 (or map (setq map query-replace-map))
2386 (and query-flag minibuffer-auto-raise
2387 (raise-frame (window-frame (minibuffer-window))))
2388 (let* ((case-fold-search
2389 (if (and case-fold-search search-upper-case)
2390 (isearch-no-upper-case-p from-string regexp-flag)
2391 case-fold-search))
2392 (nocasify (not (and case-replace case-fold-search)))
2393 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2394 (search-string from-string)
2395 (real-match-data nil) ; The match data for the current match.
2396 (next-replacement nil)
2397 ;; This is non-nil if we know there is nothing for the user
2398 ;; to edit in the replacement.
2399 (noedit nil)
2400 (keep-going t)
2401 (stack nil)
2402 (search-string-replaced nil) ; last string matching `from-string'
2403 (next-replacement-replaced nil) ; replacement string
2404 ; (substituted regexp)
2405 (last-was-undo)
2406 (last-was-act-and-show)
2407 (update-stack t)
2408 (replace-count 0)
2409 (skip-read-only-count 0)
2410 (skip-filtered-count 0)
2411 (skip-invisible-count 0)
2412 (nonempty-match nil)
2413 (multi-buffer nil)
2414 (recenter-last-op nil) ; Start cycling order with initial position.
2416 ;; If non-nil, it is marker saying where in the buffer to stop.
2417 (limit nil)
2418 ;; Use local binding in add-function below.
2419 (isearch-filter-predicate isearch-filter-predicate)
2420 (region-bounds nil)
2422 ;; Data for the next match. If a cons, it has the same format as
2423 ;; (match-data); otherwise it is t if a match is possible at point.
2424 (match-again t)
2426 (message
2427 (if query-flag
2428 (apply 'propertize
2429 (concat "Query replacing "
2430 (if backward "backward " "")
2431 (if delimited-flag
2432 (or (and (symbolp delimited-flag)
2433 (get delimited-flag
2434 'isearch-message-prefix))
2435 "word ") "")
2436 (if regexp-flag "regexp " "")
2437 "%s with %s: "
2438 (substitute-command-keys
2439 "(\\<query-replace-map>\\[help] for help) "))
2440 minibuffer-prompt-properties))))
2442 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2443 (when region-noncontiguous-p
2444 (setq region-bounds
2445 (mapcar (lambda (position)
2446 (cons (copy-marker (car position))
2447 (copy-marker (cdr position))))
2448 (funcall region-extract-function 'bounds)))
2449 (add-function :after-while isearch-filter-predicate
2450 (lambda (start end)
2451 (delq nil (mapcar
2452 (lambda (bounds)
2453 (and
2454 (>= start (car bounds))
2455 (<= start (cdr bounds))
2456 (>= end (car bounds))
2457 (<= end (cdr bounds))))
2458 region-bounds)))))
2460 ;; If region is active, in Transient Mark mode, operate on region.
2461 (if backward
2462 (when end
2463 (setq limit (copy-marker (min start end)))
2464 (goto-char (max start end))
2465 (deactivate-mark))
2466 (when start
2467 (setq limit (copy-marker (max start end)))
2468 (goto-char (min start end))
2469 (deactivate-mark)))
2471 ;; If last typed key in previous call of multi-buffer perform-replace
2472 ;; was `automatic-all', don't ask more questions in next files
2473 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2474 (setq query-flag nil multi-buffer t))
2476 (cond
2477 ((stringp replacements)
2478 (setq next-replacement replacements
2479 replacements nil))
2480 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2481 (or repeat-count (setq repeat-count 1))
2482 (setq replacements (cons 'replace-loop-through-replacements
2483 (vector repeat-count repeat-count
2484 replacements replacements)))))
2486 (when query-replace-lazy-highlight
2487 (setq isearch-lazy-highlight-last-string nil))
2489 (push-mark)
2490 (undo-boundary)
2491 (unwind-protect
2492 ;; Loop finding occurrences that perhaps should be replaced.
2493 (while (and keep-going
2494 (if backward
2495 (not (or (bobp) (and limit (<= (point) limit))))
2496 (not (or (eobp) (and limit (>= (point) limit)))))
2497 ;; Use the next match if it is already known;
2498 ;; otherwise, search for a match after moving forward
2499 ;; one char if progress is required.
2500 (setq real-match-data
2501 (cond ((consp match-again)
2502 (goto-char (if backward
2503 (nth 0 match-again)
2504 (nth 1 match-again)))
2505 (replace-match-data
2506 t real-match-data match-again))
2507 ;; MATCH-AGAIN non-nil means accept an
2508 ;; adjacent match.
2509 (match-again
2510 (and
2511 (replace-search search-string limit
2512 regexp-flag delimited-flag
2513 case-fold-search backward)
2514 ;; For speed, use only integers and
2515 ;; reuse the list used last time.
2516 (replace-match-data t real-match-data)))
2517 ((and (if backward
2518 (> (1- (point)) (point-min))
2519 (< (1+ (point)) (point-max)))
2520 (or (null limit)
2521 (if backward
2522 (> (1- (point)) limit)
2523 (< (1+ (point)) limit))))
2524 ;; If not accepting adjacent matches,
2525 ;; move one char to the right before
2526 ;; searching again. Undo the motion
2527 ;; if the search fails.
2528 (let ((opoint (point)))
2529 (forward-char (if backward -1 1))
2530 (if (replace-search search-string limit
2531 regexp-flag delimited-flag
2532 case-fold-search backward)
2533 (replace-match-data
2534 t real-match-data)
2535 (goto-char opoint)
2536 nil))))))
2538 ;; Record whether the match is nonempty, to avoid an infinite loop
2539 ;; repeatedly matching the same empty string.
2540 (setq nonempty-match
2541 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2543 ;; If the match is empty, record that the next one can't be
2544 ;; adjacent.
2546 ;; Otherwise, if matching a regular expression, do the next
2547 ;; match now, since the replacement for this match may
2548 ;; affect whether the next match is adjacent to this one.
2549 ;; If that match is empty, don't use it.
2550 (setq match-again
2551 (and nonempty-match
2552 (or (not regexp-flag)
2553 (and (if backward
2554 (looking-back search-string nil)
2555 (looking-at search-string))
2556 (let ((match (match-data)))
2557 (and (/= (nth 0 match) (nth 1 match))
2558 match))))))
2560 (cond
2561 ;; Optionally ignore matches that have a read-only property.
2562 ((not (or (not query-replace-skip-read-only)
2563 (not (text-property-not-all
2564 (nth 0 real-match-data) (nth 1 real-match-data)
2565 'read-only nil))))
2566 (setq skip-read-only-count (1+ skip-read-only-count)))
2567 ;; Optionally filter out matches.
2568 ((not (funcall isearch-filter-predicate
2569 (nth 0 real-match-data) (nth 1 real-match-data)))
2570 (setq skip-filtered-count (1+ skip-filtered-count)))
2571 ;; Optionally ignore invisible matches.
2572 ((not (or (eq search-invisible t)
2573 ;; Don't open overlays for automatic replacements.
2574 (and (not query-flag) search-invisible)
2575 ;; Open hidden overlays for interactive replacements.
2576 (not (isearch-range-invisible
2577 (nth 0 real-match-data) (nth 1 real-match-data)))))
2578 (setq skip-invisible-count (1+ skip-invisible-count)))
2580 ;; Calculate the replacement string, if necessary.
2581 (when replacements
2582 (set-match-data real-match-data)
2583 (setq next-replacement
2584 (funcall (car replacements) (cdr replacements)
2585 replace-count)))
2586 (if (not query-flag)
2587 (progn
2588 (unless (or literal noedit)
2589 (replace-highlight
2590 (nth 0 real-match-data) (nth 1 real-match-data)
2591 start end search-string
2592 regexp-flag delimited-flag case-fold-search backward))
2593 (setq noedit
2594 (replace-match-maybe-edit
2595 next-replacement nocasify literal
2596 noedit real-match-data backward)
2597 replace-count (1+ replace-count)))
2598 (undo-boundary)
2599 (let (done replaced key def)
2600 ;; Loop reading commands until one of them sets done,
2601 ;; which means it has finished handling this
2602 ;; occurrence. Any command that sets `done' should
2603 ;; leave behind proper match data for the stack.
2604 ;; Commands not setting `done' need to adjust
2605 ;; `real-match-data'.
2606 (while (not done)
2607 (set-match-data real-match-data)
2608 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2609 (replace-highlight
2610 (match-beginning 0) (match-end 0)
2611 start end search-string
2612 regexp-flag delimited-flag case-fold-search backward)
2613 ;; Obtain the matched groups: needed only when
2614 ;; regexp-flag non nil.
2615 (when (and last-was-undo regexp-flag)
2616 (setq last-was-undo nil
2617 real-match-data
2618 (save-excursion
2619 (goto-char (match-beginning 0))
2620 (looking-at search-string)
2621 (match-data t real-match-data))))
2622 ;; Matched string and next-replacement-replaced
2623 ;; stored in stack.
2624 (setq search-string-replaced (buffer-substring-no-properties
2625 (match-beginning 0)
2626 (match-end 0))
2627 next-replacement-replaced
2628 (query-replace-descr
2629 (save-match-data
2630 (set-match-data real-match-data)
2631 (match-substitute-replacement
2632 next-replacement nocasify literal))))
2633 ;; Bind message-log-max so we don't fill up the
2634 ;; message log with a bunch of identical messages.
2635 (let ((message-log-max nil)
2636 (replacement-presentation
2637 (if query-replace-show-replacement
2638 (save-match-data
2639 (set-match-data real-match-data)
2640 (match-substitute-replacement next-replacement
2641 nocasify literal))
2642 next-replacement)))
2643 (message message
2644 (query-replace-descr from-string)
2645 (query-replace-descr replacement-presentation)))
2646 (setq key (read-event))
2647 ;; Necessary in case something happens during
2648 ;; read-event that clobbers the match data.
2649 (set-match-data real-match-data)
2650 (setq key (vector key))
2651 (setq def (lookup-key map key))
2652 ;; Restore the match data while we process the command.
2653 (cond ((eq def 'help)
2654 (with-output-to-temp-buffer "*Help*"
2655 (princ
2656 (concat "Query replacing "
2657 (if backward "backward " "")
2658 (if delimited-flag
2659 (or (and (symbolp delimited-flag)
2660 (get delimited-flag
2661 'isearch-message-prefix))
2662 "word ") "")
2663 (if regexp-flag "regexp " "")
2664 from-string " with "
2665 next-replacement ".\n\n"
2666 (substitute-command-keys
2667 query-replace-help)))
2668 (with-current-buffer standard-output
2669 (help-mode))))
2670 ((eq def 'exit)
2671 (setq keep-going nil)
2672 (setq done t))
2673 ((eq def 'exit-current)
2674 (setq multi-buffer t keep-going nil done t))
2675 ((eq def 'backup)
2676 (if stack
2677 (let ((elt (pop stack)))
2678 (goto-char (nth 0 elt))
2679 (setq replaced (nth 1 elt)
2680 real-match-data
2681 (replace-match-data
2682 t real-match-data
2683 (nth 2 elt))))
2684 (message "No previous match")
2685 (ding 'no-terminate)
2686 (sit-for 1)))
2687 ((or (eq def 'undo) (eq def 'undo-all))
2688 (if (null stack)
2689 (progn
2690 (message "Nothing to undo")
2691 (ding 'no-terminate)
2692 (sit-for 1))
2693 (let ((stack-idx 0)
2694 (stack-len (length stack))
2695 (num-replacements 0)
2696 (nocasify t) ; Undo must preserve case (Bug#31073).
2697 search-string
2698 next-replacement)
2699 (while (and (< stack-idx stack-len)
2700 stack
2701 (or (null replaced) last-was-act-and-show))
2702 (let* ((elt (nth stack-idx stack)))
2703 (setq
2704 stack-idx (1+ stack-idx)
2705 replaced (nth 1 elt)
2706 ;; Bind swapped values
2707 ;; (search-string <--> replacement)
2708 search-string (nth (if replaced 4 3) elt)
2709 next-replacement (nth (if replaced 3 4) elt)
2710 search-string-replaced search-string
2711 next-replacement-replaced next-replacement
2712 last-was-act-and-show nil)
2714 (when (and (= stack-idx stack-len)
2715 (and (null replaced) (not last-was-act-and-show))
2716 (zerop num-replacements))
2717 (message "Nothing to undo")
2718 (ding 'no-terminate)
2719 (sit-for 1))
2721 (when replaced
2722 (setq stack (nthcdr stack-idx stack))
2723 (goto-char (nth 0 elt))
2724 (set-match-data (nth 2 elt))
2725 (setq real-match-data
2726 (save-excursion
2727 (goto-char (match-beginning 0))
2728 (looking-at search-string)
2729 (match-data t (nth 2 elt)))
2730 noedit
2731 (replace-match-maybe-edit
2732 next-replacement nocasify literal
2733 noedit real-match-data backward)
2734 replace-count (1- replace-count)
2735 real-match-data
2736 (save-excursion
2737 (goto-char (match-beginning 0))
2738 (looking-at next-replacement)
2739 (match-data t (nth 2 elt))))
2740 ;; Set replaced nil to keep in loop
2741 (when (eq def 'undo-all)
2742 (setq replaced nil
2743 stack-len (- stack-len stack-idx)
2744 stack-idx 0
2745 num-replacements
2746 (1+ num-replacements))))))
2747 (when (and (eq def 'undo-all)
2748 (null (zerop num-replacements)))
2749 (message "Undid %d %s" num-replacements
2750 (if (= num-replacements 1)
2751 "replacement"
2752 "replacements"))
2753 (ding 'no-terminate)
2754 (sit-for 1)))
2755 (setq replaced nil last-was-undo t last-was-act-and-show nil)))
2756 ((eq def 'act)
2757 (or replaced
2758 (setq noedit
2759 (replace-match-maybe-edit
2760 next-replacement nocasify literal
2761 noedit real-match-data backward)
2762 replace-count (1+ replace-count)))
2763 (setq done t replaced t update-stack (not last-was-act-and-show)))
2764 ((eq def 'act-and-exit)
2765 (or replaced
2766 (setq noedit
2767 (replace-match-maybe-edit
2768 next-replacement nocasify literal
2769 noedit real-match-data backward)
2770 replace-count (1+ replace-count)))
2771 (setq keep-going nil)
2772 (setq done t replaced t))
2773 ((eq def 'act-and-show)
2774 (unless replaced
2775 (setq noedit
2776 (replace-match-maybe-edit
2777 next-replacement nocasify literal
2778 noedit real-match-data backward)
2779 replace-count (1+ replace-count)
2780 real-match-data (replace-match-data
2781 t real-match-data)
2782 replaced t last-was-act-and-show t)
2783 (replace--push-stack
2784 replaced
2785 search-string-replaced
2786 next-replacement-replaced stack)))
2787 ((or (eq def 'automatic) (eq def 'automatic-all))
2788 (or replaced
2789 (setq noedit
2790 (replace-match-maybe-edit
2791 next-replacement nocasify literal
2792 noedit real-match-data backward)
2793 replace-count (1+ replace-count)))
2794 (setq done t query-flag nil replaced t)
2795 (if (eq def 'automatic-all) (setq multi-buffer t)))
2796 ((eq def 'skip)
2797 (setq done t update-stack (not last-was-act-and-show)))
2798 ((eq def 'recenter)
2799 ;; `this-command' has the value `query-replace',
2800 ;; so we need to bind it to `recenter-top-bottom'
2801 ;; to allow it to detect a sequence of `C-l'.
2802 (let ((this-command 'recenter-top-bottom)
2803 (last-command 'recenter-top-bottom))
2804 (recenter-top-bottom)))
2805 ((eq def 'edit)
2806 (let ((opos (point-marker)))
2807 (setq real-match-data (replace-match-data
2808 nil real-match-data
2809 real-match-data))
2810 (goto-char (match-beginning 0))
2811 (save-excursion
2812 (save-window-excursion
2813 (recursive-edit)))
2814 (goto-char opos)
2815 (set-marker opos nil))
2816 ;; Before we make the replacement,
2817 ;; decide whether the search string
2818 ;; can match again just after this match.
2819 (if (and regexp-flag nonempty-match)
2820 (setq match-again (and (looking-at search-string)
2821 (match-data)))))
2822 ;; Edit replacement.
2823 ((eq def 'edit-replacement)
2824 (setq real-match-data (replace-match-data
2825 nil real-match-data
2826 real-match-data)
2827 next-replacement
2828 (read-string "Edit replacement string: "
2829 next-replacement)
2830 noedit nil)
2831 (if replaced
2832 (set-match-data real-match-data)
2833 (setq noedit
2834 (replace-match-maybe-edit
2835 next-replacement nocasify literal noedit
2836 real-match-data backward)
2837 replaced t)
2838 (setq next-replacement-replaced next-replacement))
2839 (setq done t))
2841 ((eq def 'delete-and-edit)
2842 (replace-match "" t t)
2843 (setq real-match-data (replace-match-data
2844 nil real-match-data))
2845 (replace-dehighlight)
2846 (save-excursion (recursive-edit))
2847 (setq replaced t))
2848 ;; Note: we do not need to treat `exit-prefix'
2849 ;; specially here, since we reread
2850 ;; any unrecognized character.
2852 (setq this-command 'mode-exited)
2853 (setq keep-going nil)
2854 (setq unread-command-events
2855 (append (listify-key-sequence key)
2856 unread-command-events))
2857 (setq done t)))
2858 (when query-replace-lazy-highlight
2859 ;; Force lazy rehighlighting only after replacements.
2860 (if (not (memq def '(skip backup)))
2861 (setq isearch-lazy-highlight-last-string nil)))
2862 (unless (eq def 'recenter)
2863 ;; Reset recenter cycling order to initial position.
2864 (setq recenter-last-op nil)))
2865 ;; Record previous position for ^ when we move on.
2866 ;; Change markers to numbers in the match data
2867 ;; since lots of markers slow down editing.
2868 (when update-stack
2869 (replace--push-stack
2870 replaced
2871 search-string-replaced
2872 next-replacement-replaced stack))
2873 (setq next-replacement-replaced nil
2874 search-string-replaced nil
2875 last-was-act-and-show nil))))))
2876 (replace-dehighlight))
2877 (or unread-command-events
2878 (message "Replaced %d occurrence%s%s"
2879 replace-count
2880 (if (= replace-count 1) "" "s")
2881 (if (> (+ skip-read-only-count
2882 skip-filtered-count
2883 skip-invisible-count) 0)
2884 (format " (skipped %s)"
2885 (mapconcat
2886 'identity
2887 (delq nil (list
2888 (if (> skip-read-only-count 0)
2889 (format "%s read-only"
2890 skip-read-only-count))
2891 (if (> skip-invisible-count 0)
2892 (format "%s invisible"
2893 skip-invisible-count))
2894 (if (> skip-filtered-count 0)
2895 (format "%s filtered out"
2896 skip-filtered-count))))
2897 ", "))
2898 "")))
2899 (or (and keep-going stack) multi-buffer)))
2901 (provide 'replace)
2903 ;;; replace.el ends here