* killing.texi (Appending Kills): Remove a strangely off-topic index
[emacs/old-mirror.git] / lisp / replace.el
blobde57ddccff20e387940b4bb463078dc4463dd238
1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
6 ;; Maintainer: FSF
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 3, or (at your option)
13 ;; any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
25 ;;; Commentary:
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
30 ;;; Code:
32 (defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
34 :type 'boolean
35 :group 'matching)
37 (defvar query-replace-history nil)
39 (defvar query-replace-defaults nil
40 "Default values of FROM-STRING and TO-STRING for `query-replace'.
41 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
42 no default value.")
44 (defvar query-replace-interactive nil
45 "Non-nil means `query-replace' uses the last search string.
46 That becomes the \"string to replace\".")
48 (defcustom query-replace-from-history-variable 'query-replace-history
49 "History list to use for the FROM argument of `query-replace' commands.
50 The value of this variable should be a symbol; that symbol
51 is used as a variable to hold a history list for the strings
52 or patterns to be replaced."
53 :group 'matching
54 :type 'symbol
55 :version "20.3")
57 (defcustom query-replace-to-history-variable 'query-replace-history
58 "History list to use for the TO argument of `query-replace' commands.
59 The value of this variable should be a symbol; that symbol
60 is used as a variable to hold a history list for replacement
61 strings or patterns."
62 :group 'matching
63 :type 'symbol
64 :version "20.3")
66 (defcustom query-replace-skip-read-only nil
67 "*Non-nil means `query-replace' and friends ignore read-only matches."
68 :type 'boolean
69 :group 'matching
70 :version "22.1")
72 (defcustom query-replace-highlight t
73 "*Non-nil means to highlight matches during query replacement."
74 :type 'boolean
75 :group 'matching)
77 (defcustom query-replace-lazy-highlight t
78 "*Controls the lazy-highlighting during query replacements.
79 When non-nil, all text in the buffer matching the current match
80 is highlighted lazily using isearch lazy highlighting (see
81 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
82 :type 'boolean
83 :group 'lazy-highlight
84 :group 'matching
85 :version "22.1")
87 (defface query-replace
88 '((t (:inherit isearch)))
89 "Face for highlighting query replacement matches."
90 :group 'matching
91 :version "22.1")
93 (defun query-replace-descr (string)
94 (mapconcat 'isearch-text-char-description string ""))
96 (defun query-replace-read-from (prompt regexp-flag)
97 "Query and return the `from' argument of a query-replace operation.
98 The return value can also be a pair (FROM . TO) indicating that the user
99 wants to replace FROM with TO."
100 (if query-replace-interactive
101 (car (if regexp-flag regexp-search-ring search-ring))
102 (let* ((history-add-new-input nil)
103 (from
104 ;; The save-excursion here is in case the user marks and copies
105 ;; a region in order to specify the minibuffer input.
106 ;; That should not clobber the region for the query-replace itself.
107 (save-excursion
108 (read-from-minibuffer
109 (if query-replace-defaults
110 (format "%s (default %s -> %s): " prompt
111 (query-replace-descr (car query-replace-defaults))
112 (query-replace-descr (cdr query-replace-defaults)))
113 (format "%s: " prompt))
114 nil nil nil
115 query-replace-from-history-variable
116 nil t))))
117 (if (and (zerop (length from)) query-replace-defaults)
118 (cons (car query-replace-defaults)
119 (query-replace-compile-replacement
120 (cdr query-replace-defaults) regexp-flag))
121 (add-to-history query-replace-from-history-variable from nil t)
122 ;; Warn if user types \n or \t, but don't reject the input.
123 (and regexp-flag
124 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
125 (let ((match (match-string 3 from)))
126 (cond
127 ((string= match "\\n")
128 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
129 ((string= match "\\t")
130 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
131 (sit-for 2)))
132 from))))
134 (defun query-replace-compile-replacement (to regexp-flag)
135 "Maybe convert a regexp replacement TO to Lisp.
136 Returns a list suitable for `perform-replace' if necessary,
137 the original string if not."
138 (if (and regexp-flag
139 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
140 (let (pos list char)
141 (while
142 (progn
143 (setq pos (match-end 0))
144 (push (substring to 0 (- pos 2)) list)
145 (setq char (aref to (1- pos))
146 to (substring to pos))
147 (cond ((eq char ?\#)
148 (push '(number-to-string replace-count) list))
149 ((eq char ?\,)
150 (setq pos (read-from-string to))
151 (push `(replace-quote ,(car pos)) list)
152 (let ((end
153 ;; Swallow a space after a symbol
154 ;; if there is a space.
155 (if (and (or (symbolp (car pos))
156 ;; Swallow a space after 'foo
157 ;; but not after (quote foo).
158 (and (eq (car-safe (car pos)) 'quote)
159 (not (= ?\( (aref to 0)))))
160 (eq (string-match " " to (cdr pos))
161 (cdr pos)))
162 (1+ (cdr pos))
163 (cdr pos))))
164 (setq to (substring to end)))))
165 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
166 (setq to (nreverse (delete "" (cons to list))))
167 (replace-match-string-symbols to)
168 (cons 'replace-eval-replacement
169 (if (cdr to)
170 (cons 'concat to)
171 (car to))))
172 to))
175 (defun query-replace-read-to (from prompt regexp-flag)
176 "Query and return the `to' argument of a query-replace operation."
177 (query-replace-compile-replacement
178 (save-excursion
179 (let* ((history-add-new-input nil)
180 (to (read-from-minibuffer
181 (format "%s %s with: " prompt (query-replace-descr from))
182 nil nil nil
183 query-replace-to-history-variable from t)))
184 (add-to-history query-replace-to-history-variable to nil t)
185 (setq query-replace-defaults (cons from to))
186 to))
187 regexp-flag))
189 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
190 (unless noerror
191 (barf-if-buffer-read-only))
192 (let* ((from (query-replace-read-from prompt regexp-flag))
193 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
194 (query-replace-read-to from prompt regexp-flag))))
195 (list from to current-prefix-arg)))
197 (defun query-replace (from-string to-string &optional delimited start end)
198 "Replace some occurrences of FROM-STRING with TO-STRING.
199 As each match is found, the user must type a character saying
200 what to do with it. For directions, type \\[help-command] at that time.
202 In Transient Mark mode, if the mark is active, operate on the contents
203 of the region. Otherwise, operate from point to the end of the buffer.
205 If `query-replace-interactive' is non-nil, the last incremental search
206 string is used as FROM-STRING--you don't have to specify it with the
207 minibuffer.
209 Matching is independent of case if `case-fold-search' is non-nil and
210 FROM-STRING has no uppercase letters. Replacement transfers the case
211 pattern of the old text to the new text, if `case-replace' and
212 `case-fold-search' are non-nil and FROM-STRING has no uppercase
213 letters. \(Transferring the case pattern means that if the old text
214 matched is all caps, or capitalized, then its replacement is upcased
215 or capitalized.)
217 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
218 only matches surrounded by word boundaries.
219 Fourth and fifth arg START and END specify the region to operate on.
221 To customize possible responses, change the \"bindings\" in `query-replace-map'."
222 (interactive (let ((common
223 (query-replace-read-args
224 (if (and transient-mark-mode mark-active)
225 "Query replace in region"
226 "Query replace")
227 nil)))
228 (list (nth 0 common) (nth 1 common) (nth 2 common)
229 ;; These are done separately here
230 ;; so that command-history will record these expressions
231 ;; rather than the values they had this time.
232 (if (and transient-mark-mode mark-active)
233 (region-beginning))
234 (if (and transient-mark-mode mark-active)
235 (region-end)))))
236 (perform-replace from-string to-string t nil delimited nil nil start end))
238 (define-key esc-map "%" 'query-replace)
240 (defun query-replace-regexp (regexp to-string &optional delimited start end)
241 "Replace some things after point matching REGEXP with TO-STRING.
242 As each match is found, the user must type a character saying
243 what to do with it. For directions, type \\[help-command] at that time.
245 In Transient Mark mode, if the mark is active, operate on the contents
246 of the region. Otherwise, operate from point to the end of the buffer.
248 If `query-replace-interactive' is non-nil, the last incremental search
249 regexp is used as REGEXP--you don't have to specify it with the
250 minibuffer.
252 Matching is independent of case if `case-fold-search' is non-nil and
253 REGEXP has no uppercase letters. Replacement transfers the case
254 pattern of the old text to the new text, if `case-replace' and
255 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
256 \(Transferring the case pattern means that if the old text matched is
257 all caps, or capitalized, then its replacement is upcased or
258 capitalized.)
260 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
261 only matches surrounded by word boundaries.
262 Fourth and fifth arg START and END specify the region to operate on.
264 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
265 and `\\=\\N' (where N is a digit) stands for
266 whatever what matched the Nth `\\(...\\)' in REGEXP.
267 `\\?' lets you edit the replacement text in the minibuffer
268 at the given position for each replacement.
270 In interactive calls, the replacement text can contain `\\,'
271 followed by a Lisp expression. Each
272 replacement evaluates that expression to compute the replacement
273 string. Inside of that expression, `\\&' is a string denoting the
274 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
275 for the whole or a partial match converted to a number with
276 `string-to-number', and `\\#' itself for the number of replacements
277 done so far (starting with zero).
279 If the replacement expression is a symbol, write a space after it
280 to terminate it. One space there, if any, will be discarded.
282 When using those Lisp features interactively in the replacement
283 text, TO-STRING is actually made a list instead of a string.
284 Use \\[repeat-complex-command] after this command for details."
285 (interactive
286 (let ((common
287 (query-replace-read-args
288 (if (and transient-mark-mode mark-active)
289 "Query replace regexp in region"
290 "Query replace regexp")
291 t)))
292 (list (nth 0 common) (nth 1 common) (nth 2 common)
293 ;; These are done separately here
294 ;; so that command-history will record these expressions
295 ;; rather than the values they had this time.
296 (if (and transient-mark-mode mark-active)
297 (region-beginning))
298 (if (and transient-mark-mode mark-active)
299 (region-end)))))
300 (perform-replace regexp to-string t t delimited nil nil start end))
302 (define-key esc-map [?\C-%] 'query-replace-regexp)
304 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
305 "Replace some things after point matching REGEXP with the result of TO-EXPR.
307 Interactive use of this function is deprecated in favor of the
308 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
309 using `search-forward-regexp' and `replace-match' is preferred.
311 As each match is found, the user must type a character saying
312 what to do with it. For directions, type \\[help-command] at that time.
314 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
315 reference `replace-count' to get the number of replacements already made.
316 If the result of TO-EXPR is not a string, it is converted to one using
317 `prin1-to-string' with the NOESCAPE argument (which see).
319 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
320 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
321 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
322 Use `\\#&' or `\\#N' if you want a number instead of a string.
323 In interactive use, `\\#' in itself stands for `replace-count'.
325 In Transient Mark mode, if the mark is active, operate on the contents
326 of the region. Otherwise, operate from point to the end of the buffer.
328 If `query-replace-interactive' is non-nil, the last incremental search
329 regexp is used as REGEXP--you don't have to specify it with the
330 minibuffer.
332 Preserves case in each replacement if `case-replace' and `case-fold-search'
333 are non-nil and REGEXP has no uppercase letters.
335 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
336 only matches that are surrounded by word boundaries.
337 Fourth and fifth arg START and END specify the region to operate on."
338 (interactive
339 (progn
340 (barf-if-buffer-read-only)
341 (let* ((from
342 ;; Let-bind the history var to disable the "foo -> bar" default.
343 ;; Maybe we shouldn't disable this default, but for now I'll
344 ;; leave it off. --Stef
345 (let ((query-replace-to-history-variable nil))
346 (query-replace-read-from "Query replace regexp" t)))
347 (to (list (read-from-minibuffer
348 (format "Query replace regexp %s with eval: "
349 (query-replace-descr from))
350 nil nil t query-replace-to-history-variable from t))))
351 ;; We make TO a list because replace-match-string-symbols requires one,
352 ;; and the user might enter a single token.
353 (replace-match-string-symbols to)
354 (list from (car to) current-prefix-arg
355 (if (and transient-mark-mode mark-active)
356 (region-beginning))
357 (if (and transient-mark-mode mark-active)
358 (region-end))))))
359 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
360 t 'literal delimited nil nil start end))
362 (make-obsolete 'query-replace-regexp-eval
363 "for interactive use, use the special `\\,' feature of
364 `query-replace-regexp' instead. Non-interactively, a loop
365 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
367 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
368 "Replace some matches for REGEXP with various strings, in rotation.
369 The second argument TO-STRINGS contains the replacement strings, separated
370 by spaces. This command works like `query-replace-regexp' except that
371 each successive replacement uses the next successive replacement string,
372 wrapping around from the last such string to the first.
374 In Transient Mark mode, if the mark is active, operate on the contents
375 of the region. Otherwise, operate from point to the end of the buffer.
377 Non-interactively, TO-STRINGS may be a list of replacement strings.
379 If `query-replace-interactive' is non-nil, the last incremental search
380 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
382 A prefix argument N says to use each replacement string N times
383 before rotating to the next.
384 Fourth and fifth arg START and END specify the region to operate on."
385 (interactive
386 (let* ((from (if query-replace-interactive
387 (car regexp-search-ring)
388 (read-from-minibuffer "Map query replace (regexp): "
389 nil nil nil
390 'query-replace-history nil t)))
391 (to (read-from-minibuffer
392 (format "Query replace %s with (space-separated strings): "
393 (query-replace-descr from))
394 nil nil nil
395 'query-replace-history from t)))
396 (list from to
397 (and current-prefix-arg
398 (prefix-numeric-value current-prefix-arg))
399 (if (and transient-mark-mode mark-active)
400 (region-beginning))
401 (if (and transient-mark-mode mark-active)
402 (region-end)))))
403 (let (replacements)
404 (if (listp to-strings)
405 (setq replacements to-strings)
406 (while (/= (length to-strings) 0)
407 (if (string-match " " to-strings)
408 (setq replacements
409 (append replacements
410 (list (substring to-strings 0
411 (string-match " " to-strings))))
412 to-strings (substring to-strings
413 (1+ (string-match " " to-strings))))
414 (setq replacements (append replacements (list to-strings))
415 to-strings ""))))
416 (perform-replace regexp replacements t t nil n nil start end)))
418 (defun replace-string (from-string to-string &optional delimited start end)
419 "Replace occurrences of FROM-STRING with TO-STRING.
420 Preserve case in each match if `case-replace' and `case-fold-search'
421 are non-nil and FROM-STRING has no uppercase letters.
422 \(Preserving case means that if the string matched is all caps, or capitalized,
423 then its replacement is upcased or capitalized.)
425 In Transient Mark mode, if the mark is active, operate on the contents
426 of the region. Otherwise, operate from point to the end of the buffer.
428 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
429 only matches surrounded by word boundaries.
430 Fourth and fifth arg START and END specify the region to operate on.
432 If `query-replace-interactive' is non-nil, the last incremental search
433 string is used as FROM-STRING--you don't have to specify it with the
434 minibuffer.
436 This function is usually the wrong thing to use in a Lisp program.
437 What you probably want is a loop like this:
438 (while (search-forward FROM-STRING nil t)
439 (replace-match TO-STRING nil t))
440 which will run faster and will not set the mark or print anything.
441 \(You may need a more complex loop if FROM-STRING can match the null string
442 and TO-STRING is also null.)"
443 (interactive
444 (let ((common
445 (query-replace-read-args
446 (if (and transient-mark-mode mark-active)
447 "Replace string in region"
448 "Replace string")
449 nil)))
450 (list (nth 0 common) (nth 1 common) (nth 2 common)
451 (if (and transient-mark-mode mark-active)
452 (region-beginning))
453 (if (and transient-mark-mode mark-active)
454 (region-end)))))
455 (perform-replace from-string to-string nil nil delimited nil nil start end))
457 (defun replace-regexp (regexp to-string &optional delimited start end)
458 "Replace things after point matching REGEXP with TO-STRING.
459 Preserve case in each match if `case-replace' and `case-fold-search'
460 are non-nil and REGEXP has no uppercase letters.
462 In Transient Mark mode, if the mark is active, operate on the contents
463 of the region. Otherwise, operate from point to the end of the buffer.
465 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
466 only matches surrounded by word boundaries.
467 Fourth and fifth arg START and END specify the region to operate on.
469 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
470 and `\\=\\N' (where N is a digit) stands for
471 whatever what matched the Nth `\\(...\\)' in REGEXP.
472 `\\?' lets you edit the replacement text in the minibuffer
473 at the given position for each replacement.
475 In interactive calls, the replacement text may contain `\\,'
476 followed by a Lisp expression used as part of the replacement
477 text. Inside of that expression, `\\&' is a string denoting the
478 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
479 numeric values from `string-to-number', and `\\#' itself for
480 `replace-count', the number of replacements occurred so far.
482 If your Lisp expression is an identifier and the next letter in
483 the replacement string would be interpreted as part of it, you
484 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
485 for this particular case you may also enter `\\#' in the
486 replacement text directly.
488 When using those Lisp features interactively in the replacement
489 text, TO-STRING is actually made a list instead of a string.
490 Use \\[repeat-complex-command] after this command for details.
492 If `query-replace-interactive' is non-nil, the last incremental search
493 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
495 This function is usually the wrong thing to use in a Lisp program.
496 What you probably want is a loop like this:
497 (while (re-search-forward REGEXP nil t)
498 (replace-match TO-STRING nil nil))
499 which will run faster and will not set the mark or print anything."
500 (interactive
501 (let ((common
502 (query-replace-read-args
503 (if (and transient-mark-mode mark-active)
504 "Replace regexp in region"
505 "Replace regexp")
506 t)))
507 (list (nth 0 common) (nth 1 common) (nth 2 common)
508 (if (and transient-mark-mode mark-active)
509 (region-beginning))
510 (if (and transient-mark-mode mark-active)
511 (region-end)))))
512 (perform-replace regexp to-string nil t delimited nil nil start end))
515 (defvar regexp-history nil
516 "History list for some commands that read regular expressions.
518 Maximum length of the history list is determined by the value
519 of `history-length', which see.")
522 (defalias 'delete-non-matching-lines 'keep-lines)
523 (defalias 'delete-matching-lines 'flush-lines)
524 (defalias 'count-matches 'how-many)
527 (defun keep-lines-read-args (prompt)
528 "Read arguments for `keep-lines' and friends.
529 Prompt for a regexp with PROMPT.
530 Value is a list, (REGEXP)."
531 (list (read-from-minibuffer prompt nil nil nil
532 'regexp-history nil t)
533 nil nil t))
535 (defun keep-lines (regexp &optional rstart rend interactive)
536 "Delete all lines except those containing matches for REGEXP.
537 A match split across lines preserves all the lines it lies in.
538 When called from Lisp (and usually interactively as well, see below)
539 applies to all lines starting after point.
541 If REGEXP contains upper case characters (excluding those preceded by `\\'),
542 the matching is case-sensitive.
544 Second and third arg RSTART and REND specify the region to operate on.
545 This command operates on (the accessible part of) all lines whose
546 accessible part is entirely contained in the region determined by RSTART
547 and REND. (A newline ending a line counts as part of that line.)
549 Interactively, in Transient Mark mode when the mark is active, operate
550 on all lines whose accessible part is entirely contained in the region.
551 Otherwise, the command applies to all lines starting after point.
552 When calling this function from Lisp, you can pretend that it was
553 called interactively by passing a non-nil INTERACTIVE argument.
555 This function starts looking for the next match from the end of
556 the previous match. Hence, it ignores matches that overlap
557 a previously found match."
559 (interactive
560 (progn
561 (barf-if-buffer-read-only)
562 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
563 (if rstart
564 (progn
565 (goto-char (min rstart rend))
566 (setq rend
567 (progn
568 (save-excursion
569 (goto-char (max rstart rend))
570 (unless (or (bolp) (eobp))
571 (forward-line 0))
572 (point-marker)))))
573 (if (and interactive transient-mark-mode mark-active)
574 (setq rstart (region-beginning)
575 rend (progn
576 (goto-char (region-end))
577 (unless (or (bolp) (eobp))
578 (forward-line 0))
579 (point-marker)))
580 (setq rstart (point)
581 rend (point-max-marker)))
582 (goto-char rstart))
583 (save-excursion
584 (or (bolp) (forward-line 1))
585 (let ((start (point))
586 (case-fold-search (and case-fold-search
587 (isearch-no-upper-case-p regexp t))))
588 (while (< (point) rend)
589 ;; Start is first char not preserved by previous match.
590 (if (not (re-search-forward regexp rend 'move))
591 (delete-region start rend)
592 (let ((end (save-excursion (goto-char (match-beginning 0))
593 (forward-line 0)
594 (point))))
595 ;; Now end is first char preserved by the new match.
596 (if (< start end)
597 (delete-region start end))))
599 (setq start (save-excursion (forward-line 1) (point)))
600 ;; If the match was empty, avoid matching again at same place.
601 (and (< (point) rend)
602 (= (match-beginning 0) (match-end 0))
603 (forward-char 1)))))
604 (set-marker rend nil)
605 nil)
608 (defun flush-lines (regexp &optional rstart rend interactive)
609 "Delete lines containing matches for REGEXP.
610 When called from Lisp (and usually when called interactively as
611 well, see below), applies to the part of the buffer after point.
612 The line point is in is deleted if and only if it contains a
613 match for regexp starting after point.
615 If REGEXP contains upper case characters (excluding those preceded by `\\'),
616 the matching is case-sensitive.
618 Second and third arg RSTART and REND specify the region to operate on.
619 Lines partially contained in this region are deleted if and only if
620 they contain a match entirely contained in it.
622 Interactively, in Transient Mark mode when the mark is active, operate
623 on the contents of the region. Otherwise, operate from point to the
624 end of (the accessible portion of) the buffer. When calling this function
625 from Lisp, you can pretend that it was called interactively by passing
626 a non-nil INTERACTIVE argument.
628 If a match is split across lines, all the lines it lies in are deleted.
629 They are deleted _before_ looking for the next match. Hence, a match
630 starting on the same line at which another match ended is ignored."
632 (interactive
633 (progn
634 (barf-if-buffer-read-only)
635 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
636 (if rstart
637 (progn
638 (goto-char (min rstart rend))
639 (setq rend (copy-marker (max rstart rend))))
640 (if (and interactive transient-mark-mode mark-active)
641 (setq rstart (region-beginning)
642 rend (copy-marker (region-end)))
643 (setq rstart (point)
644 rend (point-max-marker)))
645 (goto-char rstart))
646 (let ((case-fold-search (and case-fold-search
647 (isearch-no-upper-case-p regexp t))))
648 (save-excursion
649 (while (and (< (point) rend)
650 (re-search-forward regexp rend t))
651 (delete-region (save-excursion (goto-char (match-beginning 0))
652 (forward-line 0)
653 (point))
654 (progn (forward-line 1) (point))))))
655 (set-marker rend nil)
656 nil)
659 (defun how-many (regexp &optional rstart rend interactive)
660 "Print and return number of matches for REGEXP following point.
661 When called from Lisp and INTERACTIVE is omitted or nil, just return
662 the number, do not print it; if INTERACTIVE is t, the function behaves
663 in all respects has if it had been called interactively.
665 If REGEXP contains upper case characters (excluding those preceded by `\\'),
666 the matching is case-sensitive.
668 Second and third arg RSTART and REND specify the region to operate on.
670 Interactively, in Transient Mark mode when the mark is active, operate
671 on the contents of the region. Otherwise, operate from point to the
672 end of (the accessible portion of) the buffer.
674 This function starts looking for the next match from the end of
675 the previous match. Hence, it ignores matches that overlap
676 a previously found match."
678 (interactive
679 (keep-lines-read-args "How many matches for (regexp): "))
680 (save-excursion
681 (if rstart
682 (progn
683 (goto-char (min rstart rend))
684 (setq rend (max rstart rend)))
685 (if (and interactive transient-mark-mode mark-active)
686 (setq rstart (region-beginning)
687 rend (region-end))
688 (setq rstart (point)
689 rend (point-max)))
690 (goto-char rstart))
691 (let ((count 0)
692 opoint
693 (case-fold-search (and case-fold-search
694 (isearch-no-upper-case-p regexp t))))
695 (while (and (< (point) rend)
696 (progn (setq opoint (point))
697 (re-search-forward regexp rend t)))
698 (if (= opoint (point))
699 (forward-char 1)
700 (setq count (1+ count))))
701 (when interactive (message "%d occurrence%s"
702 count
703 (if (= count 1) "" "s")))
704 count)))
707 (defvar occur-mode-map
708 (let ((map (make-sparse-keymap)))
709 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
710 (define-key map [mouse-2] 'occur-mode-mouse-goto)
711 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
712 (define-key map "\C-m" 'occur-mode-goto-occurrence)
713 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
714 (define-key map "\C-o" 'occur-mode-display-occurrence)
715 (define-key map "\M-n" 'occur-next)
716 (define-key map "\M-p" 'occur-prev)
717 (define-key map "r" 'occur-rename-buffer)
718 (define-key map "c" 'clone-buffer)
719 (define-key map "g" 'revert-buffer)
720 (define-key map "q" 'quit-window)
721 (define-key map "z" 'kill-this-buffer)
722 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
723 map)
724 "Keymap for `occur-mode'.")
726 (defvar occur-revert-arguments nil
727 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
728 See `occur-revert-function'.")
730 (defcustom occur-mode-hook '(turn-on-font-lock)
731 "Hook run when entering Occur mode."
732 :type 'hook
733 :group 'matching)
735 (defcustom occur-hook nil
736 "Hook run by Occur when there are any matches."
737 :type 'hook
738 :group 'matching)
740 (put 'occur-mode 'mode-class 'special)
741 (defun occur-mode ()
742 "Major mode for output from \\[occur].
743 \\<occur-mode-map>Move point to one of the items in this buffer, then use
744 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
745 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
747 \\{occur-mode-map}"
748 (interactive)
749 (kill-all-local-variables)
750 (use-local-map occur-mode-map)
751 (setq major-mode 'occur-mode)
752 (setq mode-name "Occur")
753 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
754 (make-local-variable 'occur-revert-arguments)
755 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
756 (setq next-error-function 'occur-next-error)
757 (run-mode-hooks 'occur-mode-hook))
759 (defun occur-revert-function (ignore1 ignore2)
760 "Handle `revert-buffer' for Occur mode buffers."
761 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
763 (defun occur-mode-find-occurrence ()
764 (let ((pos (get-text-property (point) 'occur-target)))
765 (unless pos
766 (error "No occurrence on this line"))
767 (unless (buffer-live-p (marker-buffer pos))
768 (error "Buffer for this occurrence was killed"))
769 pos))
771 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
772 (defun occur-mode-goto-occurrence (&optional event)
773 "Go to the occurrence the current line describes."
774 (interactive (list last-nonmenu-event))
775 (let ((pos
776 (if (null event)
777 ;; Actually `event-end' works correctly with a nil argument as
778 ;; well, so we could dispense with this test, but let's not
779 ;; rely on this undocumented behavior.
780 (occur-mode-find-occurrence)
781 (with-current-buffer (window-buffer (posn-window (event-end event)))
782 (save-excursion
783 (goto-char (posn-point (event-end event)))
784 (occur-mode-find-occurrence)))))
785 same-window-buffer-names
786 same-window-regexps)
787 (pop-to-buffer (marker-buffer pos))
788 (goto-char pos)))
790 (defun occur-mode-goto-occurrence-other-window ()
791 "Go to the occurrence the current line describes, in another window."
792 (interactive)
793 (let ((pos (occur-mode-find-occurrence)))
794 (switch-to-buffer-other-window (marker-buffer pos))
795 (goto-char pos)))
797 (defun occur-mode-display-occurrence ()
798 "Display in another window the occurrence the current line describes."
799 (interactive)
800 (let ((pos (occur-mode-find-occurrence))
801 window
802 ;; Bind these to ensure `display-buffer' puts it in another window.
803 same-window-buffer-names
804 same-window-regexps)
805 (setq window (display-buffer (marker-buffer pos)))
806 ;; This is the way to set point in the proper window.
807 (save-selected-window
808 (select-window window)
809 (goto-char pos))))
811 (defun occur-find-match (n search message)
812 (if (not n) (setq n 1))
813 (let ((r))
814 (while (> n 0)
815 (setq r (funcall search (point) 'occur-match))
816 (and r
817 (get-text-property r 'occur-match)
818 (setq r (funcall search r 'occur-match)))
819 (if r
820 (goto-char r)
821 (error message))
822 (setq n (1- n)))))
824 (defun occur-next (&optional n)
825 "Move to the Nth (default 1) next match in an Occur mode buffer."
826 (interactive "p")
827 (occur-find-match n #'next-single-property-change "No more matches"))
829 (defun occur-prev (&optional n)
830 "Move to the Nth (default 1) previous match in an Occur mode buffer."
831 (interactive "p")
832 (occur-find-match n #'previous-single-property-change "No earlier matches"))
834 (defun occur-next-error (&optional argp reset)
835 "Move to the Nth (default 1) next match in an Occur mode buffer.
836 Compatibility function for \\[next-error] invocations."
837 (interactive "p")
838 ;; we need to run occur-find-match from within the Occur buffer
839 (with-current-buffer
840 ;; Choose the buffer and make it current.
841 (if (next-error-buffer-p (current-buffer))
842 (current-buffer)
843 (next-error-find-buffer nil nil
844 (lambda ()
845 (eq major-mode 'occur-mode))))
847 (goto-char (cond (reset (point-min))
848 ((< argp 0) (line-beginning-position))
849 ((> argp 0) (line-end-position))
850 ((point))))
851 (occur-find-match
852 (abs argp)
853 (if (> 0 argp)
854 #'previous-single-property-change
855 #'next-single-property-change)
856 "No more matches")
857 ;; In case the *Occur* buffer is visible in a nonselected window.
858 (let ((win (get-buffer-window (current-buffer) t)))
859 (if win (set-window-point win (point))))
860 (occur-mode-goto-occurrence)))
862 (defface match
863 '((((class color) (min-colors 88) (background light))
864 :background "yellow1")
865 (((class color) (min-colors 88) (background dark))
866 :background "RoyalBlue3")
867 (((class color) (min-colors 8) (background light))
868 :background "yellow" :foreground "black")
869 (((class color) (min-colors 8) (background dark))
870 :background "blue" :foreground "white")
871 (((type tty) (class mono))
872 :inverse-video t)
873 (t :background "gray"))
874 "Face used to highlight matches permanently."
875 :group 'matching
876 :version "22.1")
878 (defcustom list-matching-lines-default-context-lines 0
879 "*Default number of context lines included around `list-matching-lines' matches.
880 A negative number means to include that many lines before the match.
881 A positive number means to include that many lines both before and after."
882 :type 'integer
883 :group 'matching)
885 (defalias 'list-matching-lines 'occur)
887 (defcustom list-matching-lines-face 'match
888 "*Face used by \\[list-matching-lines] to show the text that matches.
889 If the value is nil, don't highlight the matching portions specially."
890 :type 'face
891 :group 'matching)
893 (defcustom list-matching-lines-buffer-name-face 'underline
894 "*Face used by \\[list-matching-lines] to show the names of buffers.
895 If the value is nil, don't highlight the buffer names specially."
896 :type 'face
897 :group 'matching)
899 (defcustom occur-excluded-properties
900 '(read-only invisible intangible field mouse-face help-echo local-map keymap
901 yank-handler follow-link)
902 "*Text properties to discard when copying lines to the *Occur* buffer.
903 The value should be a list of text properties to discard or t,
904 which means to discard all text properties."
905 :type '(choice (const :tag "All" t) (repeat symbol))
906 :group 'matching
907 :version "22.1")
909 (defun occur-accumulate-lines (count &optional keep-props)
910 (save-excursion
911 (let ((forwardp (> count 0))
912 result beg end)
913 (while (not (or (zerop count)
914 (if forwardp
915 (eobp)
916 (bobp))))
917 (setq count (+ count (if forwardp -1 1)))
918 (setq beg (line-beginning-position)
919 end (line-end-position))
920 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
921 (text-property-not-all beg end 'fontified t))
922 (if (fboundp 'jit-lock-fontify-now)
923 (jit-lock-fontify-now beg end)))
924 (push
925 (if (and keep-props (not (eq occur-excluded-properties t)))
926 (let ((str (buffer-substring beg end)))
927 (remove-list-of-text-properties
928 0 (length str) occur-excluded-properties str)
929 str)
930 (buffer-substring-no-properties beg end))
931 result)
932 (forward-line (if forwardp 1 -1)))
933 (nreverse result))))
935 (defun occur-read-primary-args ()
936 (list (let* ((default (car regexp-history))
937 (input
938 (read-from-minibuffer
939 (if default
940 (format "List lines matching regexp (default %s): "
941 (query-replace-descr default))
942 "List lines matching regexp: ")
946 'regexp-history
947 default)))
948 (if (equal input "")
949 default
950 input))
951 (when current-prefix-arg
952 (prefix-numeric-value current-prefix-arg))))
954 (defun occur-rename-buffer (&optional unique-p interactive-p)
955 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
956 Here `original-buffer-name' is the buffer name were Occur was originally run.
957 When given the prefix argument, or called non-interactively, the renaming
958 will not clobber the existing buffer(s) of that name, but use
959 `generate-new-buffer-name' instead. You can add this to `occur-hook'
960 if you always want a separate *Occur* buffer for each buffer where you
961 invoke `occur'."
962 (interactive "P\np")
963 (with-current-buffer
964 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
965 (rename-buffer (concat "*Occur: "
966 (mapconcat #'buffer-name
967 (car (cddr occur-revert-arguments)) "/")
968 "*")
969 (or unique-p (not interactive-p)))))
971 (defun occur (regexp &optional nlines)
972 "Show all lines in the current buffer containing a match for REGEXP.
973 This function can not handle matches that span more than one line.
975 Each line is displayed with NLINES lines before and after, or -NLINES
976 before if NLINES is negative.
977 NLINES defaults to `list-matching-lines-default-context-lines'.
978 Interactively it is the prefix arg.
980 The lines are shown in a buffer named `*Occur*'.
981 It serves as a menu to find any of the occurrences in this buffer.
982 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
984 If REGEXP contains upper case characters (excluding those preceded by `\\'),
985 the matching is case-sensitive."
986 (interactive (occur-read-primary-args))
987 (occur-1 regexp nlines (list (current-buffer))))
989 (defun multi-occur (bufs regexp &optional nlines)
990 "Show all lines in buffers BUFS containing a match for REGEXP.
991 This function acts on multiple buffers; otherwise, it is exactly like
992 `occur'. When you invoke this command interactively, you must specify
993 the buffer names that you want, one by one."
994 (interactive
995 (cons
996 (let* ((bufs (list (read-buffer "First buffer to search: "
997 (current-buffer) t)))
998 (buf nil)
999 (ido-ignore-item-temp-list bufs))
1000 (while (not (string-equal
1001 (setq buf (read-buffer
1002 (if (eq read-buffer-function 'ido-read-buffer)
1003 "Next buffer to search (C-j to end): "
1004 "Next buffer to search (RET to end): ")
1005 nil t))
1006 ""))
1007 (add-to-list 'bufs buf)
1008 (setq ido-ignore-item-temp-list bufs))
1009 (nreverse (mapcar #'get-buffer bufs)))
1010 (occur-read-primary-args)))
1011 (occur-1 regexp nlines bufs))
1013 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1014 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1015 Normally BUFREGEXP matches against each buffer's visited file name,
1016 but if you specify a prefix argument, it matches against the buffer name.
1017 See also `multi-occur'."
1018 (interactive
1019 (cons
1020 (let* ((default (car regexp-history))
1021 (input
1022 (read-from-minibuffer
1023 (if current-prefix-arg
1024 "List lines in buffers whose names match regexp: "
1025 "List lines in buffers whose filenames match regexp: ")
1029 'regexp-history)))
1030 (if (equal input "")
1031 default
1032 input))
1033 (occur-read-primary-args)))
1034 (when bufregexp
1035 (occur-1 regexp nil
1036 (delq nil
1037 (mapcar (lambda (buf)
1038 (when (if allbufs
1039 (string-match bufregexp
1040 (buffer-name buf))
1041 (and (buffer-file-name buf)
1042 (string-match bufregexp
1043 (buffer-file-name buf))))
1044 buf))
1045 (buffer-list))))))
1047 (defun occur-1 (regexp nlines bufs &optional buf-name)
1048 (unless buf-name
1049 (setq buf-name "*Occur*"))
1050 (let (occur-buf
1051 (active-bufs (delq nil (mapcar #'(lambda (buf)
1052 (when (buffer-live-p buf) buf))
1053 bufs))))
1054 ;; Handle the case where one of the buffers we're searching is the
1055 ;; output buffer. Just rename it.
1056 (when (member buf-name (mapcar 'buffer-name active-bufs))
1057 (with-current-buffer (get-buffer buf-name)
1058 (rename-uniquely)))
1060 ;; Now find or create the output buffer.
1061 ;; If we just renamed that buffer, we will make a new one here.
1062 (setq occur-buf (get-buffer-create buf-name))
1064 (with-current-buffer occur-buf
1065 (occur-mode)
1066 (let ((inhibit-read-only t)
1067 ;; Don't generate undo entries for creation of the initial contents.
1068 (buffer-undo-list t))
1069 (erase-buffer)
1070 (let ((count (occur-engine
1071 regexp active-bufs occur-buf
1072 (or nlines list-matching-lines-default-context-lines)
1073 (and case-fold-search
1074 (isearch-no-upper-case-p regexp t))
1075 list-matching-lines-buffer-name-face
1076 nil list-matching-lines-face
1077 (not (eq occur-excluded-properties t)))))
1078 (let* ((bufcount (length active-bufs))
1079 (diff (- (length bufs) bufcount)))
1080 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1081 bufcount (if (= bufcount 1) "" "s")
1082 (if (zerop diff) "" (format " (%d killed)" diff))
1083 (if (zerop count) "no" (format "%d" count))
1084 (if (= count 1) "" "es")
1085 regexp))
1086 (setq occur-revert-arguments (list regexp nlines bufs))
1087 (if (= count 0)
1088 (kill-buffer occur-buf)
1089 (display-buffer occur-buf)
1090 (setq next-error-last-buffer occur-buf)
1091 (setq buffer-read-only t)
1092 (set-buffer-modified-p nil)
1093 (run-hooks 'occur-hook)))))))
1095 (defun occur-engine-add-prefix (lines)
1096 (mapcar
1097 #'(lambda (line)
1098 (concat " :" line "\n"))
1099 lines))
1101 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1102 title-face prefix-face match-face keep-props)
1103 (with-current-buffer out-buf
1104 (let ((globalcount 0)
1105 (coding nil))
1106 ;; Map over all the buffers
1107 (dolist (buf buffers)
1108 (when (buffer-live-p buf)
1109 (let ((matches 0) ;; count of matched lines
1110 (lines 1) ;; line count
1111 (matchbeg 0)
1112 (origpt nil)
1113 (begpt nil)
1114 (endpt nil)
1115 (marker nil)
1116 (curstring "")
1117 (inhibit-field-text-motion t)
1118 (headerpt (with-current-buffer out-buf (point))))
1119 (with-current-buffer buf
1120 (or coding
1121 ;; Set CODING only if the current buffer locally
1122 ;; binds buffer-file-coding-system.
1123 (not (local-variable-p 'buffer-file-coding-system))
1124 (setq coding buffer-file-coding-system))
1125 (save-excursion
1126 (goto-char (point-min)) ;; begin searching in the buffer
1127 (while (not (eobp))
1128 (setq origpt (point))
1129 (when (setq endpt (re-search-forward regexp nil t))
1130 (setq matches (1+ matches)) ;; increment match count
1131 (setq matchbeg (match-beginning 0))
1132 (setq lines (+ lines (1- (count-lines origpt endpt))))
1133 (save-excursion
1134 (goto-char matchbeg)
1135 (setq begpt (line-beginning-position)
1136 endpt (line-end-position)))
1137 (setq marker (make-marker))
1138 (set-marker marker matchbeg)
1139 (if (and keep-props
1140 (if (boundp 'jit-lock-mode) jit-lock-mode)
1141 (text-property-not-all begpt endpt 'fontified t))
1142 (if (fboundp 'jit-lock-fontify-now)
1143 (jit-lock-fontify-now begpt endpt)))
1144 (if (and keep-props (not (eq occur-excluded-properties t)))
1145 (progn
1146 (setq curstring (buffer-substring begpt endpt))
1147 (remove-list-of-text-properties
1148 0 (length curstring) occur-excluded-properties curstring))
1149 (setq curstring (buffer-substring-no-properties begpt endpt)))
1150 ;; Highlight the matches
1151 (let ((len (length curstring))
1152 (start 0))
1153 (while (and (< start len)
1154 (string-match regexp curstring start))
1155 (add-text-properties
1156 (match-beginning 0) (match-end 0)
1157 (append
1158 `(occur-match t)
1159 (when match-face
1160 ;; Use `face' rather than `font-lock-face' here
1161 ;; so as to override faces copied from the buffer.
1162 `(face ,match-face)))
1163 curstring)
1164 (setq start (match-end 0))))
1165 ;; Generate the string to insert for this match
1166 (let* ((out-line
1167 (concat
1168 ;; Using 7 digits aligns tabs properly.
1169 (apply #'propertize (format "%7d:" lines)
1170 (append
1171 (when prefix-face
1172 `(font-lock-face prefix-face))
1173 `(occur-prefix t mouse-face (highlight)
1174 occur-target ,marker follow-link t
1175 help-echo "mouse-2: go to this occurrence")))
1176 ;; We don't put `mouse-face' on the newline,
1177 ;; because that loses. And don't put it
1178 ;; on context lines to reduce flicker.
1179 (propertize curstring 'mouse-face (list 'highlight)
1180 'occur-target marker
1181 'follow-link t
1182 'help-echo
1183 "mouse-2: go to this occurrence")
1184 ;; Add marker at eol, but no mouse props.
1185 (propertize "\n" 'occur-target marker)))
1186 (data
1187 (if (= nlines 0)
1188 ;; The simple display style
1189 out-line
1190 ;; The complex multi-line display
1191 ;; style. Generate a list of lines,
1192 ;; concatenate them all together.
1193 (apply #'concat
1194 (nconc
1195 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines))) keep-props))))
1196 (list out-line)
1197 (if (> nlines 0)
1198 (occur-engine-add-prefix
1199 (cdr (occur-accumulate-lines (1+ nlines) keep-props)))))))))
1200 ;; Actually insert the match display data
1201 (with-current-buffer out-buf
1202 (let ((beg (point))
1203 (end (progn (insert data) (point))))
1204 (unless (= nlines 0)
1205 (insert "-------\n")))))
1206 (goto-char endpt))
1207 (if endpt
1208 (progn
1209 (setq lines (1+ lines))
1210 ;; On to the next match...
1211 (forward-line 1))
1212 (goto-char (point-max))))))
1213 (when (not (zerop matches)) ;; is the count zero?
1214 (setq globalcount (+ globalcount matches))
1215 (with-current-buffer out-buf
1216 (goto-char headerpt)
1217 (let ((beg (point))
1218 end)
1219 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1220 matches (if (= matches 1) "" "es")
1221 regexp (buffer-name buf)))
1222 (setq end (point))
1223 (add-text-properties beg end
1224 (append
1225 (when title-face
1226 `(font-lock-face ,title-face))
1227 `(occur-title ,buf))))
1228 (goto-char (point-min)))))))
1229 (if coding
1230 ;; CODING is buffer-file-coding-system of the first buffer
1231 ;; that locally binds it. Let's use it also for the output
1232 ;; buffer.
1233 (set-buffer-file-coding-system coding))
1234 ;; Return the number of matches
1235 globalcount)))
1238 ;; It would be nice to use \\[...], but there is no reasonable way
1239 ;; to make that display both SPC and Y.
1240 (defconst query-replace-help
1241 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1242 RET or `q' to exit, Period to replace one match and exit,
1243 Comma to replace but not move point immediately,
1244 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1245 C-w to delete match and recursive edit,
1246 C-l to clear the screen, redisplay, and offer same replacement again,
1247 ! to replace all remaining matches with no more questions,
1248 ^ to move point back to previous match,
1249 E to edit the replacement string"
1250 "Help message while in `query-replace'.")
1252 (defvar query-replace-map
1253 (let ((map (make-sparse-keymap)))
1254 (define-key map " " 'act)
1255 (define-key map "\d" 'skip)
1256 (define-key map [delete] 'skip)
1257 (define-key map [backspace] 'skip)
1258 (define-key map "y" 'act)
1259 (define-key map "n" 'skip)
1260 (define-key map "Y" 'act)
1261 (define-key map "N" 'skip)
1262 (define-key map "e" 'edit-replacement)
1263 (define-key map "E" 'edit-replacement)
1264 (define-key map "," 'act-and-show)
1265 (define-key map "q" 'exit)
1266 (define-key map "\r" 'exit)
1267 (define-key map [return] 'exit)
1268 (define-key map "." 'act-and-exit)
1269 (define-key map "\C-r" 'edit)
1270 (define-key map "\C-w" 'delete-and-edit)
1271 (define-key map "\C-l" 'recenter)
1272 (define-key map "!" 'automatic)
1273 (define-key map "^" 'backup)
1274 (define-key map "\C-h" 'help)
1275 (define-key map [f1] 'help)
1276 (define-key map [help] 'help)
1277 (define-key map "?" 'help)
1278 (define-key map "\C-g" 'quit)
1279 (define-key map "\C-]" 'quit)
1280 (define-key map "\e" 'exit-prefix)
1281 (define-key map [escape] 'exit-prefix)
1282 map)
1283 "Keymap that defines the responses to questions in `query-replace'.
1284 The \"bindings\" in this map are not commands; they are answers.
1285 The valid answers include `act', `skip', `act-and-show',
1286 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1287 `automatic', `backup', `exit-prefix', and `help'.")
1289 (defun replace-match-string-symbols (n)
1290 "Process a list (and any sub-lists), expanding certain symbols.
1291 Symbol Expands To
1292 N (match-string N) (where N is a string of digits)
1293 #N (string-to-number (match-string N))
1294 & (match-string 0)
1295 #& (string-to-number (match-string 0))
1296 # replace-count
1298 Note that these symbols must be preceeded by a backslash in order to
1299 type them using Lisp syntax."
1300 (while (consp n)
1301 (cond
1302 ((consp (car n))
1303 (replace-match-string-symbols (car n))) ;Process sub-list
1304 ((symbolp (car n))
1305 (let ((name (symbol-name (car n))))
1306 (cond
1307 ((string-match "^[0-9]+$" name)
1308 (setcar n (list 'match-string (string-to-number name))))
1309 ((string-match "^#[0-9]+$" name)
1310 (setcar n (list 'string-to-number
1311 (list 'match-string
1312 (string-to-number (substring name 1))))))
1313 ((string= "&" name)
1314 (setcar n '(match-string 0)))
1315 ((string= "#&" name)
1316 (setcar n '(string-to-number (match-string 0))))
1317 ((string= "#" name)
1318 (setcar n 'replace-count))))))
1319 (setq n (cdr n))))
1321 (defun replace-eval-replacement (expression replace-count)
1322 (let ((replacement (eval expression)))
1323 (if (stringp replacement)
1324 replacement
1325 (prin1-to-string replacement t))))
1327 (defun replace-quote (replacement)
1328 "Quote a replacement string.
1329 This just doubles all backslashes in REPLACEMENT and
1330 returns the resulting string. If REPLACEMENT is not
1331 a string, it is first passed through `prin1-to-string'
1332 with the `noescape' argument set.
1334 `match-data' is preserved across the call."
1335 (save-match-data
1336 (replace-regexp-in-string "\\\\" "\\\\"
1337 (if (stringp replacement)
1338 replacement
1339 (prin1-to-string replacement t))
1340 t t)))
1342 (defun replace-loop-through-replacements (data replace-count)
1343 ;; DATA is a vector contaning the following values:
1344 ;; 0 next-rotate-count
1345 ;; 1 repeat-count
1346 ;; 2 next-replacement
1347 ;; 3 replacements
1348 (if (= (aref data 0) replace-count)
1349 (progn
1350 (aset data 0 (+ replace-count (aref data 1)))
1351 (let ((next (cdr (aref data 2))))
1352 (aset data 2 (if (consp next) next (aref data 3))))))
1353 (car (aref data 2)))
1355 (defun replace-match-data (integers reuse &optional new)
1356 "Like `match-data', but markers in REUSE get invalidated.
1357 If NEW is non-nil, it is set and returned instead of fresh data,
1358 but coerced to the correct value of INTEGERS."
1359 (or (and new
1360 (progn
1361 (set-match-data new)
1362 (and (eq new reuse)
1363 (eq (null integers) (markerp (car reuse)))
1364 new)))
1365 (match-data integers reuse t)))
1367 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1368 "Make a replacement with `replace-match', editing `\\?'.
1369 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1370 check for `\\?' is made to save time. MATCH-DATA is used for the
1371 replacement. In case editing is done, it is changed to use markers.
1373 The return value is non-nil if there has been no `\\?' or NOEDIT was
1374 passed in. If LITERAL is set, no checking is done, anyway."
1375 (unless (or literal noedit)
1376 (setq noedit t)
1377 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1378 newtext)
1379 (setq newtext
1380 (read-string "Edit replacement string: "
1381 (prog1
1382 (cons
1383 (replace-match "" t t newtext 3)
1384 (1+ (match-beginning 3)))
1385 (setq match-data
1386 (replace-match-data
1387 nil match-data match-data))))
1388 noedit nil)))
1389 (set-match-data match-data)
1390 (replace-match newtext fixedcase literal)
1391 noedit)
1393 (defun perform-replace (from-string replacements
1394 query-flag regexp-flag delimited-flag
1395 &optional repeat-count map start end)
1396 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1397 Don't use this in your own program unless you want to query and set the mark
1398 just as `query-replace' does. Instead, write a simple loop like this:
1400 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1401 (replace-match \"foobar\" nil nil))
1403 which will run faster and probably do exactly what you want. Please
1404 see the documentation of `replace-match' to find out how to simulate
1405 `case-replace'.
1407 This function returns nil if and only if there were no matches to
1408 make, or the user didn't cancel the call."
1409 (or map (setq map query-replace-map))
1410 (and query-flag minibuffer-auto-raise
1411 (raise-frame (window-frame (minibuffer-window))))
1412 (let ((nocasify (not (and case-fold-search case-replace
1413 (string-equal from-string
1414 (downcase from-string)))))
1415 (case-fold-search (and case-fold-search
1416 (string-equal from-string
1417 (downcase from-string))))
1418 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1419 (search-function (if regexp-flag 're-search-forward 'search-forward))
1420 (search-string from-string)
1421 (real-match-data nil) ; the match data for the current match
1422 (next-replacement nil)
1423 ;; This is non-nil if we know there is nothing for the user
1424 ;; to edit in the replacement.
1425 (noedit nil)
1426 (keep-going t)
1427 (stack nil)
1428 (replace-count 0)
1429 (nonempty-match nil)
1431 ;; If non-nil, it is marker saying where in the buffer to stop.
1432 (limit nil)
1434 ;; Data for the next match. If a cons, it has the same format as
1435 ;; (match-data); otherwise it is t if a match is possible at point.
1436 (match-again t)
1438 (message
1439 (if query-flag
1440 (apply 'propertize
1441 (substitute-command-keys
1442 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1443 minibuffer-prompt-properties))))
1445 ;; If region is active, in Transient Mark mode, operate on region.
1446 (when start
1447 (setq limit (copy-marker (max start end)))
1448 (goto-char (min start end))
1449 (deactivate-mark))
1451 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1452 ;; containing a function and its first argument. The function is
1453 ;; called to generate each replacement like this:
1454 ;; (funcall (car replacements) (cdr replacements) replace-count)
1455 ;; It must return a string.
1456 (cond
1457 ((stringp replacements)
1458 (setq next-replacement replacements
1459 replacements nil))
1460 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1461 (or repeat-count (setq repeat-count 1))
1462 (setq replacements (cons 'replace-loop-through-replacements
1463 (vector repeat-count repeat-count
1464 replacements replacements)))))
1466 (if delimited-flag
1467 (setq search-function 're-search-forward
1468 search-string (concat "\\b"
1469 (if regexp-flag from-string
1470 (regexp-quote from-string))
1471 "\\b")))
1472 (when query-replace-lazy-highlight
1473 (setq isearch-lazy-highlight-last-string nil))
1475 (push-mark)
1476 (undo-boundary)
1477 (unwind-protect
1478 ;; Loop finding occurrences that perhaps should be replaced.
1479 (while (and keep-going
1480 (not (or (eobp) (and limit (>= (point) limit))))
1481 ;; Use the next match if it is already known;
1482 ;; otherwise, search for a match after moving forward
1483 ;; one char if progress is required.
1484 (setq real-match-data
1485 (cond ((consp match-again)
1486 (goto-char (nth 1 match-again))
1487 (replace-match-data
1488 t real-match-data match-again))
1489 ;; MATCH-AGAIN non-nil means accept an
1490 ;; adjacent match.
1491 (match-again
1492 (and
1493 (funcall search-function search-string
1494 limit t)
1495 ;; For speed, use only integers and
1496 ;; reuse the list used last time.
1497 (replace-match-data t real-match-data)))
1498 ((and (< (1+ (point)) (point-max))
1499 (or (null limit)
1500 (< (1+ (point)) limit)))
1501 ;; If not accepting adjacent matches,
1502 ;; move one char to the right before
1503 ;; searching again. Undo the motion
1504 ;; if the search fails.
1505 (let ((opoint (point)))
1506 (forward-char 1)
1507 (if (funcall
1508 search-function search-string
1509 limit t)
1510 (replace-match-data
1511 t real-match-data)
1512 (goto-char opoint)
1513 nil))))))
1515 ;; Record whether the match is nonempty, to avoid an infinite loop
1516 ;; repeatedly matching the same empty string.
1517 (setq nonempty-match
1518 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1520 ;; If the match is empty, record that the next one can't be
1521 ;; adjacent.
1523 ;; Otherwise, if matching a regular expression, do the next
1524 ;; match now, since the replacement for this match may
1525 ;; affect whether the next match is adjacent to this one.
1526 ;; If that match is empty, don't use it.
1527 (setq match-again
1528 (and nonempty-match
1529 (or (not regexp-flag)
1530 (and (looking-at search-string)
1531 (let ((match (match-data)))
1532 (and (/= (nth 0 match) (nth 1 match))
1533 match))))))
1535 ;; Optionally ignore matches that have a read-only property.
1536 (unless (and query-replace-skip-read-only
1537 (text-property-not-all
1538 (nth 0 real-match-data) (nth 1 real-match-data)
1539 'read-only nil))
1541 ;; Calculate the replacement string, if necessary.
1542 (when replacements
1543 (set-match-data real-match-data)
1544 (setq next-replacement
1545 (funcall (car replacements) (cdr replacements)
1546 replace-count)))
1547 (if (not query-flag)
1548 (let ((inhibit-read-only
1549 query-replace-skip-read-only))
1550 (unless (or literal noedit)
1551 (replace-highlight
1552 (nth 0 real-match-data) (nth 1 real-match-data)
1553 start end search-string
1554 (or delimited-flag regexp-flag) case-fold-search))
1555 (setq noedit
1556 (replace-match-maybe-edit
1557 next-replacement nocasify literal
1558 noedit real-match-data)
1559 replace-count (1+ replace-count)))
1560 (undo-boundary)
1561 (let (done replaced key def)
1562 ;; Loop reading commands until one of them sets done,
1563 ;; which means it has finished handling this
1564 ;; occurrence. Any command that sets `done' should
1565 ;; leave behind proper match data for the stack.
1566 ;; Commands not setting `done' need to adjust
1567 ;; `real-match-data'.
1568 (while (not done)
1569 (set-match-data real-match-data)
1570 (replace-highlight
1571 (match-beginning 0) (match-end 0)
1572 start end search-string
1573 (or delimited-flag regexp-flag) case-fold-search)
1574 ;; Bind message-log-max so we don't fill up the message log
1575 ;; with a bunch of identical messages.
1576 (let ((message-log-max nil))
1577 (message message
1578 (query-replace-descr from-string)
1579 (query-replace-descr next-replacement)))
1580 (setq key (read-event))
1581 ;; Necessary in case something happens during read-event
1582 ;; that clobbers the match data.
1583 (set-match-data real-match-data)
1584 (setq key (vector key))
1585 (setq def (lookup-key map key))
1586 ;; Restore the match data while we process the command.
1587 (cond ((eq def 'help)
1588 (with-output-to-temp-buffer "*Help*"
1589 (princ
1590 (concat "Query replacing "
1591 (if regexp-flag "regexp " "")
1592 from-string " with "
1593 next-replacement ".\n\n"
1594 (substitute-command-keys
1595 query-replace-help)))
1596 (with-current-buffer standard-output
1597 (help-mode))))
1598 ((eq def 'exit)
1599 (setq keep-going nil)
1600 (setq done t))
1601 ((eq def 'backup)
1602 (if stack
1603 (let ((elt (pop stack)))
1604 (goto-char (nth 0 elt))
1605 (setq replaced (nth 1 elt)
1606 real-match-data
1607 (replace-match-data
1608 t real-match-data
1609 (nth 2 elt))))
1610 (message "No previous match")
1611 (ding 'no-terminate)
1612 (sit-for 1)))
1613 ((eq def 'act)
1614 (or replaced
1615 (setq noedit
1616 (replace-match-maybe-edit
1617 next-replacement nocasify literal
1618 noedit real-match-data)
1619 replace-count (1+ replace-count)))
1620 (setq done t replaced t))
1621 ((eq def 'act-and-exit)
1622 (or replaced
1623 (setq noedit
1624 (replace-match-maybe-edit
1625 next-replacement nocasify literal
1626 noedit real-match-data)
1627 replace-count (1+ replace-count)))
1628 (setq keep-going nil)
1629 (setq done t replaced t))
1630 ((eq def 'act-and-show)
1631 (if (not replaced)
1632 (setq noedit
1633 (replace-match-maybe-edit
1634 next-replacement nocasify literal
1635 noedit real-match-data)
1636 replace-count (1+ replace-count)
1637 real-match-data (replace-match-data
1638 t real-match-data)
1639 replaced t)))
1640 ((eq def 'automatic)
1641 (or replaced
1642 (setq noedit
1643 (replace-match-maybe-edit
1644 next-replacement nocasify literal
1645 noedit real-match-data)
1646 replace-count (1+ replace-count)))
1647 (setq done t query-flag nil replaced t))
1648 ((eq def 'skip)
1649 (setq done t))
1650 ((eq def 'recenter)
1651 (recenter nil))
1652 ((eq def 'edit)
1653 (let ((opos (point-marker)))
1654 (setq real-match-data (replace-match-data
1655 nil real-match-data
1656 real-match-data))
1657 (goto-char (match-beginning 0))
1658 (save-excursion
1659 (save-window-excursion
1660 (recursive-edit)))
1661 (goto-char opos)
1662 (set-marker opos nil))
1663 ;; Before we make the replacement,
1664 ;; decide whether the search string
1665 ;; can match again just after this match.
1666 (if (and regexp-flag nonempty-match)
1667 (setq match-again (and (looking-at search-string)
1668 (match-data)))))
1669 ;; Edit replacement.
1670 ((eq def 'edit-replacement)
1671 (setq real-match-data (replace-match-data
1672 nil real-match-data
1673 real-match-data)
1674 next-replacement
1675 (read-string "Edit replacement string: "
1676 next-replacement)
1677 noedit nil)
1678 (if replaced
1679 (set-match-data real-match-data)
1680 (setq noedit
1681 (replace-match-maybe-edit
1682 next-replacement nocasify literal noedit
1683 real-match-data)
1684 replaced t))
1685 (setq done t))
1687 ((eq def 'delete-and-edit)
1688 (replace-match "" t t)
1689 (setq real-match-data (replace-match-data
1690 nil real-match-data))
1691 (replace-dehighlight)
1692 (save-excursion (recursive-edit))
1693 (setq replaced t))
1694 ;; Note: we do not need to treat `exit-prefix'
1695 ;; specially here, since we reread
1696 ;; any unrecognized character.
1698 (setq this-command 'mode-exited)
1699 (setq keep-going nil)
1700 (setq unread-command-events
1701 (append (listify-key-sequence key)
1702 unread-command-events))
1703 (setq done t)))
1704 (when query-replace-lazy-highlight
1705 ;; Force lazy rehighlighting only after replacements
1706 (if (not (memq def '(skip backup)))
1707 (setq isearch-lazy-highlight-last-string nil))))
1708 ;; Record previous position for ^ when we move on.
1709 ;; Change markers to numbers in the match data
1710 ;; since lots of markers slow down editing.
1711 (push (list (point) replaced
1712 ;;; If the replacement has already happened, all we need is the
1713 ;;; current match start and end. We could get this with a trivial
1714 ;;; match like
1715 ;;; (save-excursion (goto-char (match-beginning 0))
1716 ;;; (search-forward (match-string 0))
1717 ;;; (match-data t))
1718 ;;; if we really wanted to avoid manually constructing match data.
1719 ;;; Adding current-buffer is necessary so that match-data calls can
1720 ;;; return markers which are appropriate for editing.
1721 (if replaced
1722 (list
1723 (match-beginning 0)
1724 (match-end 0)
1725 (current-buffer))
1726 (match-data t)))
1727 stack)))))
1729 (replace-dehighlight))
1730 (or unread-command-events
1731 (message "Replaced %d occurrence%s"
1732 replace-count
1733 (if (= replace-count 1) "" "s")))
1734 (and keep-going stack)))
1736 (defvar replace-overlay nil)
1738 (defun replace-highlight (match-beg match-end range-beg range-end
1739 string regexp case-fold)
1740 (if query-replace-highlight
1741 (if replace-overlay
1742 (move-overlay replace-overlay match-beg match-end (current-buffer))
1743 (setq replace-overlay (make-overlay match-beg match-end))
1744 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1745 (overlay-put replace-overlay 'face 'query-replace)))
1746 (if query-replace-lazy-highlight
1747 (let ((isearch-string string)
1748 (isearch-regexp regexp)
1749 (search-whitespace-regexp nil)
1750 (isearch-case-fold-search case-fold))
1751 (isearch-lazy-highlight-new-loop range-beg range-end))))
1753 (defun replace-dehighlight ()
1754 (when replace-overlay
1755 (delete-overlay replace-overlay))
1756 (when query-replace-lazy-highlight
1757 (lazy-highlight-cleanup lazy-highlight-cleanup)
1758 (setq isearch-lazy-highlight-last-string nil)))
1760 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1761 ;;; replace.el ends here