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