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