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