(query-replace-regexp-eval): Doc fix.
[bpt/emacs.git] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997, 2000, 2001, 2002
4 ;; Free Software Foundation, Inc.
5
6 ;; This file is part of GNU Emacs.
7
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
11 ;; any later version.
12
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
17
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING. If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
22
23 ;;; Commentary:
24
25 ;; This package supplies the string and regular-expression replace functions
26 ;; documented in the Emacs user's manual.
27
28 ;;; Code:
29
30 (defcustom case-replace t
31 "*Non-nil means `query-replace' should preserve case in replacements."
32 :type 'boolean
33 :group 'matching)
34
35 (defvar query-replace-history nil)
36
37 (defvar query-replace-interactive nil
38 "Non-nil means `query-replace' uses the last search string.
39 That becomes the \"string to replace\".")
40
41 (defcustom query-replace-from-history-variable 'query-replace-history
42 "History list to use for the FROM argument of `query-replace' commands.
43 The value of this variable should be a symbol; that symbol
44 is used as a variable to hold a history list for the strings
45 or patterns to be replaced."
46 :group 'matching
47 :type 'symbol
48 :version "20.3")
49
50 (defcustom query-replace-to-history-variable 'query-replace-history
51 "History list to use for the TO argument of `query-replace' commands.
52 The value of this variable should be a symbol; that symbol
53 is used as a variable to hold a history list for replacement
54 strings or patterns."
55 :group 'matching
56 :type 'symbol
57 :version "20.3")
58
59 (defcustom query-replace-skip-read-only nil
60 "*Non-nil means `query-replace' and friends ignore read-only matches."
61 :type 'boolean
62 :group 'matching
63 :version "21.3")
64
65 (defun query-replace-read-args (string regexp-flag)
66 (barf-if-buffer-read-only)
67 (let (from to)
68 (if query-replace-interactive
69 (setq from (car (if regexp-flag regexp-search-ring search-ring)))
70 (setq from (read-from-minibuffer (format "%s: " string)
71 nil nil nil
72 query-replace-from-history-variable
73 nil t))
74 ;; Warn if user types \n or \t, but don't reject the input.
75 (if (string-match "\\\\[nt]" from)
76 (let ((match (match-string 0 from)))
77 (cond
78 ((string= match "\\n")
79 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
80 ((string= match "\\t")
81 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
82 (sit-for 2))))
83
84 (setq to (read-from-minibuffer (format "%s %s with: " string from)
85 nil nil nil
86 query-replace-to-history-variable from t))
87 (if (and transient-mark-mode mark-active)
88 (list from to current-prefix-arg (region-beginning) (region-end))
89 (list from to current-prefix-arg nil nil))))
90
91 (defun query-replace (from-string to-string &optional delimited start end)
92 "Replace some occurrences of FROM-STRING with TO-STRING.
93 As each match is found, the user must type a character saying
94 what to do with it. For directions, type \\[help-command] at that time.
95
96 In Transient Mark mode, if the mark is active, operate on the contents
97 of the region. Otherwise, operate from point to the end of the buffer.
98
99 If `query-replace-interactive' is non-nil, the last incremental search
100 string is used as FROM-STRING--you don't have to specify it with the
101 minibuffer.
102
103 Replacement transfers the case of the old text to the new text,
104 if `case-replace' and `case-fold-search'
105 are non-nil and FROM-STRING has no uppercase letters.
106 \(Preserving case means that if the string matched is all caps, or capitalized,
107 then its replacement is upcased or capitalized.)
108
109 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
110 only matches surrounded by word boundaries.
111 Fourth and fifth arg START and END specify the region to operate on.
112
113 To customize possible responses, change the \"bindings\" in `query-replace-map'."
114 (interactive (query-replace-read-args "Query replace" nil))
115 (perform-replace from-string to-string t nil delimited nil nil start end))
116
117 (define-key esc-map "%" 'query-replace)
118
119 (defun query-replace-regexp (regexp to-string &optional delimited start end)
120 "Replace some things after point matching REGEXP with TO-STRING.
121 As each match is found, the user must type a character saying
122 what to do with it. For directions, type \\[help-command] at that time.
123
124 In Transient Mark mode, if the mark is active, operate on the contents
125 of the region. Otherwise, operate from point to the end of the buffer.
126
127 If `query-replace-interactive' is non-nil, the last incremental search
128 regexp is used as REGEXP--you don't have to specify it with the
129 minibuffer.
130
131 Preserves case in each replacement if `case-replace' and `case-fold-search'
132 are non-nil and REGEXP has no uppercase letters.
133
134 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
135 only matches surrounded by word boundaries.
136 Fourth and fifth arg START and END specify the region to operate on.
137
138 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
139 and `\\=\\N' (where N is a digit) stands for
140 whatever what matched the Nth `\\(...\\)' in REGEXP."
141 (interactive (query-replace-read-args "Query replace regexp" t))
142 (perform-replace regexp to-string t t delimited nil nil start end))
143 (define-key esc-map [?\C-%] 'query-replace-regexp)
144
145 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
146 "Replace some things after point matching REGEXP with the result of TO-EXPR.
147 As each match is found, the user must type a character saying
148 what to do with it. For directions, type \\[help-command] at that time.
149
150 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
151 reference `replace-count' to get the number of replacements already made.
152 If the result of TO-EXPR is not a string, it is converted to one using
153 `prin1-to-string' with the NOESCAPE argument (which see).
154
155 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
156 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
157 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
158 Use `\\#&' or `\\#N' if you want a number instead of a string.
159
160 In Transient Mark mode, if the mark is active, operate on the contents
161 of the region. Otherwise, operate from point to the end of the buffer.
162
163 If `query-replace-interactive' is non-nil, the last incremental search
164 regexp is used as REGEXP--you don't have to specify it with the
165 minibuffer.
166
167 Preserves case in each replacement if `case-replace' and `case-fold-search'
168 are non-nil and REGEXP has no uppercase letters.
169
170 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
171 only matches that are surrounded by word boundaries.
172 Fourth and fifth arg START and END specify the region to operate on."
173 (interactive
174 (let (from to start end)
175 (when (and transient-mark-mode mark-active)
176 (setq start (region-beginning)
177 end (region-end)))
178 (if query-replace-interactive
179 (setq from (car regexp-search-ring))
180 (setq from (read-from-minibuffer "Query replace regexp: "
181 nil nil nil
182 query-replace-from-history-variable
183 nil t)))
184 (setq to (list (read-from-minibuffer
185 (format "Query replace regexp %s with eval: " from)
186 nil nil t query-replace-to-history-variable from t)))
187 ;; We make TO a list because replace-match-string-symbols requires one,
188 ;; and the user might enter a single token.
189 (replace-match-string-symbols to)
190 (list from (car to) current-prefix-arg start end)))
191 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
192 t t delimited nil nil start end))
193
194 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
195 "Replace some matches for REGEXP with various strings, in rotation.
196 The second argument TO-STRINGS contains the replacement strings,
197 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
198 if non-nil, means replace only matches surrounded by word boundaries.
199 This command works like `query-replace-regexp' except that each
200 successive replacement uses the next successive replacement string,
201 wrapping around from the last such string to the first.
202
203 In Transient Mark mode, if the mark is active, operate on the contents
204 of the region. Otherwise, operate from point to the end of the buffer.
205
206 Non-interactively, TO-STRINGS may be a list of replacement strings.
207
208 If `query-replace-interactive' is non-nil, the last incremental search
209 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
210
211 A prefix argument N says to use each replacement string N times
212 before rotating to the next.
213 Fourth and fifth arg START and END specify the region to operate on."
214 (interactive
215 (let (from to start end)
216 (when (and transient-mark-mode mark-active)
217 (setq start (region-beginning)
218 end (region-end)))
219 (setq from (if query-replace-interactive
220 (car regexp-search-ring)
221 (read-from-minibuffer "Map query replace (regexp): "
222 nil nil nil
223 'query-replace-history nil t)))
224 (setq to (read-from-minibuffer
225 (format "Query replace %s with (space-separated strings): "
226 from)
227 nil nil nil
228 'query-replace-history from t))
229 (list from to start end current-prefix-arg)))
230 (let (replacements)
231 (if (listp to-strings)
232 (setq replacements to-strings)
233 (while (/= (length to-strings) 0)
234 (if (string-match " " to-strings)
235 (setq replacements
236 (append replacements
237 (list (substring to-strings 0
238 (string-match " " to-strings))))
239 to-strings (substring to-strings
240 (1+ (string-match " " to-strings))))
241 (setq replacements (append replacements (list to-strings))
242 to-strings ""))))
243 (perform-replace regexp replacements t t nil n nil start end)))
244
245 (defun replace-string (from-string to-string &optional delimited start end)
246 "Replace occurrences of FROM-STRING with TO-STRING.
247 Preserve case in each match if `case-replace' and `case-fold-search'
248 are non-nil and FROM-STRING has no uppercase letters.
249 \(Preserving case means that if the string matched is all caps, or capitalized,
250 then its replacement is upcased or capitalized.)
251
252 In Transient Mark mode, if the mark is active, operate on the contents
253 of the region. Otherwise, operate from point to the end of the buffer.
254
255 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
256 only matches surrounded by word boundaries.
257 Fourth and fifth arg START and END specify the region to operate on.
258
259 If `query-replace-interactive' is non-nil, the last incremental search
260 string is used as FROM-STRING--you don't have to specify it with the
261 minibuffer.
262
263 This function is usually the wrong thing to use in a Lisp program.
264 What you probably want is a loop like this:
265 (while (search-forward FROM-STRING nil t)
266 (replace-match TO-STRING nil t))
267 which will run faster and will not set the mark or print anything.
268 \(You may need a more complex loop if FROM-STRING can match the null string
269 and TO-STRING is also null.)"
270 (interactive (query-replace-read-args "Replace string" nil))
271 (perform-replace from-string to-string nil nil delimited nil nil start end))
272
273 (defun replace-regexp (regexp to-string &optional delimited start end)
274 "Replace things after point matching REGEXP with TO-STRING.
275 Preserve case in each match if `case-replace' and `case-fold-search'
276 are non-nil and REGEXP has no uppercase letters.
277
278 In Transient Mark mode, if the mark is active, operate on the contents
279 of the region. Otherwise, operate from point to the end of the buffer.
280
281 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
282 only matches surrounded by word boundaries.
283 Fourth and fifth arg START and END specify the region to operate on.
284
285 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
286 and `\\=\\N' (where N is a digit) stands for
287 whatever what matched the Nth `\\(...\\)' in REGEXP.
288
289 If `query-replace-interactive' is non-nil, the last incremental search
290 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
291
292 This function is usually the wrong thing to use in a Lisp program.
293 What you probably want is a loop like this:
294 (while (re-search-forward REGEXP nil t)
295 (replace-match TO-STRING nil nil))
296 which will run faster and will not set the mark or print anything."
297 (interactive (query-replace-read-args "Replace regexp" t))
298 (perform-replace regexp to-string nil t delimited nil nil start end))
299
300 \f
301 (defvar regexp-history nil
302 "History list for some commands that read regular expressions.")
303
304
305 (defalias 'delete-non-matching-lines 'keep-lines)
306 (defalias 'delete-matching-lines 'flush-lines)
307 (defalias 'count-matches 'how-many)
308
309
310 (defun keep-lines-read-args (prompt)
311 "Read arguments for `keep-lines' and friends.
312 Prompt for a regexp with PROMPT.
313 Value is a list, (REGEXP)."
314 (list (read-from-minibuffer prompt nil nil nil
315 'regexp-history nil t)))
316
317 (defun keep-lines (regexp &optional rstart rend)
318 "Delete all lines except those containing matches for REGEXP.
319 A match split across lines preserves all the lines it lies in.
320 Applies to all lines after point.
321
322 If REGEXP contains upper case characters (excluding those preceded by `\\'),
323 the matching is case-sensitive.
324
325 Second and third arg RSTART and REND specify the region to operate on.
326
327 Interactively, in Transient Mark mode when the mark is active, operate
328 on the contents of the region. Otherwise, operate from point to the
329 end of the buffer."
330
331 (interactive
332 (keep-lines-read-args "Keep lines (containing match for regexp): "))
333 (if rstart
334 (goto-char (min rstart rend))
335 (if (and transient-mark-mode mark-active)
336 (setq rstart (region-beginning)
337 rend (copy-marker (region-end)))
338 (setq rstart (point)
339 rend (point-max-marker)))
340 (goto-char rstart))
341 (save-excursion
342 (or (bolp) (forward-line 1))
343 (let ((start (point))
344 (case-fold-search (and case-fold-search
345 (isearch-no-upper-case-p regexp t))))
346 (while (< (point) rend)
347 ;; Start is first char not preserved by previous match.
348 (if (not (re-search-forward regexp rend 'move))
349 (delete-region start rend)
350 (let ((end (save-excursion (goto-char (match-beginning 0))
351 (beginning-of-line)
352 (point))))
353 ;; Now end is first char preserved by the new match.
354 (if (< start end)
355 (delete-region start end))))
356
357 (setq start (save-excursion (forward-line 1) (point)))
358 ;; If the match was empty, avoid matching again at same place.
359 (and (< (point) rend)
360 (= (match-beginning 0) (match-end 0))
361 (forward-char 1))))))
362
363
364 (defun flush-lines (regexp &optional rstart rend)
365 "Delete lines containing matches for REGEXP.
366 If a match is split across lines, all the lines it lies in are deleted.
367 Applies to lines after point.
368
369 If REGEXP contains upper case characters (excluding those preceded by `\\'),
370 the matching is case-sensitive.
371
372 Second and third arg RSTART and REND specify the region to operate on.
373
374 Interactively, in Transient Mark mode when the mark is active, operate
375 on the contents of the region. Otherwise, operate from point to the
376 end of the buffer."
377
378 (interactive
379 (keep-lines-read-args "Flush lines (containing match for regexp): "))
380 (if rstart
381 (goto-char (min rstart rend))
382 (if (and transient-mark-mode mark-active)
383 (setq rstart (region-beginning)
384 rend (copy-marker (region-end)))
385 (setq rstart (point)
386 rend (point-max-marker)))
387 (goto-char rstart))
388 (let ((case-fold-search (and case-fold-search
389 (isearch-no-upper-case-p regexp t))))
390 (save-excursion
391 (while (and (< (point) rend)
392 (re-search-forward regexp rend t))
393 (delete-region (save-excursion (goto-char (match-beginning 0))
394 (beginning-of-line)
395 (point))
396 (progn (forward-line 1) (point)))))))
397
398
399 (defun how-many (regexp &optional rstart rend)
400 "Print number of matches for REGEXP following point.
401
402 If REGEXP contains upper case characters (excluding those preceded by `\\'),
403 the matching is case-sensitive.
404
405 Second and third arg RSTART and REND specify the region to operate on.
406
407 Interactively, in Transient Mark mode when the mark is active, operate
408 on the contents of the region. Otherwise, operate from point to the
409 end of the buffer."
410
411 (interactive
412 (keep-lines-read-args "How many matches for (regexp): "))
413 (save-excursion
414 (if rstart
415 (goto-char (min rstart rend))
416 (if (and transient-mark-mode mark-active)
417 (setq rstart (region-beginning)
418 rend (copy-marker (region-end)))
419 (setq rstart (point)
420 rend (point-max-marker)))
421 (goto-char rstart))
422 (let ((count 0)
423 opoint
424 (case-fold-search (and case-fold-search
425 (isearch-no-upper-case-p regexp t))))
426 (while (and (< (point) rend)
427 (progn (setq opoint (point))
428 (re-search-forward regexp rend t)))
429 (if (= opoint (point))
430 (forward-char 1)
431 (setq count (1+ count))))
432 (message "%d occurrences" count))))
433
434 \f
435 (defvar occur-mode-map
436 (let ((map (make-sparse-keymap)))
437 (define-key map [mouse-2] 'occur-mode-mouse-goto)
438 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
439 (define-key map "\C-m" 'occur-mode-goto-occurrence)
440 (define-key map "\o" 'occur-mode-goto-occurrence-other-window)
441 (define-key map "\C-o" 'occur-mode-display-occurrence)
442 (define-key map "\M-n" 'occur-next)
443 (define-key map "\M-p" 'occur-prev)
444 (define-key map "g" 'revert-buffer)
445 map)
446 "Keymap for `occur-mode'.")
447
448
449 (defvar occur-buffer nil
450 "Name of buffer for last occur.")
451
452
453 (defvar occur-nlines nil
454 "Number of lines of context to show around matching line.")
455
456 (defvar occur-command-arguments nil
457 "Arguments that were given to `occur' when it made this buffer.")
458
459 (put 'occur-mode 'mode-class 'special)
460
461 (defun occur-mode ()
462 "Major mode for output from \\[occur].
463 \\<occur-mode-map>Move point to one of the items in this buffer, then use
464 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
465 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
466
467 \\{occur-mode-map}"
468 (kill-all-local-variables)
469 (use-local-map occur-mode-map)
470 (setq major-mode 'occur-mode)
471 (setq mode-name "Occur")
472 (make-local-variable 'revert-buffer-function)
473 (setq revert-buffer-function 'occur-revert-function)
474 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
475 (make-local-variable 'occur-buffer)
476 (make-local-variable 'occur-nlines)
477 (make-local-variable 'occur-command-arguments)
478 (run-hooks 'occur-mode-hook))
479
480 (defun occur-revert-function (ignore1 ignore2)
481 "Handle `revert-buffer' for *Occur* buffers."
482 (let ((args occur-command-arguments ))
483 (save-excursion
484 (set-buffer occur-buffer)
485 (apply 'occur args))))
486
487 (defun occur-mode-mouse-goto (event)
488 "In Occur mode, go to the occurrence whose line you click on."
489 (interactive "e")
490 (let (buffer pos)
491 (save-excursion
492 (set-buffer (window-buffer (posn-window (event-end event))))
493 (save-excursion
494 (goto-char (posn-point (event-end event)))
495 (setq pos (occur-mode-find-occurrence))
496 (setq buffer occur-buffer)))
497 (pop-to-buffer buffer)
498 (goto-char (marker-position pos))))
499
500 (defun occur-mode-find-occurrence ()
501 (if (or (null occur-buffer)
502 (null (buffer-name occur-buffer)))
503 (progn
504 (setq occur-buffer nil)
505 (error "Buffer in which occurrences were found is deleted")))
506 (let ((pos (get-text-property (point) 'occur)))
507 (if (null pos)
508 (error "No occurrence on this line")
509 pos)))
510
511 (defun occur-mode-goto-occurrence ()
512 "Go to the occurrence the current line describes."
513 (interactive)
514 (let ((pos (occur-mode-find-occurrence)))
515 (pop-to-buffer occur-buffer)
516 (goto-char (marker-position pos))))
517
518 (defun occur-mode-goto-occurrence-other-window ()
519 "Go to the occurrence the current line describes, in another window."
520 (interactive)
521 (let ((pos (occur-mode-find-occurrence)))
522 (switch-to-buffer-other-window occur-buffer)
523 (goto-char (marker-position pos))))
524
525 (defun occur-mode-display-occurrence ()
526 "Display in another window the occurrence the current line describes."
527 (interactive)
528 (let ((pos (occur-mode-find-occurrence))
529 same-window-buffer-names
530 same-window-regexps
531 window)
532 (setq window (display-buffer occur-buffer))
533 ;; This is the way to set point in the proper window.
534 (save-selected-window
535 (select-window window)
536 (goto-char (marker-position pos)))))
537
538 (defun occur-next (&optional n)
539 "Move to the Nth (default 1) next match in the *Occur* buffer."
540 (interactive "p")
541 (if (not n) (setq n 1))
542 (let ((r))
543 (while (> n 0)
544 (if (get-text-property (point) 'occur-point)
545 (forward-char 1))
546 (setq r (next-single-property-change (point) 'occur-point))
547 (if r
548 (goto-char r)
549 (error "No more matches"))
550 (setq n (1- n)))))
551
552
553
554 (defun occur-prev (&optional n)
555 "Move to the Nth (default 1) previous match in the *Occur* buffer."
556 (interactive "p")
557 (if (not n) (setq n 1))
558 (let ((r))
559 (while (> n 0)
560
561 (setq r (get-text-property (point) 'occur-point))
562 (if r (forward-char -1))
563
564 (setq r (previous-single-property-change (point) 'occur-point))
565 (if r
566 (goto-char (- r 1))
567 (error "No earlier matches"))
568
569 (setq n (1- n)))))
570 \f
571 (defcustom list-matching-lines-default-context-lines 0
572 "*Default number of context lines included around `list-matching-lines' matches.
573 A negative number means to include that many lines before the match.
574 A positive number means to include that many lines both before and after."
575 :type 'integer
576 :group 'matching)
577
578 (defalias 'list-matching-lines 'occur)
579
580 (defvar list-matching-lines-face 'bold
581 "*Face used by \\[list-matching-lines] to show the text that matches.
582 If the value is nil, don't highlight the matching portions specially.")
583
584 (defun occur (regexp &optional nlines)
585 "Show all lines in the current buffer containing a match for REGEXP.
586
587 If a match spreads across multiple lines, all those lines are shown.
588
589 Each line is displayed with NLINES lines before and after, or -NLINES
590 before if NLINES is negative.
591 NLINES defaults to `list-matching-lines-default-context-lines'.
592 Interactively it is the prefix arg.
593
594 The lines are shown in a buffer named `*Occur*'.
595 It serves as a menu to find any of the occurrences in this buffer.
596 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
597
598 If REGEXP contains upper case characters (excluding those preceded by `\\'),
599 the matching is case-sensitive."
600 (interactive
601 (list (let* ((default (car regexp-history))
602 (input
603 (read-from-minibuffer
604 (if default
605 (format "List lines matching regexp (default `%s'): "
606 default)
607 "List lines matching regexp: ")
608 nil nil nil 'regexp-history default t)))
609 (and (equal input "") default
610 (setq input default))
611 input)
612 current-prefix-arg))
613 (let* ((nlines (if nlines
614 (prefix-numeric-value nlines)
615 list-matching-lines-default-context-lines))
616 (current-tab-width tab-width)
617 (inhibit-read-only t)
618 ;; Minimum width of line number plus trailing colon.
619 (min-line-number-width 6)
620 ;; Width of line number prefix without the colon. Choose a
621 ;; width that's a multiple of `tab-width' in the original
622 ;; buffer so that lines in *Occur* appear right.
623 (line-number-width (1- (* (/ (- (+ min-line-number-width
624 tab-width)
625 1)
626 tab-width)
627 tab-width)))
628 ;; Format string for line numbers.
629 (line-number-format (format "%%%dd" line-number-width))
630 (empty (make-string line-number-width ?\ ))
631 (first t)
632 ;;flag to prevent printing separator for first match
633 (occur-num-matches 0)
634 (buffer (current-buffer))
635 (dir default-directory)
636 (linenum 1)
637 (prevpos
638 ;;position of most recent match
639 (point-min))
640 (case-fold-search (and case-fold-search
641 (isearch-no-upper-case-p regexp t)))
642 (final-context-start
643 ;; Marker to the start of context immediately following
644 ;; the matched text in *Occur*.
645 (make-marker)))
646 ;;; (save-excursion
647 ;;; (beginning-of-line)
648 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
649 ;;; (setq prevpos (point)))
650 (save-excursion
651 (goto-char (point-min))
652 ;; Check first whether there are any matches at all.
653 (if (not (re-search-forward regexp nil t))
654 (message "No matches for `%s'" regexp)
655 ;; Back up, so the search loop below will find the first match.
656 (goto-char (match-beginning 0))
657 (with-output-to-temp-buffer "*Occur*"
658 (save-excursion
659 (set-buffer standard-output)
660 (setq default-directory dir)
661 ;; We will insert the number of lines, and "lines", later.
662 (insert " matching ")
663 (let ((print-escape-newlines t))
664 (prin1 regexp))
665 (insert " in buffer " (buffer-name buffer) ?. ?\n)
666 (occur-mode)
667 (setq occur-buffer buffer)
668 (setq occur-nlines nlines)
669 (setq occur-command-arguments
670 (list regexp nlines)))
671 (if (eq buffer standard-output)
672 (goto-char (point-max)))
673 (save-excursion
674 ;; Find next match, but give up if prev match was at end of buffer.
675 (while (and (not (eobp))
676 (re-search-forward regexp nil t))
677 (goto-char (match-beginning 0))
678 (beginning-of-line)
679 (save-match-data
680 (setq linenum (+ linenum (count-lines prevpos (point)))))
681 (setq prevpos (point))
682 (goto-char (match-end 0))
683 (let* (;;start point of text in source buffer to be put
684 ;;into *Occur*
685 (start (save-excursion
686 (goto-char (match-beginning 0))
687 (forward-line (if (< nlines 0)
688 nlines
689 (- nlines)))
690 (point)))
691 ;; end point of text in source buffer to be put
692 ;; into *Occur*
693 (end (save-excursion
694 (goto-char (match-end 0))
695 (if (> nlines 0)
696 (forward-line (1+ nlines))
697 (forward-line 1))
698 (point)))
699 ;; Amount of context before matching text
700 (match-beg (- (match-beginning 0) start))
701 ;; Length of matching text
702 (match-len (- (match-end 0) (match-beginning 0)))
703 (tag (format line-number-format linenum))
704 tem
705 insertion-start
706 ;; Number of lines of context to show for current match.
707 occur-marker
708 ;; Marker pointing to end of match in source buffer.
709 (text-beg
710 ;; Marker pointing to start of text for one
711 ;; match in *Occur*.
712 (make-marker))
713 (text-end
714 ;; Marker pointing to end of text for one match
715 ;; in *Occur*.
716 (make-marker)))
717 (save-excursion
718 (setq occur-marker (make-marker))
719 (set-marker occur-marker (point))
720 (set-buffer standard-output)
721 (setq occur-num-matches (1+ occur-num-matches))
722 (or first (zerop nlines)
723 (insert "--------\n"))
724 (setq first nil)
725 (save-excursion
726 (set-buffer "*Occur*")
727 (setq tab-width current-tab-width))
728
729 ;; Insert matching text including context lines from
730 ;; source buffer into *Occur*
731 (set-marker text-beg (point))
732 (setq insertion-start (point))
733 (insert-buffer-substring buffer start end)
734 (or (and (/= (+ start match-beg) end)
735 (with-current-buffer buffer
736 (eq (char-before end) ?\n)))
737 (insert "\n"))
738 (set-marker final-context-start
739 (+ (- (point) (- end (match-end 0)))
740 (if (save-excursion
741 (set-buffer buffer)
742 (save-excursion
743 (goto-char (match-end 0))
744 (end-of-line)
745 (bolp)))
746 1 0)))
747 (set-marker text-end (point))
748
749 ;; Highlight text that was matched.
750 (if list-matching-lines-face
751 (put-text-property
752 (+ (marker-position text-beg) match-beg)
753 (+ (marker-position text-beg) match-beg match-len)
754 'face list-matching-lines-face))
755
756 ;; `occur-point' property is used by occur-next and
757 ;; occur-prev to move between matching lines.
758 (put-text-property
759 (+ (marker-position text-beg) match-beg match-len)
760 (+ (marker-position text-beg) match-beg match-len 1)
761 'occur-point t)
762
763 ;; Now go back to the start of the matching text
764 ;; adding the space and colon to the start of each line.
765 (goto-char insertion-start)
766 ;; Insert space and colon for lines of context before match.
767 (setq tem (if (< linenum nlines)
768 (- nlines linenum)
769 nlines))
770 (while (> tem 0)
771 (insert empty ?:)
772 (forward-line 1)
773 (setq tem (1- tem)))
774
775 ;; Insert line number and colon for the lines of
776 ;; matching text.
777 (let ((this-linenum linenum))
778 (while (< (point) final-context-start)
779 (if (null tag)
780 (setq tag (format line-number-format this-linenum)))
781 (insert tag ?:)
782 (forward-line 1)
783 (setq tag nil)
784 (setq this-linenum (1+ this-linenum)))
785 (while (and (not (eobp)) (<= (point) final-context-start))
786 (insert empty ?:)
787 (forward-line 1)
788 (setq this-linenum (1+ this-linenum))))
789
790 ;; Insert space and colon for lines of context after match.
791 (while (and (< (point) (point-max)) (< tem nlines))
792 (insert empty ?:)
793 (forward-line 1)
794 (setq tem (1+ tem)))
795
796 ;; Add text properties. The `occur' prop is used to
797 ;; store the marker of the matching text in the
798 ;; source buffer.
799 (add-text-properties
800 (marker-position text-beg) (- (marker-position text-end) 1)
801 '(mouse-face highlight
802 help-echo "mouse-2: go to this occurrence"))
803 (put-text-property (marker-position text-beg)
804 (marker-position text-end)
805 'occur occur-marker)
806 (goto-char (point-max)))
807 (forward-line 1)))
808 (set-buffer standard-output)
809 ;; Go back to top of *Occur* and finish off by printing the
810 ;; number of matching lines.
811 (goto-char (point-min))
812 (let ((message-string
813 (if (= occur-num-matches 1)
814 "1 line"
815 (format "%d lines" occur-num-matches))))
816 (insert message-string)
817 (if (interactive-p)
818 (message "%s matched" message-string)))
819 (setq buffer-read-only t)))))))
820 \f
821 ;; It would be nice to use \\[...], but there is no reasonable way
822 ;; to make that display both SPC and Y.
823 (defconst query-replace-help
824 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
825 RET or `q' to exit, Period to replace one match and exit,
826 Comma to replace but not move point immediately,
827 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
828 C-w to delete match and recursive edit,
829 C-l to clear the screen, redisplay, and offer same replacement again,
830 ! to replace all remaining matches with no more questions,
831 ^ to move point back to previous match,
832 E to edit the replacement string"
833 "Help message while in `query-replace'.")
834
835 (defvar query-replace-map (make-sparse-keymap)
836 "Keymap that defines the responses to questions in `query-replace'.
837 The \"bindings\" in this map are not commands; they are answers.
838 The valid answers include `act', `skip', `act-and-show',
839 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
840 `automatic', `backup', `exit-prefix', and `help'.")
841
842 (define-key query-replace-map " " 'act)
843 (define-key query-replace-map "\d" 'skip)
844 (define-key query-replace-map [delete] 'skip)
845 (define-key query-replace-map [backspace] 'skip)
846 (define-key query-replace-map "y" 'act)
847 (define-key query-replace-map "n" 'skip)
848 (define-key query-replace-map "Y" 'act)
849 (define-key query-replace-map "N" 'skip)
850 (define-key query-replace-map "e" 'edit-replacement)
851 (define-key query-replace-map "E" 'edit-replacement)
852 (define-key query-replace-map "," 'act-and-show)
853 (define-key query-replace-map "q" 'exit)
854 (define-key query-replace-map "\r" 'exit)
855 (define-key query-replace-map [return] 'exit)
856 (define-key query-replace-map "." 'act-and-exit)
857 (define-key query-replace-map "\C-r" 'edit)
858 (define-key query-replace-map "\C-w" 'delete-and-edit)
859 (define-key query-replace-map "\C-l" 'recenter)
860 (define-key query-replace-map "!" 'automatic)
861 (define-key query-replace-map "^" 'backup)
862 (define-key query-replace-map "\C-h" 'help)
863 (define-key query-replace-map [f1] 'help)
864 (define-key query-replace-map [help] 'help)
865 (define-key query-replace-map "?" 'help)
866 (define-key query-replace-map "\C-g" 'quit)
867 (define-key query-replace-map "\C-]" 'quit)
868 (define-key query-replace-map "\e" 'exit-prefix)
869 (define-key query-replace-map [escape] 'exit-prefix)
870
871 (defun replace-match-string-symbols (n)
872 "Process a list (and any sub-lists), expanding certain symbols.
873 Symbol Expands To
874 N (match-string N) (where N is a string of digits)
875 #N (string-to-number (match-string N))
876 & (match-string 0)
877 #& (string-to-number (match-string 0))
878
879 Note that these symbols must be preceeded by a backslash in order to
880 type them."
881 (while n
882 (cond
883 ((consp (car n))
884 (replace-match-string-symbols (car n))) ;Process sub-list
885 ((symbolp (car n))
886 (let ((name (symbol-name (car n))))
887 (cond
888 ((string-match "^[0-9]+$" name)
889 (setcar n (list 'match-string (string-to-number name))))
890 ((string-match "^#[0-9]+$" name)
891 (setcar n (list 'string-to-number
892 (list 'match-string
893 (string-to-number (substring name 1))))))
894 ((string= "&" name)
895 (setcar n '(match-string 0)))
896 ((string= "#&" name)
897 (setcar n '(string-to-number (match-string 0))))))))
898 (setq n (cdr n))))
899
900 (defun replace-eval-replacement (expression replace-count)
901 (let ((replacement (eval expression)))
902 (if (stringp replacement)
903 replacement
904 (prin1-to-string replacement t))))
905
906 (defun replace-loop-through-replacements (data replace-count)
907 ;; DATA is a vector contaning the following values:
908 ;; 0 next-rotate-count
909 ;; 1 repeat-count
910 ;; 2 next-replacement
911 ;; 3 replacements
912 (if (= (aref data 0) replace-count)
913 (progn
914 (aset data 0 (+ replace-count (aref data 1)))
915 (let ((next (cdr (aref data 2))))
916 (aset data 2 (if (consp next) next (aref data 3))))))
917 (car (aref data 2)))
918
919 (defun perform-replace (from-string replacements
920 query-flag regexp-flag delimited-flag
921 &optional repeat-count map start end)
922 "Subroutine of `query-replace'. Its complexity handles interactive queries.
923 Don't use this in your own program unless you want to query and set the mark
924 just as `query-replace' does. Instead, write a simple loop like this:
925
926 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
927 (replace-match \"foobar\" nil nil))
928
929 which will run faster and probably do exactly what you want. Please
930 see the documentation of `replace-match' to find out how to simulate
931 `case-replace'."
932 (or map (setq map query-replace-map))
933 (and query-flag minibuffer-auto-raise
934 (raise-frame (window-frame (minibuffer-window))))
935 (let ((nocasify (not (and case-fold-search case-replace
936 (string-equal from-string
937 (downcase from-string)))))
938 (case-fold-search (and case-fold-search
939 (string-equal from-string
940 (downcase from-string))))
941 (literal (not regexp-flag))
942 (search-function (if regexp-flag 're-search-forward 'search-forward))
943 (search-string from-string)
944 (real-match-data nil) ; the match data for the current match
945 (next-replacement nil)
946 (keep-going t)
947 (stack nil)
948 (replace-count 0)
949 (nonempty-match nil)
950
951 ;; If non-nil, it is marker saying where in the buffer to stop.
952 (limit nil)
953
954 ;; Data for the next match. If a cons, it has the same format as
955 ;; (match-data); otherwise it is t if a match is possible at point.
956 (match-again t)
957
958 (message
959 (if query-flag
960 (substitute-command-keys
961 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
962
963 ;; If region is active, in Transient Mark mode, operate on region.
964 (when start
965 (setq limit (copy-marker (max start end)))
966 (goto-char (min start end))
967 (deactivate-mark))
968
969 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
970 ;; containing a function and its first argument. The function is
971 ;; called to generate each replacement like this:
972 ;; (funcall (car replacements) (cdr replacements) replace-count)
973 ;; It must return a string.
974 (cond
975 ((stringp replacements)
976 (setq next-replacement replacements
977 replacements nil))
978 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
979 (or repeat-count (setq repeat-count 1))
980 (setq replacements (cons 'replace-loop-through-replacements
981 (vector repeat-count repeat-count
982 replacements replacements)))))
983
984 (if delimited-flag
985 (setq search-function 're-search-forward
986 search-string (concat "\\b"
987 (if regexp-flag from-string
988 (regexp-quote from-string))
989 "\\b")))
990 (push-mark)
991 (undo-boundary)
992 (unwind-protect
993 ;; Loop finding occurrences that perhaps should be replaced.
994 (while (and keep-going
995 (not (eobp))
996 ;; Use the next match if it is already known;
997 ;; otherwise, search for a match after moving forward
998 ;; one char if progress is required.
999 (setq real-match-data
1000 (if (consp match-again)
1001 (progn (goto-char (nth 1 match-again))
1002 match-again)
1003 (and (or match-again
1004 ;; MATCH-AGAIN non-nil means we
1005 ;; accept an adjacent match. If
1006 ;; we don't, move one char to the
1007 ;; right. This takes us a
1008 ;; character too far at the end,
1009 ;; but this is undone after the
1010 ;; while-loop.
1011 (progn (forward-char 1) (not (eobp))))
1012 (funcall search-function search-string limit t)
1013 ;; For speed, use only integers and
1014 ;; reuse the list used last time.
1015 (match-data t real-match-data)))))
1016 ;; Optionally ignore matches that have a read-only property.
1017 (unless (and query-replace-skip-read-only
1018 (text-property-not-all
1019 (match-beginning 0) (match-end 0)
1020 'read-only nil))
1021
1022 ;; Record whether the match is nonempty, to avoid an infinite loop
1023 ;; repeatedly matching the same empty string.
1024 (setq nonempty-match
1025 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1026
1027 ;; If the match is empty, record that the next one can't be
1028 ;; adjacent.
1029
1030 ;; Otherwise, if matching a regular expression, do the next
1031 ;; match now, since the replacement for this match may
1032 ;; affect whether the next match is adjacent to this one.
1033 ;; If that match is empty, don't use it.
1034 (setq match-again
1035 (and nonempty-match
1036 (or (not regexp-flag)
1037 (and (looking-at search-string)
1038 (let ((match (match-data)))
1039 (and (/= (nth 0 match) (nth 1 match))
1040 match))))))
1041
1042 ;; Calculate the replacement string, if necessary.
1043 (when replacements
1044 (set-match-data real-match-data)
1045 (setq next-replacement
1046 (funcall (car replacements) (cdr replacements)
1047 replace-count)))
1048 (if (not query-flag)
1049 (let ((inhibit-read-only query-replace-skip-read-only))
1050 (set-match-data real-match-data)
1051 (replace-match next-replacement nocasify literal)
1052 (setq replace-count (1+ replace-count)))
1053 (undo-boundary)
1054 (let (done replaced key def)
1055 ;; Loop reading commands until one of them sets done,
1056 ;; which means it has finished handling this occurrence.
1057 (while (not done)
1058 (set-match-data real-match-data)
1059 (replace-highlight (match-beginning 0) (match-end 0))
1060 ;; Bind message-log-max so we don't fill up the message log
1061 ;; with a bunch of identical messages.
1062 (let ((message-log-max nil))
1063 (message message from-string next-replacement))
1064 (setq key (read-event))
1065 ;; Necessary in case something happens during read-event
1066 ;; that clobbers the match data.
1067 (set-match-data real-match-data)
1068 (setq key (vector key))
1069 (setq def (lookup-key map key))
1070 ;; Restore the match data while we process the command.
1071 (cond ((eq def 'help)
1072 (with-output-to-temp-buffer "*Help*"
1073 (princ
1074 (concat "Query replacing "
1075 (if regexp-flag "regexp " "")
1076 from-string " with "
1077 next-replacement ".\n\n"
1078 (substitute-command-keys
1079 query-replace-help)))
1080 (with-current-buffer standard-output
1081 (help-mode))))
1082 ((eq def 'exit)
1083 (setq keep-going nil)
1084 (setq done t))
1085 ((eq def 'backup)
1086 (if stack
1087 (let ((elt (car stack)))
1088 (goto-char (car elt))
1089 (setq replaced (eq t (cdr elt)))
1090 (or replaced
1091 (set-match-data (cdr elt)))
1092 (setq stack (cdr stack)))
1093 (message "No previous match")
1094 (ding 'no-terminate)
1095 (sit-for 1)))
1096 ((eq def 'act)
1097 (or replaced
1098 (progn
1099 (replace-match next-replacement nocasify literal)
1100 (setq replace-count (1+ replace-count))))
1101 (setq done t replaced t))
1102 ((eq def 'act-and-exit)
1103 (or replaced
1104 (progn
1105 (replace-match next-replacement nocasify literal)
1106 (setq replace-count (1+ replace-count))))
1107 (setq keep-going nil)
1108 (setq done t replaced t))
1109 ((eq def 'act-and-show)
1110 (if (not replaced)
1111 (progn
1112 (replace-match next-replacement nocasify literal)
1113 (setq replace-count (1+ replace-count))
1114 (setq replaced t))))
1115 ((eq def 'automatic)
1116 (or replaced
1117 (progn
1118 (replace-match next-replacement nocasify literal)
1119 (setq replace-count (1+ replace-count))))
1120 (setq done t query-flag nil replaced t))
1121 ((eq def 'skip)
1122 (setq done t))
1123 ((eq def 'recenter)
1124 (recenter nil))
1125 ((eq def 'edit)
1126 (let ((opos (point-marker)))
1127 (goto-char (match-beginning 0))
1128 (save-excursion
1129 (funcall search-function search-string limit t)
1130 (setq real-match-data (match-data)))
1131 (save-excursion (recursive-edit))
1132 (goto-char opos))
1133 (set-match-data real-match-data)
1134 ;; Before we make the replacement,
1135 ;; decide whether the search string
1136 ;; can match again just after this match.
1137 (if (and regexp-flag nonempty-match)
1138 (setq match-again (and (looking-at search-string)
1139 (match-data)))))
1140
1141 ;; Edit replacement.
1142 ((eq def 'edit-replacement)
1143 (setq next-replacement
1144 (read-input "Edit replacement string: "
1145 next-replacement))
1146 (or replaced
1147 (replace-match next-replacement nocasify literal))
1148 (setq done t))
1149
1150 ((eq def 'delete-and-edit)
1151 (delete-region (match-beginning 0) (match-end 0))
1152 (set-match-data
1153 (prog1 (match-data)
1154 (save-excursion (recursive-edit))))
1155 (setq replaced t))
1156 ;; Note: we do not need to treat `exit-prefix'
1157 ;; specially here, since we reread
1158 ;; any unrecognized character.
1159 (t
1160 (setq this-command 'mode-exited)
1161 (setq keep-going nil)
1162 (setq unread-command-events
1163 (append (listify-key-sequence key)
1164 unread-command-events))
1165 (setq done t))))
1166 ;; Record previous position for ^ when we move on.
1167 ;; Change markers to numbers in the match data
1168 ;; since lots of markers slow down editing.
1169 (setq stack
1170 (cons (cons (point)
1171 (or replaced (match-data t)))
1172 stack))))))
1173
1174 ;; The code preventing adjacent regexp matches in the condition
1175 ;; of the while-loop above will haven taken us one character
1176 ;; beyond the last replacement. Undo that.
1177 (when (and regexp-flag (not match-again) (> replace-count 0))
1178 (backward-char 1))
1179
1180 (replace-dehighlight))
1181 (or unread-command-events
1182 (message "Replaced %d occurrence%s"
1183 replace-count
1184 (if (= replace-count 1) "" "s")))
1185 (and keep-going stack)))
1186
1187 (defcustom query-replace-highlight t
1188 "*Non-nil means to highlight words during query replacement."
1189 :type 'boolean
1190 :group 'matching)
1191
1192 (defvar replace-overlay nil)
1193
1194 (defun replace-dehighlight ()
1195 (and replace-overlay
1196 (progn
1197 (delete-overlay replace-overlay)
1198 (setq replace-overlay nil))))
1199
1200 (defun replace-highlight (start end)
1201 (and query-replace-highlight
1202 (progn
1203 (or replace-overlay
1204 (progn
1205 (setq replace-overlay (make-overlay start end))
1206 (overlay-put replace-overlay 'face
1207 (if (facep 'query-replace)
1208 'query-replace 'region))))
1209 (move-overlay replace-overlay start end (current-buffer)))))
1210
1211 ;;; replace.el ends here