home *** CD-ROM | disk | FTP | other *** search
/ Linux Cubed Series 2: Applications / Linux Cubed Series 2 - Applications.iso / editors / emacs / xemacs / xemacs-1.006 / xemacs-1 / lib / xemacs-19.13 / lisp / prim / replace.el < prev    next >
Encoding:
Text File  |  1995-08-09  |  26.5 KB  |  728 lines

  1. ;;; replace.el --- search and replace commands for XEmacs.
  2.  
  3. ;; Copyright (C) 1985, 1986, 1987, 1992, 1994 Free Software Foundation, Inc.
  4.  
  5. ;; This file is part of XEmacs.
  6.  
  7. ;; XEmacs is free software; you can redistribute it and/or modify it
  8. ;; under the terms of the GNU General Public License as published by
  9. ;; the Free Software Foundation; either version 2, or (at your option)
  10. ;; any later version.
  11.  
  12. ;; XEmacs is distributed in the hope that it will be useful, but
  13. ;; WITHOUT ANY WARRANTY; without even the implied warranty of
  14. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  15. ;; General Public License for more details.
  16.  
  17. ;; You should have received a copy of the GNU General Public License
  18. ;; along with XEmacs; see the file COPYING.  If not, write to the Free
  19. ;; Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  20.  
  21. ;;; Synched up with: FSF 19.28.
  22.  
  23. ;;; Commentary:
  24.  
  25. ;; This package supplies the string and regular-expression replace functions
  26. ;; documented in the XEmacs Reference Manul.
  27.  
  28. ;;; Code:
  29.  
  30. (defvar case-replace t "\
  31. *Non-nil means `query-replace' should preserve case in replacements.
  32. What this means is that `query-replace' will change the case of the
  33. replacement text so that it matches the text that was replaced.
  34. If this variable is nil, the replacement text will be inserted
  35. exactly as it was specified by the user, irrespective of the case
  36. of the text that was replaced.
  37.  
  38. Note that this flag has no effect if `case-fold-search' is nil,
  39. or if the replacement text has any uppercase letters in it.")
  40.  
  41. (defvar query-replace-history nil)
  42.  
  43. (defun query-replace-read-args (string)
  44.   (let (from to)
  45.     (setq from (read-from-minibuffer (format "%s: " (gettext string))
  46.                      nil nil nil
  47.                      'query-replace-history))
  48.     (setq to (read-from-minibuffer (format "%s %s with: " (gettext string)
  49.                        from)
  50.                    nil nil nil
  51.                    'query-replace-history))
  52.     (list from to current-prefix-arg)))
  53.  
  54. (defun query-replace (from-string to-string &optional arg)
  55.   "Replace some occurrences of FROM-STRING with TO-STRING.
  56. As each match is found, the user must type a character saying
  57. what to do with it.  For directions, type \\[help-command] at that time.
  58.  
  59. Preserves case in each replacement if `case-replace' and `case-fold-search'
  60. are non-nil and FROM-STRING has no uppercase letters.
  61. Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
  62. only matches surrounded by word boundaries.
  63.  
  64. To customize possible responses, change the \"bindings\" in `query-replace-map'."
  65.   (interactive (query-replace-read-args "Query replace"))
  66.   (perform-replace from-string to-string t nil arg)
  67.   (or unread-command-event (message "Done")))
  68.  
  69. (defun query-replace-regexp (regexp to-string &optional arg)
  70.   "Replace some things after point matching REGEXP with TO-STRING.
  71. As each match is found, the user must type a character saying
  72. what to do with it.  For directions, type \\[help-command] at that time.
  73.  
  74. Preserves case in each replacement if `case-replace' and `case-fold-search'
  75. are non-nil and REGEXP has no uppercase letters.
  76. Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
  77. only matches surrounded by word boundaries.
  78. In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
  79. and `\\=\\N' (where N is a digit) stands for
  80.  whatever what matched the Nth `\\(...\\)' in REGEXP."
  81.   (interactive (query-replace-read-args "Query replace regexp"))
  82.   (perform-replace regexp to-string t t arg)
  83.   (or unread-command-event (message "Done")))
  84.  
  85. ;;#### Not patently useful
  86. (defun map-query-replace-regexp (regexp to-strings &optional arg)
  87.   "Replace some matches for REGEXP with various strings, in rotation.
  88. The second argument TO-STRINGS contains the replacement strings, separated
  89. by spaces.  This command works like `query-replace-regexp' except
  90. that each successive replacement uses the next successive replacement string,
  91. wrapping around from the last such string to the first.
  92.  
  93. Non-interactively, TO-STRINGS may be a list of replacement strings.
  94.  
  95. A prefix argument N says to use each replacement string N times
  96. before rotating to the next."
  97.   (interactive
  98.    (let (from to)
  99.      (setq from (read-from-minibuffer "Map query replace (regexp): "
  100.                       nil nil nil
  101.                       'query-replace-history))
  102.      (setq to (read-from-minibuffer
  103.            (format "Query replace %s with (space-separated strings): "
  104.                from)
  105.            nil nil nil
  106.            'query-replace-history))
  107.      (list from to current-prefix-arg)))
  108.   (let (replacements)
  109.     (if (listp to-strings)
  110.     (setq replacements to-strings)
  111.       (while (/= (length to-strings) 0)
  112.     (if (string-match " " to-strings)
  113.         (setq replacements
  114.           (append replacements
  115.               (list (substring to-strings 0
  116.                        (string-match " " to-strings))))
  117.           to-strings (substring to-strings
  118.                        (1+ (string-match " " to-strings))))
  119.       (setq replacements (append replacements (list to-strings))
  120.         to-strings ""))))
  121.    (perform-replace regexp replacements t t nil arg))
  122.   (or unread-command-event (message "Done")))
  123.  
  124. (defun replace-string (from-string to-string &optional delimited)
  125.   "Replace occurrences of FROM-STRING with TO-STRING.
  126. Preserve case in each match if `case-replace' and `case-fold-search'
  127. are non-nil and FROM-STRING has no uppercase letters.
  128. Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
  129. only matches surrounded by word boundaries.
  130.  
  131. This function is usually the wrong thing to use in a Lisp program.
  132. What you probably want is a loop like this:
  133.   (while (search-forward FROM-STRING nil t)
  134.     (replace-match TO-STRING nil t))
  135. which will run faster and will not set the mark or print anything."
  136.   (interactive (query-replace-read-args "Replace string"))
  137.   (perform-replace from-string to-string nil nil delimited)
  138.   (or unread-command-event (message "Done")))
  139.  
  140. (defun replace-regexp (regexp to-string &optional delimited)
  141.   "Replace things after point matching REGEXP with TO-STRING.
  142. Preserve case in each match if `case-replace' and `case-fold-search'
  143. are non-nil and REGEXP has no uppercase letters.
  144. Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
  145. only matches surrounded by word boundaries.
  146. In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
  147. and `\\=\\N' (where N is a digit) stands for
  148.  whatever what matched the Nth `\\(...\\)' in REGEXP.
  149.  
  150. This function is usually the wrong thing to use in a Lisp program.
  151. What you probably want is a loop like this:
  152.   (while (re-search-forward REGEXP nil t)
  153.     (replace-match TO-STRING nil nil))
  154. which will run faster and will not set the mark or print anything."
  155.   (interactive (query-replace-read-args "Replace regexp"))
  156.   (perform-replace regexp to-string nil t delimited)
  157.   (or unread-command-event (message "Done")))
  158.  
  159.  
  160. (defvar regexp-history nil
  161.   "History list for some commands that read regular expressions.")
  162.  
  163. (define-function 'keep-lines 'delete-non-matching-lines)
  164. (defun delete-non-matching-lines (regexp)
  165.   "Delete all lines except those containing matches for REGEXP.
  166. A match split across lines preserves all the lines it lies in.
  167. Applies to all lines after point."
  168.   (interactive (list (read-from-minibuffer
  169.               "Keep lines (containing match for regexp): "
  170.               nil nil nil 'regexp-history)))
  171.   (save-excursion
  172.     (or (bolp) (forward-line 1))
  173.     (let ((start (point)))
  174.       (while (not (eobp))
  175.     ;; Start is first char not preserved by previous match.
  176.     (if (not (re-search-forward regexp nil 'move))
  177.         (delete-region start (point-max))
  178.       (let ((end (save-excursion (goto-char (match-beginning 0))
  179.                      (beginning-of-line)
  180.                      (point))))
  181.         ;; Now end is first char preserved by the new match.
  182.         (if (< start end)
  183.         (delete-region start end))))
  184.     (setq start (save-excursion (forward-line 1)
  185.                     (point)))
  186.     ;; If the match was empty, avoid matching again at same place.
  187.     (and (not (eobp)) (= (match-beginning 0) (match-end 0))
  188.          (forward-char 1))))))
  189.  
  190. (define-function 'flush-lines 'delete-matching-lines)
  191. (defun delete-matching-lines (regexp)
  192.   "Delete lines containing matches for REGEXP.
  193. If a match is split across lines, all the lines it lies in are deleted.
  194. Applies to lines after point."
  195.   (interactive (list (read-from-minibuffer
  196.               "Flush lines (containing match for regexp): "
  197.               nil nil nil 'regexp-history)))
  198.   (save-excursion
  199.     (while (and (not (eobp))
  200.         (re-search-forward regexp nil t))
  201.       (delete-region (save-excursion (goto-char (match-beginning 0))
  202.                      (beginning-of-line)
  203.                      (point))
  204.              (progn (forward-line 1) (point))))))
  205.  
  206. (define-function 'how-many 'count-matches)
  207. (defun count-matches (regexp)
  208.   "Print number of matches for REGEXP following point."
  209.   (interactive (list (read-from-minibuffer
  210.               "How many matches for (regexp): "
  211.               nil nil nil 'regexp-history)))
  212.   (let ((count 0) opoint)
  213.     (save-excursion
  214.      (while (and (not (eobp))
  215.          (progn (setq opoint (point))
  216.             (re-search-forward regexp nil t)))
  217.        (if (= opoint (point))
  218.        (forward-char 1)
  219.      (setq count (1+ count))))
  220.      (message "%d occurrences" count))))
  221.  
  222.  
  223. (defvar occur-mode-map ())
  224. (if occur-mode-map
  225.     ()
  226.   (setq occur-mode-map (make-sparse-keymap))
  227.   (set-keymap-name occur-mode-map 'occur-mode-map)
  228.   (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence)
  229.   (define-key occur-mode-map 'button2 'occur-mode-mouse-goto))
  230.  
  231. (defvar occur-buffer nil)
  232. (defvar occur-nlines nil)
  233. (defvar occur-pos-list nil)
  234.  
  235. (defun occur-mode ()
  236.   "Major mode for output from \\[occur].
  237. Move point to one of the occurrences in this buffer,
  238. then use \\[occur-mode-goto-occurrence] to go to the same occurrence
  239. Or click \\<occur-mode-map>\\[occur-mode-mouse-goto] on an occurrence line.
  240. in the buffer that the occurrences were found in.
  241. \\{occur-mode-map}"
  242.   (kill-all-local-variables)
  243.   (use-local-map occur-mode-map)
  244.   (setq major-mode 'occur-mode)
  245.   (setq mode-name (gettext "Occur"))
  246.   (make-local-variable 'occur-buffer)
  247.   (make-local-variable 'occur-nlines)
  248.   (make-local-variable 'occur-pos-list)
  249.   (require 'mode-motion)
  250.   (setq mode-motion-hook 'mode-motion-highlight-line)
  251.   (run-hooks 'occur-mode-hook))
  252.  
  253. (defun occur-mode-mouse-goto (e)
  254.   "go to occurence highlighted by mouse.  This function is only reasonable when bound
  255. to a mouse key in the occur buffer"
  256.   (interactive "e")
  257.   (let ((window-save (selected-window))
  258.     (frame-save (selected-frame)))
  259.     ;; preserve the window/frame setup
  260.     (unwind-protect
  261.     (progn
  262.       (mouse-set-point e)
  263.       (occur-mode-goto-occurrence))
  264.       (select-frame frame-save)
  265.       (select-window window-save))))
  266.  
  267. (defun occur-mode-goto-occurrence ()
  268.   "Go to the occurrence the current line describes."
  269.   (interactive)
  270.   (if (or (null occur-buffer)
  271.       (null (buffer-name occur-buffer)))
  272.       (progn
  273.     (setq occur-buffer nil
  274.           occur-pos-list nil)
  275.     (error "Buffer in which occurrences were found is deleted")))
  276.   (let* ((line-count
  277.       (count-lines (point-min)
  278.                (save-excursion
  279.              (beginning-of-line)
  280.              (point))))
  281.      (occur-number (save-excursion
  282.              (beginning-of-line)
  283.              (/ (1- line-count)
  284.                 (cond ((< occur-nlines 0)
  285.                    (- 2 occur-nlines))
  286.                   ((> occur-nlines 0)
  287.                    (+ 2 (* 2 occur-nlines)))
  288.                   (t 1)))))
  289.      (pos (nth occur-number occur-pos-list))
  290.      (window (get-buffer-window occur-buffer t))
  291.      (occur-source-buffer occur-buffer))
  292.     (if (< line-count 1)
  293.     (error "No occurrence on this line"))
  294.     (or pos
  295.     (error "No occurrence on this line"))
  296.     ;; don't raise window unless it isn't visible
  297.     ;; allow for the possibility that the occur buffer is on another frame
  298.     (or (and window
  299.          (window-live-p window)
  300.          (frame-visible-p (window-frame window))
  301.          (set-buffer occur-source-buffer))
  302.     (and (pop-to-buffer occur-source-buffer)
  303.          (setq window (get-buffer-window occur-source-buffer t))))
  304.     (goto-char pos)
  305.     (set-window-point window pos)))
  306.  
  307.  
  308. (defvar list-matching-lines-default-context-lines 0
  309.   "*Default number of context lines to include around a `list-matching-lines'
  310. match.  A negative number means to include that many lines before the match.
  311. A positive number means to include that many lines both before and after.")
  312.  
  313. ;; XEmacs addition
  314. ;;; Damn you Jamie, this is utter trash.
  315. (defvar list-matching-lines-whole-buffer t
  316.   "If t, occur operates on whole buffer, otherwise occur starts from point.
  317. default is nil.")
  318.  
  319. (define-function 'occur 'list-matching-lines)
  320. (defun list-matching-lines (regexp &optional nlines)
  321.   "Show all lines in the current buffer containing a match for REGEXP.
  322.  
  323. If a match spreads across multiple lines, all those lines are shown.
  324.  
  325. If variable `list-matching-lines-whole-buffer' is non-nil, the entire buffer is
  326. searched, otherwise search begins at point.
  327.  
  328. Each line is displayed with NLINES lines before and after,
  329. or -NLINES before if NLINES is negative.
  330. NLINES defaults to `list-matching-lines-default-context-lines'.
  331. Interactively it is the prefix arg.
  332.  
  333. The lines are shown in a buffer named `*Occur*'.
  334. It serves as a menu to find any of the occurrences in this buffer.
  335. \\[describe-mode] in that buffer will explain how."
  336.   (interactive
  337.    (list (let* ((default (or (symbol-near-point)
  338.                  (and regexp-history
  339.                   (car regexp-history))))
  340.         (minibuffer-history-minimum-string-length 0)
  341.         (input
  342.          (if default
  343.              ;; rewritten for I18N3 snarfing
  344.              (read-from-minibuffer
  345.               (format "List lines matching regexp (default `%s'): "
  346.                   default) nil nil nil 'regexp-history)
  347.            (read-from-minibuffer
  348.             "List lines matching regexp: "
  349.             nil nil nil
  350.             'regexp-history))))
  351.        (if (and (equal input "") default)
  352.            (progn
  353.          (setq input default)
  354.          (setcar regexp-history default)))
  355.        ;; clear extra entries
  356.        (setcdr regexp-history (delete (car regexp-history)
  357.                       (cdr regexp-history)))
  358.        input)
  359.      current-prefix-arg))
  360.   (if (equal regexp "")
  361.       (error "Must pass non-empty regexp to `list-matching-lines'"))
  362.   (setq nlines (if nlines (prefix-numeric-value nlines)
  363.          list-matching-lines-default-context-lines))
  364.   (let ((first t)
  365.     (buffer (current-buffer))
  366.     (linenum 1)
  367.     (prevpos (point-min))
  368.         (final-context-start (make-marker)))
  369.     (if (not list-matching-lines-whole-buffer)
  370.     (save-excursion
  371.       (beginning-of-line)
  372.       (setq linenum (1+ (count-lines (point-min) (point))))
  373.       (setq prevpos (point))))
  374.     (with-output-to-temp-buffer "*Occur*"
  375.       (save-excursion
  376.     (set-buffer standard-output)
  377.     (insert (format "Lines matching %s in buffer %s.\n"
  378.             regexp (buffer-name buffer)))
  379.     (occur-mode)
  380.     (setq occur-buffer buffer)
  381.     (setq occur-nlines nlines)
  382.     (setq occur-pos-list ()))
  383.       (if (eq buffer standard-output)
  384.       (goto-char (point-max)))
  385.       (save-excursion
  386.     (if list-matching-lines-whole-buffer
  387.         (beginning-of-buffer))
  388.     (message (format "Searching for %s ..." regexp))
  389.     ;; Find next match, but give up if prev match was at end of buffer.
  390.     (while (and (not (= prevpos (point-max)))
  391.             (re-search-forward regexp nil t))
  392.       (goto-char (match-beginning 0))
  393.       (beginning-of-line)
  394.       (save-match-data
  395.             (setq linenum (+ linenum (count-lines prevpos (point)))))
  396.       (setq prevpos (point))
  397.       (goto-char (match-end 0))
  398.       (let* ((start (save-excursion
  399.               (goto-char (match-beginning 0))
  400.               (forward-line (if (< nlines 0) nlines (- nlines)))
  401.               (point)))
  402.          (end (save-excursion
  403.             (goto-char (match-end 0))
  404.             (if (> nlines 0)
  405.                 (forward-line (1+ nlines))
  406.                 (forward-line 1))
  407.             (point)))
  408.          (tag (format "%3d" linenum))
  409.          (empty (make-string (length tag) ?\ ))
  410.          tem)
  411.         (save-excursion
  412.           (setq tem (make-marker))
  413.           (set-marker tem (point))
  414.           (set-buffer standard-output)
  415.           (setq occur-pos-list (cons tem occur-pos-list))
  416.           (or first (zerop nlines)
  417.           (insert "--------\n"))
  418.           (setq first nil)
  419.           (insert-buffer-substring buffer start end)
  420.           (backward-char (- end start))
  421.           (setq tem (if (< nlines 0) (- nlines) nlines))
  422.           (while (> tem 0)
  423.         (insert empty ?:)
  424.         (forward-line 1)
  425.         (setq tem (1- tem)))
  426.           (let ((this-linenum linenum))
  427.         (set-marker final-context-start
  428.                 (+ (point) (- (match-end 0) (match-beginning 0))))
  429.         (while (< (point) final-context-start)
  430.           (if (null tag)
  431.               (setq tag (format "%3d" this-linenum)))
  432.           (insert tag ?:)
  433. ;; ####FSFmacs
  434. ;          (put-text-property (save-excursion
  435. ;                       (beginning-of-line)
  436. ;                       (point))
  437. ;                     (save-excursion
  438. ;                       (end-of-line)
  439. ;                       (point))
  440. ;                     'mouse-face 'highlight)
  441.           (setq tag nil)
  442.           (forward-line 1)
  443.           (setq this-linenum (1+ this-linenum))))
  444.           (while (< tem nlines)
  445.         (insert empty ?:)
  446.         (forward-line 1)
  447.         (setq tem (1+ tem))))
  448.         (forward-line 1)))
  449.     (set-buffer standard-output)
  450.     ;; Put positions in increasing order to go with buffer.
  451.     (setq occur-pos-list (nreverse occur-pos-list))
  452.     (if (interactive-p)
  453.         (message "%d matching lines." (length occur-pos-list)))))))
  454.  
  455. ;; It would be nice to use \\[...], but there is no reasonable way
  456. ;; to make that display both SPC and Y.
  457. (defvar query-replace-help (purecopy
  458.   "Type Space or `y' to replace one match, Delete or `n' to skip to next,
  459. RET or `q' to exit, Period to replace one match and exit,
  460. Comma to replace but not move point immediately,
  461. C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
  462. C-w to delete match and recursive edit,
  463. C-l to clear the frame, redisplay, and offer same replacement again,
  464. ! to replace all remaining matches with no more questions,
  465. ^ to move point back to previous match.")
  466.   "Help message while in query-replace")
  467.  
  468. (defvar    query-replace-map nil
  469.   "Keymap that defines the responses to questions in `query-replace'.
  470. The \"bindings\" in this map are not commands; they are answers.
  471. The valid answers include `act', `skip', `act-and-show',
  472. `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
  473. `automatic', `backup', and `help'.")
  474.  
  475. (if query-replace-map
  476.     nil
  477.     (let ((map (make-sparse-keymap)))
  478.       (set-keymap-name map 'query-replace-map)
  479.       (define-key map " " 'act)
  480.       (define-key map "\d" 'skip)
  481.       (define-key map [delete] 'skip)
  482.       (define-key map [backspace] 'skip)
  483.       (define-key map "y" 'act)
  484.       (define-key map "n" 'skip)
  485.       (define-key map "," 'act-and-show)
  486.       (define-key map [escape] 'exit)
  487.       (define-key map "q" 'exit)
  488.       (define-key map [return] 'exit)
  489.       (define-key map "." 'act-and-exit)
  490.       (define-key map "\C-r" 'edit)
  491.       (define-key map "\C-w" 'delete-and-edit)
  492.       (define-key map "\C-l" 'recenter)
  493.       (define-key map "!" 'automatic)
  494.       (define-key map "^" 'backup)
  495.       (define-key map [(control h)] 'help)      ;; XEmacs change
  496.       (define-key map "?" 'help)
  497.       (define-key map "\C-g" 'quit)
  498.       (define-key map "\C-]" 'quit)
  499.       
  500.       (setq query-replace-map map)))
  501.  
  502.  
  503. (autoload 'isearch-highlight "isearch")
  504.  
  505. (defun perform-replace-next-event (event)
  506.   (if isearch-highlight
  507.       (let ((aborted t))
  508.     (unwind-protect
  509.         (progn
  510.           (isearch-highlight (match-beginning 0) (match-end 0))
  511.           (next-command-event event)
  512.           (setq aborted nil))
  513.       (isearch-dehighlight aborted)))
  514.     (next-command-event event)))
  515.  
  516. (defun perform-replace (from-string replacements
  517.                 query-flag regexp-flag delimited-flag
  518.             &optional repeat-count map)
  519.   "Subroutine of `query-replace'.  Its complexity handles interactive queries.
  520. Don't use this in your own program unless you want to query and set the mark
  521. just as `query-replace' does.  Instead, write a simple loop like this:
  522.   (while (re-search-forward \"foo[ \t]+bar\" nil t)
  523.     (replace-match \"foobar\" nil nil))
  524. which will run faster and probably do exactly what you want."
  525.   (or map (setq map query-replace-map))
  526.   (let ((event (allocate-event))
  527.     (nocasify (not (and case-fold-search case-replace
  528.                 (string-equal from-string
  529.                       (downcase from-string)))))
  530.     (literal (not regexp-flag))
  531.     (search-function (if regexp-flag 're-search-forward 'search-forward))
  532.     (search-string from-string)
  533.     (real-match-data nil)        ; the match data for the current match
  534.     (next-replacement nil)
  535.     (replacement-index 0)
  536.     (keep-going t)
  537.     (stack nil)
  538.     (next-rotate-count 0)
  539.     (replace-count 0)
  540.     (lastrepl nil)            ;Position after last match considered.
  541.     (match-again t)
  542.     (message
  543.      (if query-flag
  544.          (substitute-command-keys
  545.           "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
  546.     (if (stringp replacements)
  547.     (setq next-replacement replacements)
  548.       (or repeat-count (setq repeat-count 1)))
  549.     (if delimited-flag
  550.     (setq search-function 're-search-forward
  551.           search-string (concat "\\b"
  552.                     (if regexp-flag from-string
  553.                       (regexp-quote from-string))
  554.                     "\\b")))
  555.     (push-mark)
  556.     (undo-boundary)
  557.     ;; Loop finding occurrences that perhaps should be replaced.
  558.     (while (and keep-going
  559.         (not (eobp))
  560.         (funcall search-function search-string nil t)
  561.         ;; If the search string matches immediately after
  562.         ;; the previous match, but it did not match there
  563.         ;; before the replacement was done, ignore the match.
  564.         (if (or (eq lastrepl (point))
  565.             (and regexp-flag
  566.                  (eq lastrepl (match-beginning 0))
  567.                  (not match-again)))
  568.  
  569.             (if (eobp)
  570.             nil
  571.               ;; Don't replace the null string 
  572.               ;; right after end of previous replacement.
  573.               (forward-char 1)
  574.               (funcall search-function search-string nil t))
  575.           t))
  576.       ;; Save the data associated with the real match.
  577.       (setq real-match-data (match-data))
  578.  
  579.       ;; Before we make the replacement, decide whether the search string
  580.       ;; can match again just after this match.
  581.       (if regexp-flag
  582.       (progn 
  583.             (setq match-again (looking-at search-string))
  584.             (store-match-data real-match-data)))
  585.  
  586.       ;; If time for a change, advance to next replacement string.
  587.       (if (and (listp replacements)
  588.            (= next-rotate-count replace-count))
  589.       (progn
  590.         (setq next-rotate-count
  591.           (+ next-rotate-count repeat-count))
  592.         (setq next-replacement (nth replacement-index replacements))
  593.         (setq replacement-index (% (1+ replacement-index) (length replacements)))))
  594.       (if (not query-flag)
  595.       (progn
  596.         (store-match-data real-match-data)
  597.         (replace-match next-replacement nocasify literal)
  598.         (setq replace-count (1+ replace-count)))
  599.     (undo-boundary)
  600.     (let ((help-form
  601.            '(concat (format "Query replacing %s%s with %s.\n\n"
  602.                 (if regexp-flag (gettext "regexp ") "")
  603.                 from-string next-replacement)
  604.                            (substitute-command-keys query-replace-help)))
  605.               (done nil)
  606.               (replaced nil)
  607.               def)
  608.           ;; Loop reading commands until one of them sets done,
  609.       ;; which means it has finished handling this occurrence.
  610.       (while (not done)
  611.         (message message from-string next-replacement)
  612.             (perform-replace-next-event event)
  613.             (setq def (lookup-key map (vector event)))
  614.         ;; Restore the match data while we process the command.
  615.         (store-match-data real-match-data)
  616.         (cond ((eq def 'help)
  617.            (with-output-to-temp-buffer (gettext "*Help*")
  618.              (princ (concat
  619.                  (format "Query replacing %s%s with %s.\n\n"
  620.                      (if regexp-flag "regexp " "")
  621.                      from-string next-replacement)
  622.                   (substitute-command-keys
  623.                    query-replace-help)))))
  624.           ((eq def 'exit)
  625.            (setq keep-going nil)
  626.            (setq done t))
  627.           ((eq def 'backup)
  628.                    (if stack
  629.                        (let ((elt (car stack)))
  630.                          (goto-char (car elt))
  631.                          (setq replaced (eq t (cdr elt)))
  632.                          (or replaced
  633.                              (store-match-data (cdr elt)))
  634.                          (setq stack (cdr stack)))
  635.                        (progn
  636.              (message "No previous match")
  637.              (ding 'no-terminate)
  638.              (sit-for 1))))
  639.           ((eq def 'act)
  640.            (or replaced
  641.                (replace-match next-replacement nocasify literal))
  642.            (setq done t replaced t))
  643.           ((eq def 'act-and-exit)
  644.            (or replaced
  645.                (replace-match next-replacement nocasify literal))
  646.            (setq keep-going nil)
  647.            (setq done t replaced t))
  648.           ((eq def 'act-and-show)
  649.            (if (not replaced)
  650.                (progn
  651.              (replace-match next-replacement nocasify literal)
  652.              (setq replaced t))))
  653.           ((eq def 'automatic)
  654.            (or replaced
  655.                (replace-match next-replacement nocasify literal))
  656.            (setq done t query-flag nil replaced t))
  657.           ((eq def 'skip)
  658.            (setq done t))
  659.           ((eq def 'recenter)
  660.            (recenter nil))
  661.           ((eq def 'edit)
  662.            (store-match-data
  663.             (prog1 (match-data)
  664.               (save-excursion (recursive-edit))))
  665.            ;; Before we make the replacement,
  666.            ;; decide whether the search string
  667.            ;; can match again just after this match.
  668.            (if regexp-flag
  669.                (setq match-again (looking-at search-string))))
  670.           ((eq def 'delete-and-edit)
  671.            (delete-region (match-beginning 0) (match-end 0))
  672.            (store-match-data (prog1 (match-data)
  673.               (save-excursion (recursive-edit))))
  674.            (setq replaced t))
  675.           (t
  676.            (setq keep-going nil)
  677.            (setq unread-command-event event)
  678.            (setq done t))))
  679.       ;; Record previous position for ^ when we move on.
  680.       ;; Change markers to numbers in the match data
  681.       ;; since lots of markers slow down editing.
  682.       (setq stack
  683.         (cons (cons (point)
  684.                 (or replaced
  685.                 (mapcar
  686.                  #'(lambda (elt)
  687.                      (if (markerp elt)
  688.                      (prog1 (marker-position elt)
  689.                        (set-marker elt nil))
  690.                        elt))
  691.                  (match-data))))
  692.               stack))
  693.       (if replaced (setq replace-count (1+ replace-count)))))
  694.       (setq lastrepl (point)))
  695.     (and keep-going stack)))
  696.  
  697. ;;; (defun match-string (num &optional string)
  698. ;;;   "Return string of text matched by last search.
  699. ;;; NUM specifies which parenthesized expression in the last regexp.
  700. ;;;  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
  701. ;;; Zero means the entire text matched by the whole regexp or whole string.
  702. ;;; STRING should be given if the last search was by `string-match' on STRING."
  703. ;;;   (if (match-beginning num)
  704. ;;;       (if string
  705. ;;;           (substring string (match-beginning num) (match-end num))
  706. ;;;         (buffer-substring (match-beginning num) (match-end num)))))
  707.  
  708. ;; #### - this could stand to be in C...
  709. (defmacro match-string (n &optional string)
  710.   "Returns the Nth subexpression matched by the last regular expression
  711. search.  The second argument, STRING, must be specified if the last
  712. regular expression search was done with `string-match'."
  713.   ;; #### - note that match-beginning is byte coded, so it's more efficient
  714.   ;; to just call it twice than it is to let-bind its return value... --Stig
  715.   `(and (match-beginning ,n)
  716.     ,(if string
  717.          `(substring ,string (match-beginning ,n) (match-end ,n))
  718.        `(buffer-substring (match-beginning ,n) (match-end ,n)))))
  719.  
  720. (defmacro save-match-data (&rest forms)
  721.   "Execute FORMS, restoring the global value of the match data."
  722.   (list 'let '((_match_data_ (match-data)))
  723.     (list 'unwind-protect
  724.           (cons 'progn forms)
  725.           '(store-match-data _match_data_))))
  726.  
  727. ;;; replace.el ends here
  728.