]> code.delx.au - gnu-emacs/blob - lisp/replace.el
(f90-mode-abbrev-table): Mark all the predefined abbrevs as "system"
[gnu-emacs] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997, 2000, 2001
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 "\C-o" 'occur-mode-display-occurrence)
441 (define-key map "\M-n" 'occur-next)
442 (define-key map "\M-p" 'occur-prev)
443 (define-key map "g" 'revert-buffer)
444 map)
445 "Keymap for `occur-mode'.")
446
447
448 (defvar occur-buffer nil
449 "Name of buffer for last occur.")
450
451
452 (defvar occur-nlines nil
453 "Number of lines of context to show around matching line.")
454
455 (defvar occur-command-arguments nil
456 "Arguments that were given to `occur' when it made this buffer.")
457
458 (put 'occur-mode 'mode-class 'special)
459
460 (defun occur-mode ()
461 "Major mode for output from \\[occur].
462 \\<occur-mode-map>Move point to one of the items in this buffer, then use
463 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
464 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
465
466 \\{occur-mode-map}"
467 (kill-all-local-variables)
468 (use-local-map occur-mode-map)
469 (setq major-mode 'occur-mode)
470 (setq mode-name "Occur")
471 (make-local-variable 'revert-buffer-function)
472 (setq revert-buffer-function 'occur-revert-function)
473 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
474 (make-local-variable 'occur-buffer)
475 (make-local-variable 'occur-nlines)
476 (make-local-variable 'occur-command-arguments)
477 (run-hooks 'occur-mode-hook))
478
479 (defun occur-revert-function (ignore1 ignore2)
480 "Handle `revert-buffer' for *Occur* buffers."
481 (let ((args occur-command-arguments ))
482 (save-excursion
483 (set-buffer occur-buffer)
484 (apply 'occur args))))
485
486 (defun occur-mode-mouse-goto (event)
487 "In Occur mode, go to the occurrence whose line you click on."
488 (interactive "e")
489 (let (buffer pos)
490 (save-excursion
491 (set-buffer (window-buffer (posn-window (event-end event))))
492 (save-excursion
493 (goto-char (posn-point (event-end event)))
494 (setq pos (occur-mode-find-occurrence))
495 (setq buffer occur-buffer)))
496 (pop-to-buffer buffer)
497 (goto-char (marker-position pos))))
498
499 (defun occur-mode-find-occurrence ()
500 (if (or (null occur-buffer)
501 (null (buffer-name occur-buffer)))
502 (progn
503 (setq occur-buffer nil)
504 (error "Buffer in which occurrences were found is deleted")))
505 (let ((pos (get-text-property (point) 'occur)))
506 (if (null pos)
507 (error "No occurrence on this line")
508 pos)))
509
510 (defun occur-mode-goto-occurrence ()
511 "Go to the occurrence the current line describes."
512 (interactive)
513 (let ((pos (occur-mode-find-occurrence)))
514 (pop-to-buffer occur-buffer)
515 (goto-char (marker-position pos))))
516
517 (defun occur-mode-display-occurrence ()
518 "Display in another window the occurrence the current line describes."
519 (interactive)
520 (let ((pos (occur-mode-find-occurrence))
521 same-window-buffer-names
522 same-window-regexps
523 window)
524 (setq window (display-buffer occur-buffer))
525 ;; This is the way to set point in the proper window.
526 (save-selected-window
527 (select-window window)
528 (goto-char (marker-position pos)))))
529
530 (defun occur-next (&optional n)
531 "Move to the Nth (default 1) next match in the *Occur* buffer."
532 (interactive "p")
533 (if (not n) (setq n 1))
534 (let ((r))
535 (while (> n 0)
536 (if (get-text-property (point) 'occur-point)
537 (forward-char 1))
538 (setq r (next-single-property-change (point) 'occur-point))
539 (if r
540 (goto-char r)
541 (error "No more matches"))
542 (setq n (1- n)))))
543
544
545
546 (defun occur-prev (&optional n)
547 "Move to the Nth (default 1) previous match in the *Occur* buffer."
548 (interactive "p")
549 (if (not n) (setq n 1))
550 (let ((r))
551 (while (> n 0)
552
553 (setq r (get-text-property (point) 'occur-point))
554 (if r (forward-char -1))
555
556 (setq r (previous-single-property-change (point) 'occur-point))
557 (if r
558 (goto-char (- r 1))
559 (error "No earlier matches"))
560
561 (setq n (1- n)))))
562 \f
563 (defcustom list-matching-lines-default-context-lines 0
564 "*Default number of context lines included around `list-matching-lines' matches.
565 A negative number means to include that many lines before the match.
566 A positive number means to include that many lines both before and after."
567 :type 'integer
568 :group 'matching)
569
570 (defalias 'list-matching-lines 'occur)
571
572 (defvar list-matching-lines-face 'bold
573 "*Face used by \\[list-matching-lines] to show the text that matches.
574 If the value is nil, don't highlight the matching portions specially.")
575
576 (defun occur (regexp &optional nlines)
577 "Show all lines in the current buffer containing a match for REGEXP.
578
579 If a match spreads across multiple lines, all those lines are shown.
580
581 Each line is displayed with NLINES lines before and after, or -NLINES
582 before if NLINES is negative.
583 NLINES defaults to `list-matching-lines-default-context-lines'.
584 Interactively it is the prefix arg.
585
586 The lines are shown in a buffer named `*Occur*'.
587 It serves as a menu to find any of the occurrences in this buffer.
588 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
589
590 If REGEXP contains upper case characters (excluding those preceded by `\\'),
591 the matching is case-sensitive."
592 (interactive
593 (list (let* ((default (car regexp-history))
594 (input
595 (read-from-minibuffer
596 (if default
597 (format "List lines matching regexp (default `%s'): "
598 default)
599 "List lines matching regexp: ")
600 nil nil nil 'regexp-history default t)))
601 (and (equal input "") default
602 (setq input default))
603 input)
604 current-prefix-arg))
605 (let* ((nlines (if nlines
606 (prefix-numeric-value nlines)
607 list-matching-lines-default-context-lines))
608 (current-tab-width tab-width)
609 (inhibit-read-only t)
610 ;; Minimum width of line number plus trailing colon.
611 (min-line-number-width 6)
612 ;; Width of line number prefix without the colon. Choose a
613 ;; width that's a multiple of `tab-width' in the original
614 ;; buffer so that lines in *Occur* appear right.
615 (line-number-width (1- (* (/ (- (+ min-line-number-width
616 tab-width)
617 1)
618 tab-width)
619 tab-width)))
620 ;; Format string for line numbers.
621 (line-number-format (format "%%%dd" line-number-width))
622 (empty (make-string line-number-width ?\ ))
623 (first t)
624 ;;flag to prevent printing separator for first match
625 (occur-num-matches 0)
626 (buffer (current-buffer))
627 (dir default-directory)
628 (linenum 1)
629 (prevpos
630 ;;position of most recent match
631 (point-min))
632 (case-fold-search (and case-fold-search
633 (isearch-no-upper-case-p regexp t)))
634 (final-context-start
635 ;; Marker to the start of context immediately following
636 ;; the matched text in *Occur*.
637 (make-marker)))
638 ;;; (save-excursion
639 ;;; (beginning-of-line)
640 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
641 ;;; (setq prevpos (point)))
642 (save-excursion
643 (goto-char (point-min))
644 ;; Check first whether there are any matches at all.
645 (if (not (re-search-forward regexp nil t))
646 (message "No matches for `%s'" regexp)
647 ;; Back up, so the search loop below will find the first match.
648 (goto-char (match-beginning 0))
649 (with-output-to-temp-buffer "*Occur*"
650 (save-excursion
651 (set-buffer standard-output)
652 (setq default-directory dir)
653 ;; We will insert the number of lines, and "lines", later.
654 (insert " matching ")
655 (let ((print-escape-newlines t))
656 (prin1 regexp))
657 (insert " in buffer " (buffer-name buffer) ?. ?\n)
658 (occur-mode)
659 (setq occur-buffer buffer)
660 (setq occur-nlines nlines)
661 (setq occur-command-arguments
662 (list regexp nlines)))
663 (if (eq buffer standard-output)
664 (goto-char (point-max)))
665 (save-excursion
666 ;; Find next match, but give up if prev match was at end of buffer.
667 (while (and (not (eobp))
668 (re-search-forward regexp nil t))
669 (goto-char (match-beginning 0))
670 (beginning-of-line)
671 (save-match-data
672 (setq linenum (+ linenum (count-lines prevpos (point)))))
673 (setq prevpos (point))
674 (goto-char (match-end 0))
675 (let* (;;start point of text in source buffer to be put
676 ;;into *Occur*
677 (start (save-excursion
678 (goto-char (match-beginning 0))
679 (forward-line (if (< nlines 0)
680 nlines
681 (- nlines)))
682 (point)))
683 ;; end point of text in source buffer to be put
684 ;; into *Occur*
685 (end (save-excursion
686 (goto-char (match-end 0))
687 (if (> nlines 0)
688 (forward-line (1+ nlines))
689 (forward-line 1))
690 (point)))
691 ;; Amount of context before matching text
692 (match-beg (- (match-beginning 0) start))
693 ;; Length of matching text
694 (match-len (- (match-end 0) (match-beginning 0)))
695 (tag (format line-number-format linenum))
696 tem
697 insertion-start
698 ;; Number of lines of context to show for current match.
699 occur-marker
700 ;; Marker pointing to end of match in source buffer.
701 (text-beg
702 ;; Marker pointing to start of text for one
703 ;; match in *Occur*.
704 (make-marker))
705 (text-end
706 ;; Marker pointing to end of text for one match
707 ;; in *Occur*.
708 (make-marker)))
709 (save-excursion
710 (setq occur-marker (make-marker))
711 (set-marker occur-marker (point))
712 (set-buffer standard-output)
713 (setq occur-num-matches (1+ occur-num-matches))
714 (or first (zerop nlines)
715 (insert "--------\n"))
716 (setq first nil)
717 (save-excursion
718 (set-buffer "*Occur*")
719 (setq tab-width current-tab-width))
720
721 ;; Insert matching text including context lines from
722 ;; source buffer into *Occur*
723 (set-marker text-beg (point))
724 (setq insertion-start (point))
725 (insert-buffer-substring buffer start end)
726 (or (and (/= (+ start match-beg) end)
727 (with-current-buffer buffer
728 (eq (char-before end) ?\n)))
729 (insert "\n"))
730 (set-marker final-context-start
731 (+ (- (point) (- end (match-end 0)))
732 (if (save-excursion
733 (set-buffer buffer)
734 (save-excursion
735 (goto-char (match-end 0))
736 (end-of-line)
737 (bolp)))
738 1 0)))
739 (set-marker text-end (point))
740
741 ;; Highlight text that was matched.
742 (if list-matching-lines-face
743 (put-text-property
744 (+ (marker-position text-beg) match-beg)
745 (+ (marker-position text-beg) match-beg match-len)
746 'face list-matching-lines-face))
747
748 ;; `occur-point' property is used by occur-next and
749 ;; occur-prev to move between matching lines.
750 (put-text-property
751 (+ (marker-position text-beg) match-beg match-len)
752 (+ (marker-position text-beg) match-beg match-len 1)
753 'occur-point t)
754
755 ;; Now go back to the start of the matching text
756 ;; adding the space and colon to the start of each line.
757 (goto-char insertion-start)
758 ;; Insert space and colon for lines of context before match.
759 (setq tem (if (< linenum nlines)
760 (- nlines linenum)
761 nlines))
762 (while (> tem 0)
763 (insert empty ?:)
764 (forward-line 1)
765 (setq tem (1- tem)))
766
767 ;; Insert line number and colon for the lines of
768 ;; matching text.
769 (let ((this-linenum linenum))
770 (while (< (point) final-context-start)
771 (if (null tag)
772 (setq tag (format line-number-format this-linenum)))
773 (insert tag ?:)
774 (forward-line 1)
775 (setq tag nil)
776 (setq this-linenum (1+ this-linenum)))
777 (while (and (not (eobp)) (<= (point) final-context-start))
778 (insert empty ?:)
779 (forward-line 1)
780 (setq this-linenum (1+ this-linenum))))
781
782 ;; Insert space and colon for lines of context after match.
783 (while (and (< (point) (point-max)) (< tem nlines))
784 (insert empty ?:)
785 (forward-line 1)
786 (setq tem (1+ tem)))
787
788 ;; Add text properties. The `occur' prop is used to
789 ;; store the marker of the matching text in the
790 ;; source buffer.
791 (add-text-properties
792 (marker-position text-beg) (- (marker-position text-end) 1)
793 '(mouse-face highlight
794 help-echo "mouse-2: go to this occurence"))
795 (put-text-property (marker-position text-beg)
796 (marker-position text-end)
797 'occur occur-marker)
798 (goto-char (point-max)))
799 (forward-line 1)))
800 (set-buffer standard-output)
801 ;; Go back to top of *Occur* and finish off by printing the
802 ;; number of matching lines.
803 (goto-char (point-min))
804 (let ((message-string
805 (if (= occur-num-matches 1)
806 "1 line"
807 (format "%d lines" occur-num-matches))))
808 (insert message-string)
809 (if (interactive-p)
810 (message "%s matched" message-string)))
811 (setq buffer-read-only t)))))))
812 \f
813 ;; It would be nice to use \\[...], but there is no reasonable way
814 ;; to make that display both SPC and Y.
815 (defconst query-replace-help
816 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
817 RET or `q' to exit, Period to replace one match and exit,
818 Comma to replace but not move point immediately,
819 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
820 C-w to delete match and recursive edit,
821 C-l to clear the screen, redisplay, and offer same replacement again,
822 ! to replace all remaining matches with no more questions,
823 ^ to move point back to previous match,
824 E to edit the replacement string"
825 "Help message while in `query-replace'.")
826
827 (defvar query-replace-map (make-sparse-keymap)
828 "Keymap that defines the responses to questions in `query-replace'.
829 The \"bindings\" in this map are not commands; they are answers.
830 The valid answers include `act', `skip', `act-and-show',
831 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
832 `automatic', `backup', `exit-prefix', and `help'.")
833
834 (define-key query-replace-map " " 'act)
835 (define-key query-replace-map "\d" 'skip)
836 (define-key query-replace-map [delete] 'skip)
837 (define-key query-replace-map [backspace] 'skip)
838 (define-key query-replace-map "y" 'act)
839 (define-key query-replace-map "n" 'skip)
840 (define-key query-replace-map "Y" 'act)
841 (define-key query-replace-map "N" 'skip)
842 (define-key query-replace-map "e" 'edit-replacement)
843 (define-key query-replace-map "E" 'edit-replacement)
844 (define-key query-replace-map "," 'act-and-show)
845 (define-key query-replace-map "q" 'exit)
846 (define-key query-replace-map "\r" 'exit)
847 (define-key query-replace-map [return] 'exit)
848 (define-key query-replace-map "." 'act-and-exit)
849 (define-key query-replace-map "\C-r" 'edit)
850 (define-key query-replace-map "\C-w" 'delete-and-edit)
851 (define-key query-replace-map "\C-l" 'recenter)
852 (define-key query-replace-map "!" 'automatic)
853 (define-key query-replace-map "^" 'backup)
854 (define-key query-replace-map "\C-h" 'help)
855 (define-key query-replace-map [f1] 'help)
856 (define-key query-replace-map [help] 'help)
857 (define-key query-replace-map "?" 'help)
858 (define-key query-replace-map "\C-g" 'quit)
859 (define-key query-replace-map "\C-]" 'quit)
860 (define-key query-replace-map "\e" 'exit-prefix)
861 (define-key query-replace-map [escape] 'exit-prefix)
862
863 (defun replace-match-string-symbols (n)
864 "Process a list (and any sub-lists), expanding certain symbols.
865 Symbol Expands To
866 N (match-string N) (where N is a string of digits)
867 #N (string-to-number (match-string N))
868 & (match-string 0)
869 #& (string-to-number (match-string 0))
870
871 Note that these symbols must be preceeded by a backslash in order to
872 type them."
873 (while n
874 (cond
875 ((consp (car n))
876 (replace-match-string-symbols (car n))) ;Process sub-list
877 ((symbolp (car n))
878 (let ((name (symbol-name (car n))))
879 (cond
880 ((string-match "^[0-9]+$" name)
881 (setcar n (list 'match-string (string-to-number name))))
882 ((string-match "^#[0-9]+$" name)
883 (setcar n (list 'string-to-number
884 (list 'match-string
885 (string-to-number (substring name 1))))))
886 ((string= "&" name)
887 (setcar n '(match-string 0)))
888 ((string= "#&" name)
889 (setcar n '(string-to-number (match-string 0))))))))
890 (setq n (cdr n))))
891
892 (defun replace-eval-replacement (expression replace-count)
893 (let ((replacement (eval expression)))
894 (if (stringp replacement)
895 replacement
896 (prin1-to-string replacement t))))
897
898 (defun replace-loop-through-replacements (data replace-count)
899 ;; DATA is a vector contaning the following values:
900 ;; 0 next-rotate-count
901 ;; 1 repeat-count
902 ;; 2 next-replacement
903 ;; 3 replacements
904 (if (= (aref data 0) replace-count)
905 (progn
906 (aset data 0 (+ replace-count (aref data 1)))
907 (let ((next (cdr (aref data 2))))
908 (aset data 2 (if (consp next) next (aref data 3))))))
909 (car (aref data 2)))
910
911 (defun perform-replace (from-string replacements
912 query-flag regexp-flag delimited-flag
913 &optional repeat-count map start end)
914 "Subroutine of `query-replace'. Its complexity handles interactive queries.
915 Don't use this in your own program unless you want to query and set the mark
916 just as `query-replace' does. Instead, write a simple loop like this:
917
918 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
919 (replace-match \"foobar\" nil nil))
920
921 which will run faster and probably do exactly what you want. Please
922 see the documentation of `replace-match' to find out how to simulate
923 `case-replace'."
924 (or map (setq map query-replace-map))
925 (and query-flag minibuffer-auto-raise
926 (raise-frame (window-frame (minibuffer-window))))
927 (let ((nocasify (not (and case-fold-search case-replace
928 (string-equal from-string
929 (downcase from-string)))))
930 (case-fold-search (and case-fold-search
931 (string-equal from-string
932 (downcase from-string))))
933 (literal (not regexp-flag))
934 (search-function (if regexp-flag 're-search-forward 'search-forward))
935 (search-string from-string)
936 (real-match-data nil) ; the match data for the current match
937 (next-replacement nil)
938 (keep-going t)
939 (stack nil)
940 (replace-count 0)
941 (nonempty-match nil)
942
943 ;; If non-nil, it is marker saying where in the buffer to stop.
944 (limit nil)
945
946 ;; Data for the next match. If a cons, it has the same format as
947 ;; (match-data); otherwise it is t if a match is possible at point.
948 (match-again t)
949
950 (message
951 (if query-flag
952 (substitute-command-keys
953 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
954
955 ;; If region is active, in Transient Mark mode, operate on region.
956 (when start
957 (setq limit (copy-marker (max start end)))
958 (goto-char (min start end))
959 (deactivate-mark))
960
961 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
962 ;; containing a function and its first argument. The function is
963 ;; called to generate each replacement like this:
964 ;; (funcall (car replacements) (cdr replacements) replace-count)
965 ;; It must return a string.
966 (cond
967 ((stringp replacements)
968 (setq next-replacement replacements
969 replacements nil))
970 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
971 (or repeat-count (setq repeat-count 1))
972 (setq replacements (cons 'replace-loop-through-replacements
973 (vector repeat-count repeat-count
974 replacements replacements)))))
975
976 (if delimited-flag
977 (setq search-function 're-search-forward
978 search-string (concat "\\b"
979 (if regexp-flag from-string
980 (regexp-quote from-string))
981 "\\b")))
982 (push-mark)
983 (undo-boundary)
984 (unwind-protect
985 ;; Loop finding occurrences that perhaps should be replaced.
986 (while (and keep-going
987 (not (eobp))
988 ;; Use the next match if it is already known;
989 ;; otherwise, search for a match after moving forward
990 ;; one char if progress is required.
991 (setq real-match-data
992 (if (consp match-again)
993 (progn (goto-char (nth 1 match-again))
994 match-again)
995 (and (or match-again
996 ;; MATCH-AGAIN non-nil means we
997 ;; accept an adjacent match. If
998 ;; we don't, move one char to the
999 ;; right. This takes us a
1000 ;; character too far at the end,
1001 ;; but this is undone after the
1002 ;; while-loop.
1003 (progn (forward-char 1) (not (eobp))))
1004 (funcall search-function search-string limit t)
1005 ;; For speed, use only integers and
1006 ;; reuse the list used last time.
1007 (match-data t real-match-data)))))
1008 ;; Optionally ignore matches that have a read-only property.
1009 (unless (and query-replace-skip-read-only
1010 (text-property-not-all
1011 (match-beginning 0) (match-end 0)
1012 'read-only nil))
1013
1014 ;; Record whether the match is nonempty, to avoid an infinite loop
1015 ;; repeatedly matching the same empty string.
1016 (setq nonempty-match
1017 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1018
1019 ;; If the match is empty, record that the next one can't be
1020 ;; adjacent.
1021
1022 ;; Otherwise, if matching a regular expression, do the next
1023 ;; match now, since the replacement for this match may
1024 ;; affect whether the next match is adjacent to this one.
1025 ;; If that match is empty, don't use it.
1026 (setq match-again
1027 (and nonempty-match
1028 (or (not regexp-flag)
1029 (and (looking-at search-string)
1030 (let ((match (match-data)))
1031 (and (/= (nth 0 match) (nth 1 match))
1032 match))))))
1033
1034 ;; Calculate the replacement string, if necessary.
1035 (when replacements
1036 (set-match-data real-match-data)
1037 (setq next-replacement
1038 (funcall (car replacements) (cdr replacements)
1039 replace-count)))
1040 (if (not query-flag)
1041 (let ((inhibit-read-only query-replace-skip-read-only))
1042 (set-match-data real-match-data)
1043 (replace-match next-replacement nocasify literal)
1044 (setq replace-count (1+ replace-count)))
1045 (undo-boundary)
1046 (let (done replaced key def)
1047 ;; Loop reading commands until one of them sets done,
1048 ;; which means it has finished handling this occurrence.
1049 (while (not done)
1050 (set-match-data real-match-data)
1051 (replace-highlight (match-beginning 0) (match-end 0))
1052 ;; Bind message-log-max so we don't fill up the message log
1053 ;; with a bunch of identical messages.
1054 (let ((message-log-max nil))
1055 (message message from-string next-replacement))
1056 (setq key (read-event))
1057 ;; Necessary in case something happens during read-event
1058 ;; that clobbers the match data.
1059 (set-match-data real-match-data)
1060 (setq key (vector key))
1061 (setq def (lookup-key map key))
1062 ;; Restore the match data while we process the command.
1063 (cond ((eq def 'help)
1064 (with-output-to-temp-buffer "*Help*"
1065 (princ
1066 (concat "Query replacing "
1067 (if regexp-flag "regexp " "")
1068 from-string " with "
1069 next-replacement ".\n\n"
1070 (substitute-command-keys
1071 query-replace-help)))
1072 (with-current-buffer standard-output
1073 (help-mode))))
1074 ((eq def 'exit)
1075 (setq keep-going nil)
1076 (setq done t))
1077 ((eq def 'backup)
1078 (if stack
1079 (let ((elt (car stack)))
1080 (goto-char (car elt))
1081 (setq replaced (eq t (cdr elt)))
1082 (or replaced
1083 (set-match-data (cdr elt)))
1084 (setq stack (cdr stack)))
1085 (message "No previous match")
1086 (ding 'no-terminate)
1087 (sit-for 1)))
1088 ((eq def 'act)
1089 (or replaced
1090 (progn
1091 (replace-match next-replacement nocasify literal)
1092 (setq replace-count (1+ replace-count))))
1093 (setq done t replaced t))
1094 ((eq def 'act-and-exit)
1095 (or replaced
1096 (progn
1097 (replace-match next-replacement nocasify literal)
1098 (setq replace-count (1+ replace-count))))
1099 (setq keep-going nil)
1100 (setq done t replaced t))
1101 ((eq def 'act-and-show)
1102 (if (not replaced)
1103 (progn
1104 (replace-match next-replacement nocasify literal)
1105 (setq replace-count (1+ replace-count))
1106 (setq replaced t))))
1107 ((eq def 'automatic)
1108 (or replaced
1109 (progn
1110 (replace-match next-replacement nocasify literal)
1111 (setq replace-count (1+ replace-count))))
1112 (setq done t query-flag nil replaced t))
1113 ((eq def 'skip)
1114 (setq done t))
1115 ((eq def 'recenter)
1116 (recenter nil))
1117 ((eq def 'edit)
1118 (let ((opos (point-marker)))
1119 (goto-char (match-beginning 0))
1120 (save-excursion
1121 (funcall search-function search-string limit t)
1122 (setq real-match-data (match-data)))
1123 (save-excursion (recursive-edit))
1124 (goto-char opos))
1125 (set-match-data real-match-data)
1126 ;; Before we make the replacement,
1127 ;; decide whether the search string
1128 ;; can match again just after this match.
1129 (if (and regexp-flag nonempty-match)
1130 (setq match-again (and (looking-at search-string)
1131 (match-data)))))
1132
1133 ;; Edit replacement.
1134 ((eq def 'edit-replacement)
1135 (setq next-replacement
1136 (read-input "Edit replacement string: "
1137 next-replacement))
1138 (or replaced
1139 (replace-match next-replacement nocasify literal))
1140 (setq done t))
1141
1142 ((eq def 'delete-and-edit)
1143 (delete-region (match-beginning 0) (match-end 0))
1144 (set-match-data
1145 (prog1 (match-data)
1146 (save-excursion (recursive-edit))))
1147 (setq replaced t))
1148 ;; Note: we do not need to treat `exit-prefix'
1149 ;; specially here, since we reread
1150 ;; any unrecognized character.
1151 (t
1152 (setq this-command 'mode-exited)
1153 (setq keep-going nil)
1154 (setq unread-command-events
1155 (append (listify-key-sequence key)
1156 unread-command-events))
1157 (setq done t))))
1158 ;; Record previous position for ^ when we move on.
1159 ;; Change markers to numbers in the match data
1160 ;; since lots of markers slow down editing.
1161 (setq stack
1162 (cons (cons (point)
1163 (or replaced (match-data t)))
1164 stack))))))
1165
1166 ;; The code preventing adjacent regexp matches in the condition
1167 ;; of the while-loop above will haven taken us one character
1168 ;; beyond the last replacement. Undo that.
1169 (when (and regexp-flag (not match-again) (> replace-count 0))
1170 (backward-char 1))
1171
1172 (replace-dehighlight))
1173 (or unread-command-events
1174 (message "Replaced %d occurrence%s"
1175 replace-count
1176 (if (= replace-count 1) "" "s")))
1177 (and keep-going stack)))
1178
1179 (defcustom query-replace-highlight t
1180 "*Non-nil means to highlight words during query replacement."
1181 :type 'boolean
1182 :group 'matching)
1183
1184 (defvar replace-overlay nil)
1185
1186 (defun replace-dehighlight ()
1187 (and replace-overlay
1188 (progn
1189 (delete-overlay replace-overlay)
1190 (setq replace-overlay nil))))
1191
1192 (defun replace-highlight (start end)
1193 (and query-replace-highlight
1194 (progn
1195 (or replace-overlay
1196 (progn
1197 (setq replace-overlay (make-overlay start end))
1198 (overlay-put replace-overlay 'face
1199 (if (facep 'query-replace)
1200 'query-replace 'region))))
1201 (move-overlay replace-overlay start end (current-buffer)))))
1202
1203 ;;; replace.el ends here