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