changeset 52170:27340819ef07

Updated to version 4.21
author Carsten Dominik <dominik@science.uva.nl>
date Mon, 11 Aug 2003 12:27:02 +0000
parents b97eb548bcaa
children 03075c276aac
files lisp/textmodes/reftex-auc.el lisp/textmodes/reftex-cite.el lisp/textmodes/reftex-dcr.el lisp/textmodes/reftex-global.el lisp/textmodes/reftex-index.el lisp/textmodes/reftex-parse.el lisp/textmodes/reftex-ref.el lisp/textmodes/reftex-sel.el lisp/textmodes/reftex-toc.el lisp/textmodes/reftex-vars.el lisp/textmodes/reftex.el
diffstat 11 files changed, 4180 insertions(+), 3725 deletions(-) [+]
line wrap: on
line diff
--- a/lisp/textmodes/reftex-auc.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-auc.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-auc.el --- RefTeX's interface to AUC TeX
-;; Copyright (c) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 
 ;; This file is part of GNU Emacs.
 
@@ -34,7 +34,7 @@
   ;; Tell if a certain flag is set in reftex-plug-into-AUCTeX
   (or (eq t reftex-plug-into-AUCTeX)
       (and (listp reftex-plug-into-AUCTeX)
-	   (nth which reftex-plug-into-AUCTeX))))
+           (nth which reftex-plug-into-AUCTeX))))
 
 (defun reftex-arg-label (optional &optional prompt definition)
   "Use `reftex-label', `reftex-reference' or AUCTeX's code to insert label arg.
@@ -44,17 +44,17 @@
      ((and definition (reftex-plug-flag 1))
       ;; Create a new label, with a temporary brace for `reftex-what-macro'
       (unwind-protect
-	  (progn (insert "{") (setq label (or (reftex-label nil t) "")))
-	(delete-backward-char 1)))
+          (progn (insert "{") (setq label (or (reftex-label nil t) "")))
+        (delete-backward-char 1)))
      ((and (not definition) (reftex-plug-flag 2))
       ;; Reference a label with RefTeX
       (setq label (reftex-reference nil t)))
      (t
       ;; AUCTeX's default mechanism
       (setq label (completing-read (TeX-argument-prompt optional prompt "Key")
-				   (LaTeX-label-list)))))
+                                   (LaTeX-label-list)))))
     (if (and definition (not (string-equal "" label)))
-	(LaTeX-add-labels label))
+        (LaTeX-add-labels label))
     (TeX-argument-insert label optional)))
 
 (defun reftex-arg-cite (optional &optional prompt definition)
@@ -66,28 +66,28 @@
       (setq items (list (or (reftex-citation t) ""))))
      (t
       (setq prompt (concat (if optional "(Optional) " "")
-			   (if prompt prompt "Add key")
-			   ": (default none) "))
+                           (if prompt prompt "Add key")
+                           ": (default none) "))
       (setq items (multi-prompt "," t prompt (LaTeX-bibitem-list)))))
     (apply 'LaTeX-add-bibitems items)
     (TeX-argument-insert (mapconcat 'identity items ",") optional)))
 
 
 (defun reftex-arg-index-tag (optional &optional prompt &rest args)
-  "Prompt for an index tag with completion.
+  "Prompt for an index tag with completion. 
 This is the name of an index, not the entry."
   (let (tag taglist)
     (setq prompt (concat (if optional "(Optional) " "")
-			 (if prompt prompt "Index tag")
-			 ": (default none) "))
+                         (if prompt prompt "Index tag")
+                         ": (default none) "))
     (if (and reftex-support-index (reftex-plug-flag 4))
-	;; Use RefTeX completion
-	(progn
-	  (reftex-access-scan-info nil)
-	  (setq taglist
-		(cdr (assoc 'index-tags
-			    (symbol-value reftex-docstruct-symbol)))
-		tag (completing-read prompt (mapcar 'list taglist))))
+        ;; Use RefTeX completion
+        (progn
+          (reftex-access-scan-info nil)
+          (setq taglist 
+                (cdr (assoc 'index-tags 
+                            (symbol-value reftex-docstruct-symbol)))
+                tag (completing-read prompt (mapcar 'list taglist))))
       ;; Just ask like AUCTeX does.
       (setq tag (read-string prompt)))
     (TeX-argument-insert tag optional)))
@@ -98,12 +98,12 @@
 argument identify one of multiple indices."
   (let* (tag key)
     (if (and reftex-support-index (reftex-plug-flag 4))
-	(progn
-	  (reftex-access-scan-info nil)
-	  (setq tag (reftex-what-index-tag)
-		key (reftex-index-complete-key (or tag "idx"))))
+        (progn
+          (reftex-access-scan-info nil)
+          (setq tag (reftex-what-index-tag)
+                key (reftex-index-complete-key (or tag "idx"))))
       (setq key (completing-read (TeX-argument-prompt optional prompt "Key")
-				 (LaTeX-index-entry-list))))
+                                 (LaTeX-index-entry-list))))
     (unless (string-equal "" key)
       (LaTeX-add-index-entries key))
     (TeX-argument-insert key optional)))
@@ -111,18 +111,18 @@
 (defun reftex-what-index-tag ()
   ;; Look backward to find out what index the macro at point belongs to
   (let ((macro (save-excursion
-		 (and (re-search-backward "\\\\[a-zA-Z*]+" nil t)
-		      (match-string 0))))
-	tag entry)
+                 (and (re-search-backward "\\\\[a-zA-Z*]+" nil t)
+                      (match-string 0))))
+        tag entry)
     (when (and macro
-	       (setq entry (assoc macro reftex-index-macro-alist)))
+               (setq entry (assoc macro reftex-index-macro-alist)))
       (setq tag (nth 1 entry))
       (cond
        ((stringp tag) tag)
        ((integerp tag)
-	(save-excursion
-	  (goto-char (match-end 1))
-	  (or (reftex-nth-arg tag (nth 6 entry)) "idx")))
+        (save-excursion
+          (goto-char (match-end 1))
+          (or (reftex-nth-arg tag (nth 6 entry)) "idx")))
        (t "idx")))))
 
 (defvar LaTeX-label-function)
@@ -130,7 +130,7 @@
   ;; Replace AUCTeX functions with RefTeX functions.
   ;; Which functions are replaced is controlled by the variable
   ;; `reftex-plug-into-AUCTeX'.
-
+  
   (if (reftex-plug-flag 0)
       (setq LaTeX-label-function 'reftex-label)
     (setq LaTeX-label-function nil))
@@ -142,11 +142,11 @@
   (and (reftex-plug-flag 3)
        (fboundp 'TeX-arg-cite)
        (fset 'TeX-arg-cite 'reftex-arg-cite))
-
-  (and (reftex-plug-flag 4)
+  
+  (and (reftex-plug-flag 4) 
        (fboundp 'TeX-arg-index-tag)
        (fset 'TeX-arg-index-tag 'reftex-arg-index-tag))
-  (and (reftex-plug-flag 4)
+  (and (reftex-plug-flag 4) 
        (fboundp 'TeX-arg-index)
        (fset 'TeX-arg-index 'reftex-arg-index)))
 
@@ -174,17 +174,17 @@
   (unless reftex-docstruct-symbol
     (reftex-tie-multifile-symbols))
   (when (and reftex-docstruct-symbol
-	     (symbolp reftex-docstruct-symbol))
+             (symbolp reftex-docstruct-symbol))
     (let ((list (get reftex-docstruct-symbol 'reftex-label-alist-style))
-	  entry changed)
+          entry changed)
       (while entry-list
-	(setq entry (pop entry-list))
-	(unless (member entry list)
-	  (setq reftex-tables-dirty t
-		changed t)
-	  (push entry list)))
+        (setq entry (pop entry-list))
+        (unless (member entry list)
+          (setq reftex-tables-dirty t
+                changed t)
+          (push entry list)))
       (when changed
-	(put reftex-docstruct-symbol 'reftex-label-alist-style list)))))
+        (put reftex-docstruct-symbol 'reftex-label-alist-style list)))))
 (defalias 'reftex-add-to-label-alist 'reftex-add-label-environments)
 
 (defun reftex-add-section-levels (entry-list)
@@ -195,17 +195,17 @@
   (unless reftex-docstruct-symbol
     (reftex-tie-multifile-symbols))
   (when (and reftex-docstruct-symbol
-	     (symbolp reftex-docstruct-symbol))
+             (symbolp reftex-docstruct-symbol))
     (let ((list (get reftex-docstruct-symbol 'reftex-section-levels))
-	  entry changed)
+          entry changed)
       (while entry-list
-	(setq entry (pop entry-list))
-	(unless (member entry list)
-	  (setq reftex-tables-dirty t
-		changed t)
-	  (push entry list)))
+        (setq entry (pop entry-list))
+        (unless (member entry list)
+          (setq reftex-tables-dirty t
+                changed t)
+          (push entry list)))
       (when changed
-	(put reftex-docstruct-symbol 'reftex-section-levels list)))))
+        (put reftex-docstruct-symbol 'reftex-section-levels list)))))
 
 (defun reftex-notice-new-section ()
   (reftex-notice-new 1 'force))
--- a/lisp/textmodes/reftex-cite.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-cite.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-cite.el --- creating citations with RefTeX
-;; Copyright (c) 1997, 1998, 1999, 2000, 2003  Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 
 ;; This file is part of GNU Emacs.
 
@@ -57,21 +57,21 @@
 (defmacro reftex-with-special-syntax-for-bib (&rest body)
   `(let ((saved-syntax (syntax-table)))
      (unwind-protect
-	 (progn
-	   (set-syntax-table reftex-syntax-table-for-bib)
-	   ,@body)
+         (progn
+           (set-syntax-table reftex-syntax-table-for-bib)
+           ,@body)
        (set-syntax-table saved-syntax))))
 
 (defun reftex-default-bibliography ()
   ;; Return the expanded value of `reftex-default-bibliography'.
   ;; The expanded value is cached.
   (unless (eq (get 'reftex-default-bibliography :reftex-raw)
-	      reftex-default-bibliography)
+              reftex-default-bibliography)
     (put 'reftex-default-bibliography :reftex-expanded
-	 (reftex-locate-bibliography-files
-	  default-directory reftex-default-bibliography))
+         (reftex-locate-bibliography-files 
+          default-directory reftex-default-bibliography))
     (put 'reftex-default-bibliography :reftex-raw
-	 reftex-default-bibliography))
+         reftex-default-bibliography))
   (get 'reftex-default-bibliography :reftex-expanded))
 
 (defun reftex-bib-or-thebib ()
@@ -79,19 +79,19 @@
   ;; citation
   ;; Find the bof of the current file
   (let* ((docstruct (symbol-value reftex-docstruct-symbol))
-	 (rest (or (member (list 'bof (buffer-file-name)) docstruct)
-		   docstruct))
-	 (bib (assq 'bib rest))
-	 (thebib (assq 'thebib rest))
-	 (bibmem (memq bib rest))
-	 (thebibmem (memq thebib rest)))
+         (rest (or (member (list 'bof (buffer-file-name)) docstruct)
+                   docstruct))
+         (bib (assq 'bib rest))
+         (thebib (assq 'thebib rest))
+         (bibmem (memq bib rest))
+         (thebibmem (memq thebib rest)))
     (when (not (or thebib bib))
       (setq bib (assq 'bib docstruct)
-	    thebib (assq 'thebib docstruct)
-	    bibmem (memq bib docstruct)
-	    thebibmem (memq thebib docstruct)))
+            thebib (assq 'thebib docstruct)
+            bibmem (memq bib docstruct)
+            thebibmem (memq thebib docstruct)))
     (if (> (length bibmem) (length thebibmem))
-	(if bib 'bib nil)
+        (if bib 'bib nil)
       (if thebib 'thebib nil))))
 
 (defun reftex-get-bibfile-list ()
@@ -119,7 +119,7 @@
 ;; Find a certain reference in any of the BibTeX files.
 
 (defun reftex-pop-to-bibtex-entry (key file-list &optional mark-to-kill
-				       highlight item return)
+                                       highlight item return)
   ;; Find BibTeX KEY in any file in FILE-LIST in another window.
   ;; If MARK-TO-KILL is non-nil, mark new buffer to kill.
   ;; If HIGHLIGHT is non-nil, highlight the match.
@@ -127,11 +127,11 @@
   ;; If RETURN is non-nil, just return the entry.
 
   (let* ((re
-	  (if item
-	      (concat "\\\\bibitem\\(\\[[^]]*\\]\\)?{" (regexp-quote key) "}")
-	    (concat "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*" (regexp-quote key)
-		    "[, \t\r\n}]")))
-	 (buffer-conf (current-buffer))
+          (if item 
+              (concat "\\\\bibitem\\(\\[[^]]*\\]\\)?{" (regexp-quote key) "}")
+            (concat "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*" (regexp-quote key)
+                    "[, \t\r\n}]")))
+         (buffer-conf (current-buffer))
          file buf pos)
 
     (catch 'exit
@@ -145,47 +145,71 @@
         (goto-char (point-min))
         (when (re-search-forward re nil t)
           (goto-char (match-beginning 0))
-	  (setq pos (point))
-	  (when return
-	    ;; Just return the relevant entry
-	    (if item (goto-char (match-end 0)))
-	    (setq return (buffer-substring
-			  (point) (reftex-end-of-bib-entry item)))
-	    (set-buffer buffer-conf)
-	    (throw 'exit return))
-	  (switch-to-buffer-other-window buf)
-	  (goto-char pos)
+          (setq pos (point))
+          (when return
+            ;; Just return the relevant entry
+            (if item (goto-char (match-end 0)))
+            (setq return (buffer-substring 
+                          (point) (reftex-end-of-bib-entry item)))
+            (set-buffer buffer-conf)
+            (throw 'exit return))
+          (switch-to-buffer-other-window buf)
+          (goto-char pos)
           (recenter 0)
           (if highlight
               (reftex-highlight 0 (match-beginning 0) (match-end 0)))
           (throw 'exit (selected-window))))
       (set-buffer buffer-conf)
       (if item
-	  (error "No \\bibitem with citation key %s" key)
-	(error "No BibTeX entry with citation key %s" key)))))
+          (error "No \\bibitem with citation key %s" key)
+        (error "No BibTeX entry with citation key %s" key)))))
 
 (defun reftex-end-of-bib-entry (item)
-  (save-excursion
+  (save-excursion 
     (condition-case nil
-	(if item
-	    (progn (end-of-line)
-		   (re-search-forward
-		    "\\\\bibitem\\|\\end{thebibliography}")
-		   (1- (match-beginning 0)))
-	  (progn (forward-list 1) (point)))
+        (if item 
+            (progn (end-of-line)
+                   (re-search-forward
+                    "\\\\bibitem\\|\\end{thebibliography}")
+                   (1- (match-beginning 0)))
+          (progn (forward-list 1) (point)))
       (error (min (point-max) (+ 300 (point)))))))
 
 ;; Parse bibtex buffers
 
-(defun reftex-extract-bib-entries (buffers re-list)
+(defun reftex-extract-bib-entries (buffers)
   ;; Extract bib entries which match regexps from BUFFERS.
   ;; BUFFERS is a list of buffers or file names.
   ;; Return list with entries."
-  (let* ((buffer-list (if (listp buffers) buffers (list buffers)))
-	 (first-re (car re-list))   ; We'll use the first re to find things,
-	 (rest-re (cdr re-list))    ; the others to narrow down.
-	 found-list entry buffer1 buffer alist
-	 key-point start-point end-point default)
+  (let* (re-list first-re rest-re
+                 (buffer-list (if (listp buffers) buffers (list buffers)))
+                 found-list entry buffer1 buffer alist
+                 key-point start-point end-point default)
+
+    ;; Read a regexp, completing on known citation keys.
+    (setq default (regexp-quote (reftex-get-bibkey-default)))
+    (setq re-list 
+          (split-string 
+           (completing-read 
+            (concat
+             "Regex { && Regex...}: "
+             "[" default "]: ")
+            (if reftex-mode
+                (if (fboundp 'LaTeX-bibitem-list)
+                    (LaTeX-bibitem-list)
+                  (cdr (assoc 'bibview-cache 
+                              (symbol-value reftex-docstruct-symbol))))
+              nil)
+            nil nil nil 'reftex-cite-regexp-hist)
+           "[ \t]*&&[ \t]*"))
+
+    (if (or (null re-list ) (equal re-list '("")))
+        (setq re-list (list default)))
+
+    (setq first-re (car re-list)    ; We'll use the first re to find things,
+          rest-re  (cdr re-list))   ; the others to narrow down.
+    (if (string-match "\\`[ \t]*\\'" (or first-re ""))
+        (error "Empty regular expression"))
 
     (save-excursion
       (save-window-excursion
@@ -204,62 +228,65 @@
             (message "Scanning bibliography database %s" buffer1))
 
           (set-buffer buffer1)
-	  (reftex-with-special-syntax-for-bib
-	   (save-excursion
-	     (goto-char (point-min))
-	     (while (re-search-forward first-re nil t)
-	       (catch 'search-again
-		 (setq key-point (point))
-		 (unless (re-search-backward
-			  "^[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*[{(]" nil t)
-		   (throw 'search-again nil))
-		 (setq start-point (point))
-		 (goto-char (match-end 0))
-		 (condition-case nil
-		     (up-list 1)
-		   (error (goto-char key-point)
+          (reftex-with-special-syntax-for-bib
+           (save-excursion
+             (goto-char (point-min))
+             (while (re-search-forward first-re nil t)
+               (catch 'search-again
+                 (setq key-point (point))
+                 (unless (re-search-backward
+                          "\\(\\`\\|[\n\r]\\)[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*[{(]" nil t)
+                   (throw 'search-again nil))
+                 (setq start-point (point))
+                 (goto-char (match-end 0))
+                 (condition-case nil
+                     (up-list 1)
+                   (error (goto-char key-point)
                           (throw 'search-again nil)))
-		 (setq end-point (point))
-
-		 ;; Ignore @string, @comment and @c entries or things
-		 ;; outside entries
-		 (when (or (member-ignore-case (match-string 1)
-					       '("string" "comment" "c"))
-			   (< (point) key-point)) ; this means match not in {}
-		   (goto-char key-point)
-		   (throw 'search-again nil))
-
-		 ;; Well, we have got a match
-		 (setq entry (buffer-substring start-point (point)))
-		 
-		 ;; Check if other regexp match as well
-		 (setq re-list rest-re)
-		 (while re-list
-		   (unless (string-match (car re-list) entry)
-		     ;; nope - move on
-		     (throw 'search-again nil))
-		   (pop re-list))
-
-		 (setq alist (reftex-parse-bibtex-entry
-			      nil start-point end-point))
-		 (push (cons "&entry" entry) alist)
-
-		 ;; check for crossref entries
-		 (if (assoc "crossref" alist)
-		     (setq alist
-			   (append
-			    alist (reftex-get-crossref-alist alist))))
-
-		 ;; format the entry
-		 (push (cons "&formatted" (reftex-format-bib-entry alist))
-		       alist)
-
-		 ;; make key the first element
-		 (push (reftex-get-bib-field "&key" alist) alist)
-
-		 ;; add it to the list
-		 (push alist found-list)))))
-	  (reftex-kill-temporary-buffers))))
+                 (setq end-point (point))
+                 
+                 ;; Ignore @string, @comment and @c entries or things
+                 ;; outside entries
+                 (when (or (string= (downcase (match-string 2)) "string")
+                           (string= (downcase (match-string 2)) "comment")
+                           (string= (downcase (match-string 2)) "c")
+                           (< (point) key-point)) ; this means match not in {}
+                   (goto-char key-point)
+                   (throw 'search-again nil))
+                 
+                 ;; Well, we have got a match
+                 ;;(setq entry (concat
+                 ;;             (buffer-substring start-point (point)) "\n"))
+                 (setq entry (buffer-substring start-point (point)))
+                 
+                 ;; Check if other regexp match as well
+                 (setq re-list rest-re)
+                 (while re-list
+                   (unless (string-match (car re-list) entry)
+                     ;; nope - move on
+                     (throw 'search-again nil))
+                   (pop re-list))
+                 
+                 (setq alist (reftex-parse-bibtex-entry
+                              nil start-point end-point))
+                 (push (cons "&entry" entry) alist)
+                 
+                 ;; check for crossref entries
+                 (if (assoc "crossref" alist)
+                     (setq alist
+                           (append
+                            alist (reftex-get-crossref-alist alist))))
+                 
+                 ;; format the entry
+                 (push (cons "&formatted" (reftex-format-bib-entry alist))
+                       alist)
+                 
+                 ;; make key the first element
+                 (push (reftex-get-bib-field "&key" alist) alist)
+                 
+                 ;; add it to the list
+                 (push alist found-list)))))
+          (reftex-kill-temporary-buffers))))
     (setq found-list (nreverse found-list))
 
     ;; Sorting
@@ -310,61 +337,84 @@
           nil)))))
 
 ;; Parse the bibliography environment
-(defun reftex-extract-bib-entries-from-thebibliography (files re-list)
+(defun reftex-extract-bib-entries-from-thebibliography (files)
   ;; Extract bib-entries from the \begin{thebibliography} environment.
   ;; Parsing is not as good as for the BibTeX database stuff.
   ;; The environment should be located in file FILE.
 
-  (let* (start end buf entries re file default)
+  (let* (start end buf entries re re-list file default)
     (unless files
       (error "Need file name to find thebibliography environment"))
     (while (setq file (pop files))
-      (setq buf (reftex-get-file-buffer-force
-		 file (not reftex-keep-temporary-buffers)))
+      (setq buf (reftex-get-file-buffer-force 
+                 file (not reftex-keep-temporary-buffers)))
       (unless buf
-	(error "No such file %s" file))
+        (error "No such file %s" file))
       (message "Scanning thebibliography environment in %s" file)
 
       (save-excursion
-	(set-buffer buf)
-	(save-restriction
-	  (widen)
-	  (goto-char (point-min))
-	  (while (re-search-forward
-		  "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
-	    (beginning-of-line 2)
-	    (setq start (point))
-	    (if (re-search-forward
-		 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\end{thebibliography}" nil t)
-		(progn
-		  (beginning-of-line 1)
-		  (setq end (point))))
-	    (when (and start end)
-	      (setq entries
-		    (append entries
+        (set-buffer buf)
+        (save-restriction
+          (widen)
+          (goto-char (point-min))
+          (while (re-search-forward 
+                  "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
+            (beginning-of-line 2)
+            (setq start (point))
+            (if (re-search-forward 
+                 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\end{thebibliography}" nil t)
+                (progn
+                  (beginning-of-line 1)
+                  (setq end (point))))
+            (when (and start end)
+              (setq entries 
+                    (append entries
                       (mapcar 'reftex-parse-bibitem
-			(delete ""
-				(split-string
-				 (buffer-substring-no-properties start end)
-				 "[ \t\n\r]*\\\\bibitem\\(\\[[^]]*]\\)*"))))))
-	    (goto-char end)))))
+                        (delete ""
+                                (split-string 
+                                 (buffer-substring-no-properties start end)
+                                 "[ \t\n\r]*\\\\bibitem\\(\\[[^]]*]\\)*"))))))
+            (goto-char end)))))
     (unless entries
       (error "No bibitems found"))
 
+    ;; Read a regexp, completing on known citation keys.
+    (setq default (regexp-quote (reftex-get-bibkey-default)))
+    (setq re-list 
+          (split-string 
+           (completing-read 
+            (concat
+             "Regex { && Regex...}: "
+             "[" default "]: ")
+            (if reftex-mode
+                (if (fboundp 'LaTeX-bibitem-list)
+                    (LaTeX-bibitem-list)
+                  (cdr (assoc 'bibview-cache 
+                              (symbol-value reftex-docstruct-symbol))))
+              nil)
+            nil nil nil 'reftex-cite-regexp-hist)
+           "[ \t]*&&[ \t]*"))
+
+    (if (or (null re-list ) (equal re-list '("")))
+        (setq re-list (list default)))
+
+    (if (string-match "\\`[ \t]*\\'" (car re-list))
+        (error "Empty regular expression"))
+
     (while (and (setq re (pop re-list)) entries)
-      (setq entries
-	    (delq nil (mapcar
-		       (lambda (x)
-			 (if (string-match re (cdr (assoc "&entry" x)))
-			     x nil))
-		       entries))))
-    (setq entries
-	  (mapcar
-	    (lambda (x)
-	      (push (cons "&formatted" (reftex-format-bibitem x)) x)
-	      (push (reftex-get-bib-field "&key" x) x)
-	      x)
-	   entries))
+      (setq entries 
+            (delq nil (mapcar
+                       (lambda (x)
+                         (if (string-match re (cdr (assoc "&entry" x)))
+                             x nil))
+                       entries))))
+    (setq entries 
+          (mapcar 
+            (lambda (x)
+              (push (cons "&formatted" (reftex-format-bibitem x)) x)
+              (push (reftex-get-bib-field "&key" x) x)
+              x)
+           entries))
 
     entries))
 
@@ -374,7 +424,7 @@
   (let* ((macro (reftex-what-macro 1)))
     (save-excursion
       (if (and macro (string-match "cite" (car macro)))
-	  (goto-char (cdr macro)))
+          (goto-char (cdr macro)))
       (skip-chars-backward "^a-zA-Z0-9")
       (reftex-this-word))))
 
@@ -403,7 +453,7 @@
             (progn
               (set-buffer (get-buffer-create " *RefTeX-scratch*"))
               (fundamental-mode)
-	      (set-syntax-table reftex-syntax-table-for-bib)
+              (set-syntax-table reftex-syntax-table-for-bib)
               (erase-buffer)
               (insert entry))
           (widen)
@@ -450,9 +500,9 @@
   ;; Extract the field FIELDNAME from an ENTRY
   (let ((cell (assoc fieldname entry)))
     (if cell
-	(if format
-	    (format format (cdr cell))
-	  (cdr cell))
+        (if format
+            (format format (cdr cell))
+          (cdr cell))
       "")))
 
 (defun reftex-format-bib-entry (entry)
@@ -487,9 +537,9 @@
     (setq authors (reftex-truncate authors 30 t t))
     (when (reftex-use-fonts)
       (put-text-property 0 (length key)     'face
-			 (reftex-verified-face reftex-label-face
-					       'font-lock-constant-face
-					       'font-lock-reference-face)
+                         (reftex-verified-face reftex-label-face
+                                               'font-lock-constant-face
+                                               'font-lock-reference-face)
                          key)
       (put-text-property 0 (length authors) 'face reftex-bib-author-face
                          authors)
@@ -506,12 +556,12 @@
   (let ((key "") (text ""))
     (when (string-match "\\`{\\([^}]+\\)}\\([^\000]*\\)" item)
       (setq key (match-string 1 item)
-	    text (match-string 2 item)))
+            text (match-string 2 item)))
     ;; Clean up the text a little bit
     (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
       (setq text (replace-match " " nil t text)))
     (if (string-match "\\`[ \t]+" text)
-	(setq text (replace-match "" nil t text)))
+        (setq text (replace-match "" nil t text)))
     (list
      (cons "&key" key)
      (cons "&text" text)
@@ -520,14 +570,14 @@
 (defun reftex-format-bibitem (item)
   ;; Format a \bibitem entry so that it is (relatively) nice to look at.
   (let ((text (reftex-get-bib-field "&text" item))
-	(key  (reftex-get-bib-field "&key" item))
-	(lines nil))
+        (key  (reftex-get-bib-field "&key" item))
+        (lines nil))
 
     ;; Wrap the text into several lines.
     (while (and (> (length text) 70)
-		(string-match " " (substring text 60)))
-	(push (substring text 0 (+ 60 (match-beginning 0))) lines)
-	(setq text (substring text (+ 61 (match-beginning 0)))))
+                (string-match " " (substring text 60)))
+        (push (substring text 0 (+ 60 (match-beginning 0))) lines)
+        (setq text (substring text (+ 61 (match-beginning 0)))))
     (push text lines)
     (setq text (mapconcat 'identity (nreverse lines) "\n     "))
 
@@ -579,18 +629,18 @@
   ;; This really does the work of reftex-citation.
 
   (let* ((format (reftex-figure-out-cite-format arg no-insert format-key))
-	 (docstruct-symbol reftex-docstruct-symbol)
-	 (selected-entries (reftex-offer-bib-menu))
-	 (insert-entries selected-entries)
-	 entry string cite-view)
+         (docstruct-symbol reftex-docstruct-symbol)
+         (selected-entries (reftex-offer-bib-menu))
+         (insert-entries selected-entries)
+         entry string cite-view)
 
     (unless selected-entries (error "Quit"))
 
     (if (stringp selected-entries)
-	;; Nonexistent entry
-	(setq selected-entries nil
-	      insert-entries (list (list selected-entries
-					 (cons "&key" selected-entries))))
+        ;; Nonexistent entry
+        (setq selected-entries nil
+              insert-entries (list (list selected-entries
+                                         (cons "&key" selected-entries))))
       ;; It makes sense to compute the cite-view strings.
       (setq cite-view t))
 
@@ -598,54 +648,54 @@
       ;; All keys go into a single command - we need to trick a little
       (pop selected-entries)
       (let ((concat-keys (mapconcat 'car selected-entries ",")))
-	(setq insert-entries
-	      (list (list concat-keys (cons "&key" concat-keys))))))
-
+        (setq insert-entries 
+              (list (list concat-keys (cons "&key" concat-keys))))))
+    
     (unless no-insert
 
       ;; We shall insert this into the buffer...
       (message "Formatting...")
 
       (while (setq entry (pop insert-entries))
-	;; Format the citation and insert it
-	(setq string (if reftex-format-cite-function
-			 (funcall reftex-format-cite-function
-				  (reftex-get-bib-field "&key" entry)
-				  format)
-		       (reftex-format-citation entry format)))
-	(insert string))
+        ;; Format the citation and insert it
+        (setq string (if reftex-format-cite-function
+                         (funcall reftex-format-cite-function
+                                  (reftex-get-bib-field "&key" entry)
+                                  format)
+                       (reftex-format-citation entry format)))
+        (insert string))
 
       ;; Reposition cursor?
       (when (string-match "\\?" string)
-	(search-backward "?")
-	(delete-char 1))
+        (search-backward "?")
+        (delete-char 1))
 
       ;; Tell AUCTeX
-      (when (and reftex-mode
-		 (fboundp 'LaTeX-add-bibitems)
-		 reftex-plug-into-AUCTeX)
-	(apply 'LaTeX-add-bibitems (mapcar 'car selected-entries)))
-
+      (when (and reftex-mode 
+                 (fboundp 'LaTeX-add-bibitems)
+                 reftex-plug-into-AUCTeX)
+        (apply 'LaTeX-add-bibitems (mapcar 'car selected-entries)))
+      
       ;; Produce the cite-view strings
       (when (and reftex-mode reftex-cache-cite-echo cite-view)
-	(mapcar (lambda (entry)
-		  (reftex-make-cite-echo-string entry docstruct-symbol))
-		selected-entries))
+        (mapcar (lambda (entry) 
+                  (reftex-make-cite-echo-string entry docstruct-symbol))
+                selected-entries))
 
       (message ""))
 
     (set-marker reftex-select-return-marker nil)
     (reftex-kill-buffer "*RefTeX Select*")
-
+    
     ;; Check if the prefix arg was numeric, and call recursively
     (when (integerp arg)
       (if (> arg 1)
-	  (progn
-	    (skip-chars-backward "}")
-	    (decf arg)
-	    (reftex-do-citation arg))
-	(forward-char 1)))
-
+          (progn      
+            (skip-chars-backward "}")
+            (decf arg)
+            (reftex-do-citation arg))
+        (forward-char 1)))
+    
     ;; Return the citation key
     (car (car selected-entries))))
 
@@ -653,44 +703,44 @@
   ;; Check if there is already a cite command at point and change cite format
   ;; in order to only add another reference in the same cite command.
   (let ((macro (car (reftex-what-macro 1)))
-	(cite-format-value (reftex-get-cite-format))
-	key format)
+        (cite-format-value (reftex-get-cite-format))
+        key format)
     (cond
      (no-insert
       ;; Format does not really matter because nothing will be inserted.
       (setq format "%l"))
-
+     
      ((and (stringp macro)
-	   (string-match "\\`\\\\cite\\|cite\\'" macro))
+           (string-match "\\`\\\\cite\\|cite\\'" macro))
       ;; We are already inside a cite macro
       (if (or (not arg) (not (listp arg)))
-	  (setq format
-		(concat
-		 (if (member (preceding-char) '(?\{ ?,)) "" ",")
-		 "%l"
-		 (if (member (following-char) '(?\} ?,)) "" ",")))
-	(setq format "%l")))
+          (setq format
+                (concat
+                 (if (member (preceding-char) '(?\{ ?,)) "" ",")
+                 "%l"
+                 (if (member (following-char) '(?\} ?,)) "" ",")))
+        (setq format "%l")))
      (t
       ;; Figure out the correct format
       (setq format
             (if (and (symbolp cite-format-value)
-		     (assq cite-format-value reftex-cite-format-builtin))
-		(nth 2 (assq cite-format-value reftex-cite-format-builtin))
-	      cite-format-value))
+                     (assq cite-format-value reftex-cite-format-builtin))
+                (nth 2 (assq cite-format-value reftex-cite-format-builtin))
+              cite-format-value))
       (when (listp format)
-	(setq key
-	      (or format-key
-		  (reftex-select-with-char
-		   "" (concat "SELECT A CITATION FORMAT\n\n"
-			      (mapconcat
-			       (lambda (x)
-				 (format "[%c] %s  %s" (car x)
-					 (if (> (car x) 31) " " "")
-					 (cdr x)))
-			       format "\n")))))
-	(if (assq key format)
-	    (setq format (cdr (assq key format)))
-	  (error "No citation format associated with key `%c'" key)))))
+        (setq key
+              (or format-key
+                  (reftex-select-with-char 
+                   "" (concat "SELECT A CITATION FORMAT\n\n"
+                              (mapconcat
+                               (lambda (x)
+                                 (format "[%c] %s  %s" (car x)
+                                         (if (> (car x) 31) " " "")
+                                         (cdr x)))
+                               format "\n")))))
+        (if (assq key format)
+            (setq format (cdr (assq key format)))
+          (error "No citation format associated with key `%c'" key)))))
     format))
 
 (defun reftex-citep ()
@@ -708,163 +758,141 @@
   ;; Offer bib menu and return list of selected items
 
   (let ((bibtype (reftex-bib-or-thebib))
-	found-list rtn key data selected-entries re-list)
-    (while
-	(not
-	 (catch 'done
-	   ;; Get the search regexps, completing on known citation keys.
-	   (setq re-list
-		 (let ((default (regexp-quote (reftex-get-bibkey-default))))
-		   (split-string 
-		    (completing-read 
-		     (concat
-		      "Regex { && Regex...}: "
-		      "[" default "]: ")
-		     (if reftex-mode
-			 (if (fboundp 'LaTeX-bibitem-list)
-			     (LaTeX-bibitem-list)
-			   (cdr (assoc 'bibview-cache 
-				       (symbol-value reftex-docstruct-symbol))))
-		       nil)
-		     nil nil nil 'reftex-cite-regexp-hist default)
-		    "[ \t]*&&[ \t]*")))
-
-	   (if (string-match "\\`[ \t]*\\'" (car re-list))
-	       (error "Empty regular expression"))
-
-	   ;; Scan bibtex files
-	   (setq found-list
-	      (cond
-	       ((eq bibtype 'bib)
-;	       ((assq 'bib (symbol-value reftex-docstruct-symbol))
-		;; using BibTeX database files.
-		(reftex-extract-bib-entries (reftex-get-bibfile-list) re-list))
-	       ((eq bibtype 'thebib)
-;	       ((assq 'thebib (symbol-value reftex-docstruct-symbol))
-		;; using thebibliography environment.
-		(reftex-extract-bib-entries-from-thebibliography
-		 (reftex-uniquify
-		  (mapcar 'cdr
-			  (reftex-all-assq
-			   'thebib (symbol-value reftex-docstruct-symbol))))
-		 re-list))
-	       (reftex-default-bibliography
-		(message "Using default bibliography")
-		(reftex-extract-bib-entries (reftex-default-bibliography)
-					    re-list))
-	       (t (error "No valid bibliography in this document, and no default available"))))
-
-	   (unless found-list
-	     (error "Sorry, no matches found"))
-
-	  ;; Remember where we came from
-	  (setq reftex-call-back-to-this-buffer (current-buffer))
-	  (set-marker reftex-select-return-marker (point))
-
-	  ;; Offer selection
-	  (save-window-excursion
-	    (delete-other-windows)
-	    (let ((default-major-mode 'reftex-select-bib-mode))
-	      (reftex-kill-buffer "*RefTeX Select*")
-	      (switch-to-buffer-other-window "*RefTeX Select*")
-	      (unless (eq major-mode 'reftex-select-bib-mode)
-		(reftex-select-bib-mode))
-	      (let ((buffer-read-only nil))
-		(erase-buffer)
-		(reftex-insert-bib-matches found-list)))
-	    (setq buffer-read-only t)
-	    (if (= 0 (buffer-size))
-		(error "No matches found"))
-	    (setq truncate-lines t)
-	    (goto-char 1)
-	    (while t
-	      (setq rtn
-		    (reftex-select-item
-		     reftex-citation-prompt
-		     reftex-citation-help
-		     reftex-select-bib-map
-		     nil
-		     'reftex-bibtex-selection-callback nil))
-	      (setq key (car rtn)
-		    data (nth 1 rtn))
-	      (unless key (throw 'done t))
-	      (cond
-	       ((eq key ?g)
-		;; Start over
-		(throw 'done nil))
-	       ((eq key ?r)
-		;; Restrict with new regular expression
-		(setq found-list (reftex-restrict-bib-matches found-list))
-		(let ((buffer-read-only nil))
-		  (erase-buffer)
-		  (reftex-insert-bib-matches found-list))
-		(goto-char 1))
-	       ((eq key ?A)
-		;; Take all (marked)
-		(setq selected-entries
-		      (if reftex-select-marked
-			  (mapcar 'car (nreverse reftex-select-marked))
-			found-list))
-		(throw 'done t))
-	       ((eq key ?a)
-		;; Take all (marked), and push the symbol 'concat
-		(setq selected-entries
-		      (cons 'concat
-			    (if reftex-select-marked
-				(mapcar 'car (nreverse reftex-select-marked))
-			      found-list)))
-		(throw 'done t))
-	       ((or (eq key ?\C-m)
-		    (eq key 'return))
-		;; Take selected
-		(setq selected-entries
-		      (if reftex-select-marked
-			  (cons 'concat
-				(mapcar 'car (nreverse reftex-select-marked)))
-			(if data (list data) nil)))
-		(throw 'done t))
-	       ((stringp key)
-		;; Got this one with completion
-		(setq selected-entries key)
-		(throw 'done t))
-	       (t
-		(ding))))))))
+        found-list rtn key data selected-entries)
+    (while 
+        (not 
+         (catch 'done
+           ;; Scan bibtex files
+           (setq found-list
+              (cond
+               ((eq bibtype 'bib)
+;              ((assq 'bib (symbol-value reftex-docstruct-symbol))
+                ;; using BibTeX database files.
+                (reftex-extract-bib-entries (reftex-get-bibfile-list)))
+               ((eq bibtype 'thebib)
+;              ((assq 'thebib (symbol-value reftex-docstruct-symbol))
+                ;; using thebibliography environment.
+                (reftex-extract-bib-entries-from-thebibliography
+                 (reftex-uniquify
+                  (mapcar 'cdr
+                          (reftex-all-assq 
+                           'thebib (symbol-value reftex-docstruct-symbol))))))
+               (reftex-default-bibliography
+                (message "Using default bibliography")
+                (reftex-extract-bib-entries (reftex-default-bibliography)))
+               (t (error "No valid bibliography in this document, and no default available"))))
+           
+           (unless found-list
+             (error "Sorry, no matches found"))
+    
+          ;; Remember where we came from
+          (setq reftex-call-back-to-this-buffer (current-buffer))
+          (set-marker reftex-select-return-marker (point))
+    
+          ;; Offer selection
+          (save-window-excursion
+            (delete-other-windows)
+            (let ((default-major-mode 'reftex-select-bib-mode))
+              (reftex-kill-buffer "*RefTeX Select*")
+              (switch-to-buffer-other-window "*RefTeX Select*")
+              (unless (eq major-mode 'reftex-select-bib-mode)
+                (reftex-select-bib-mode))
+              (let ((buffer-read-only nil))
+                (erase-buffer)
+                (reftex-insert-bib-matches found-list)))
+            (setq buffer-read-only t)
+            (if (= 0 (buffer-size))
+                (error "No matches found"))
+            (setq truncate-lines t)
+            (goto-char 1)
+            (while t
+              (setq rtn
+                    (reftex-select-item
+                     reftex-citation-prompt
+                     reftex-citation-help
+                     reftex-select-bib-map
+                     nil
+                     'reftex-bibtex-selection-callback nil))
+              (setq key (car rtn)
+                    data (nth 1 rtn))
+              (unless key (throw 'done t))
+              (cond
+               ((eq key ?g)
+                ;; Start over
+                (throw 'done nil))
+               ((eq key ?r)
+                ;; Restrict with new regular expression
+                (setq found-list (reftex-restrict-bib-matches found-list))
+                (let ((buffer-read-only nil))
+                  (erase-buffer)
+                  (reftex-insert-bib-matches found-list))
+                (goto-char 1))
+               ((eq key ?A)
+                ;; Take all (marked)
+                (setq selected-entries 
+                      (if reftex-select-marked
+                          (mapcar 'car (nreverse reftex-select-marked))
+                        found-list))
+                (throw 'done t))
+               ((eq key ?a)
+                ;; Take all (marked), and push the symbol 'concat
+                (setq selected-entries 
+                      (cons 'concat 
+                            (if reftex-select-marked
+                                (mapcar 'car (nreverse reftex-select-marked))
+                              found-list)))
+                (throw 'done t))
+               ((or (eq key ?\C-m)
+                    (eq key 'return))
+                ;; Take selected
+                (setq selected-entries 
+                      (if reftex-select-marked
+                          (cons 'concat 
+                                (mapcar 'car (nreverse reftex-select-marked)))
+                        (if data (list data) nil)))
+                (throw 'done t))
+               ((stringp key)
+                ;; Got this one with completion
+                (setq selected-entries key)
+                (throw 'done t))
+               (t
+                (ding))))))))
     selected-entries))
 
 (defun reftex-restrict-bib-matches (found-list)
   ;; Limit FOUND-LIST with more regular expressions
   (let ((re-list (split-string (read-string
-				"RegExp [ && RegExp...]: "
-				nil 'reftex-cite-regexp-hist)
-			       "[ \t]*&&[ \t]*"))
-	(found-list-r found-list)
-	re)
+                                "RegExp [ && RegExp...]: "
+                                nil 'reftex-cite-regexp-hist)
+                               "[ \t]*&&[ \t]*"))
+        (found-list-r found-list)
+        re)
     (while (setq re (pop re-list))
       (setq found-list-r
-	    (delq nil
-		  (mapcar
-		   (lambda (x)
-		     (if (string-match
-			  re (cdr (assoc "&entry" x)))
-			 x
-		       nil))
-		   found-list-r))))
+            (delq nil
+                  (mapcar
+                   (lambda (x)
+                     (if (string-match
+                          re (cdr (assoc "&entry" x)))
+                         x
+                       nil))
+                   found-list-r))))
     (if found-list-r
-	found-list-r
+        found-list-r
       (ding)
       found-list)))
 
 (defun reftex-insert-bib-matches (list)
   ;; Insert the bib matches and number them correctly
   (let ((mouse-face
-	 (if (memq reftex-highlight-selection '(mouse both))
-	     reftex-mouse-selected-face
-	   nil))
-	tmp len)
-    (mapcar
+         (if (memq reftex-highlight-selection '(mouse both))
+             reftex-mouse-selected-face
+           nil))
+        tmp len)
+    (mapcar 
      (lambda (x)
        (setq tmp (cdr (assoc "&formatted" x))
-	     len (length tmp))
+             len (length tmp))
        (put-text-property 0 len :data x tmp)
        (put-text-property 0 (1- len) 'mouse-face mouse-face tmp)
        (insert tmp))
@@ -916,7 +944,7 @@
                ((= l ?A) (car (reftex-get-bib-names "author" entry)))
                ((= l ?b) (reftex-get-bib-field "booktitle" entry "in: %s"))
                ((= l ?B) (reftex-abbreviate-title
-			  (reftex-get-bib-field "booktitle" entry "in: %s")))
+                          (reftex-get-bib-field "booktitle" entry "in: %s")))
                ((= l ?c) (reftex-get-bib-field "chapter" entry))
                ((= l ?d) (reftex-get-bib-field "edition" entry))
                ((= l ?e) (reftex-format-names
@@ -939,7 +967,7 @@
                ((= l ?r) (reftex-get-bib-field "address" entry))
                ((= l ?t) (reftex-get-bib-field "title" entry))
                ((= l ?T) (reftex-abbreviate-title
-			  (reftex-get-bib-field "title" entry)))
+                          (reftex-get-bib-field "title" entry)))
                ((= l ?v) (reftex-get-bib-field "volume" entry))
                ((= l ?y) (reftex-get-bib-field "year" entry)))))
 
@@ -956,25 +984,25 @@
 (defun reftex-make-cite-echo-string (entry docstruct-symbol)
   ;; Format a bibtex entry for the echo area and cache the result.
   (let* ((key (reftex-get-bib-field "&key" entry))
-	 (string
-	  (let* ((reftex-cite-punctuation '(" " " & " " etal.")))
-	    (reftex-format-citation entry reftex-cite-view-format)))
-	 (cache (assq 'bibview-cache (symbol-value docstruct-symbol)))
-	 (cache-entry (assoc key (cdr cache))))
+         (string 
+          (let* ((reftex-cite-punctuation '(" " " & " " etal.")))
+            (reftex-format-citation entry reftex-cite-view-format)))
+         (cache (assq 'bibview-cache (symbol-value docstruct-symbol)))
+         (cache-entry (assoc key (cdr cache))))
     (unless cache
       ;; This docstruct has no cache - make one.
       (set docstruct-symbol (cons (cons 'bibview-cache nil)
-				  (symbol-value docstruct-symbol))))
+                                  (symbol-value docstruct-symbol))))
     (when reftex-cache-cite-echo
       (setq key (copy-sequence key))
       (set-text-properties 0 (length key) nil key)
       (set-text-properties 0 (length string) nil string)
       (if cache-entry
-	  (unless (string= (cdr cache-entry) string)
-	    (setcdr cache-entry string)
-	    (put reftex-docstruct-symbol 'modified t))
-	(push (cons key string) (cdr cache))
-	(put reftex-docstruct-symbol 'modified t)))
+          (unless (string= (cdr cache-entry) string)
+            (setcdr cache-entry string)
+            (put reftex-docstruct-symbol 'modified t))
+        (push (cons key string) (cdr cache))
+        (put reftex-docstruct-symbol 'modified t)))
     string))
 
 (defun reftex-bibtex-selection-callback (data ignore no-revisit)
@@ -987,32 +1015,32 @@
 
     (catch 'exit
       (save-excursion
-	(set-buffer reftex-call-back-to-this-buffer)
-	(setq bibtype (reftex-bib-or-thebib))
-	(cond
-	 ((eq bibtype 'bib)
-;	 ((assq 'bib (symbol-value reftex-docstruct-symbol))
-	  (setq bibfile-list (reftex-get-bibfile-list)))
-	 ((eq bibtype 'thebib)
-;	 ((assq 'thebib (symbol-value reftex-docstruct-symbol))
-	  (setq bibfile-list
-		(reftex-uniquify
-		 (mapcar 'cdr
-			 (reftex-all-assq
-			  'thebib (symbol-value reftex-docstruct-symbol))))
-		item t))
-	 (reftex-default-bibliography
-	  (setq bibfile-list (reftex-default-bibliography)))
-	 (t (ding) (throw 'exit nil))))
+        (set-buffer reftex-call-back-to-this-buffer)
+        (setq bibtype (reftex-bib-or-thebib))
+        (cond
+         ((eq bibtype 'bib)
+;        ((assq 'bib (symbol-value reftex-docstruct-symbol))
+          (setq bibfile-list (reftex-get-bibfile-list)))
+         ((eq bibtype 'thebib)
+;        ((assq 'thebib (symbol-value reftex-docstruct-symbol))
+          (setq bibfile-list
+                (reftex-uniquify
+                 (mapcar 'cdr
+                         (reftex-all-assq 
+                          'thebib (symbol-value reftex-docstruct-symbol))))
+                item t))
+         (reftex-default-bibliography
+          (setq bibfile-list (reftex-default-bibliography)))
+         (t (ding) (throw 'exit nil))))
 
       (when no-revisit
-	(setq bibfile-list (reftex-visited-files bibfile-list)))
+        (setq bibfile-list (reftex-visited-files bibfile-list)))
 
       (condition-case nil
-	  (reftex-pop-to-bibtex-entry
-	   key bibfile-list (not reftex-keep-temporary-buffers) t item)
-	(error (ding))))
-
+          (reftex-pop-to-bibtex-entry 
+           key bibfile-list (not reftex-keep-temporary-buffers) t item)
+        (error (ding))))
+      
     (select-window win)))
 
 ;;; reftex-cite.el ends here
--- a/lisp/textmodes/reftex-dcr.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-dcr.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-dcr.el --- viewing cross references and citations with RefTeX
-;; Copyright (c) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 ;;
 
 ;; This file is part of GNU Emacs.
@@ -52,10 +52,10 @@
   ;; See where we are.
   (let* ((macro (car (reftex-what-macro-safe 1)))
          (key (reftex-this-word "^{}%\n\r, \t"))
-	 dw)
+         dw)
 
     (if (or (null macro) (reftex-in-comment))
-	(error "Not on a crossref macro argument"))
+        (error "Not on a crossref macro argument"))
 
     (setq reftex-call-back-to-this-buffer (current-buffer))
 
@@ -68,42 +68,42 @@
       (setq dw (reftex-view-cr-ref arg key auto-how)))
      (auto-how nil)  ;; No further action for automatic display (speed)
      ((or (equal macro "\\label")
-	  (member macro reftex-macros-with-labels))
+          (member macro reftex-macros-with-labels))
       ;; A label macro: search for reference macros
       (reftex-access-scan-info arg)
       (setq dw (reftex-view-regexp-match
-		(format reftex-find-reference-format (regexp-quote key))
-		4 nil nil)))
+                (format reftex-find-reference-format (regexp-quote key))
+                4 nil nil)))
      ((equal macro "\\bibitem")
       ;; A bibitem macro: search for citations
       (reftex-access-scan-info arg)
       (setq dw (reftex-view-regexp-match
-		(format reftex-find-citation-regexp-format (regexp-quote key))
-		4 nil nil)))
+                (format reftex-find-citation-regexp-format (regexp-quote key))
+                4 nil nil)))
      ((member macro reftex-macros-with-index)
       (reftex-access-scan-info arg)
       (setq dw (reftex-view-regexp-match
-		(format reftex-find-index-entry-regexp-format
-			(regexp-quote key))
-		3 nil nil)))
-     (t
+                (format reftex-find-index-entry-regexp-format
+                        (regexp-quote key))
+                3 nil nil)))
+     (t 
       (reftex-access-scan-info arg)
       (catch 'exit
-	(let ((list reftex-view-crossref-extra)
-	      entry mre action group)
-	  (while (setq entry (pop list))
-	    (setq mre (car entry)
-		  action (nth 1 entry)
-		  group (nth 2 entry))
-	    (when (string-match mre macro)
-	      (setq dw (reftex-view-regexp-match
-			(format action key) group nil nil))
-	      (throw 'exit t))))
-	(error "Not on a crossref macro argument"))))
+        (let ((list reftex-view-crossref-extra)
+              entry mre action group)
+          (while (setq entry (pop list))
+            (setq mre (car entry)
+                  action (nth 1 entry)
+                  group (nth 2 entry))
+            (when (string-match mre macro)
+              (setq dw (reftex-view-regexp-match 
+                        (format action key) group nil nil))
+              (throw 'exit t))))
+        (error "Not on a crossref macro argument"))))
     (if (and (eq arg 2) (windowp dw)) (select-window dw))))
-
+     
 (defun reftex-view-cr-cite (arg key how)
-  ;; View crossreference of a ref cite.  HOW can have the values
+  ;; View crossreference of a ref cite.  HOW can have the values 
   ;; nil:         Show in another window.
   ;; echo:        Show one-line info in echo area.
   ;; tmp-window:  Show in small window and arrange for window to disappear.
@@ -113,113 +113,113 @@
 
   (if (eq how 'tmp-window)
       ;; Remember the window configuration
-      (put 'reftex-auto-view-crossref 'last-window-conf
-	   (current-window-configuration)))
+      (put 'reftex-auto-view-crossref 'last-window-conf 
+           (current-window-configuration)))
 
   (let (files size item (pos (point)) (win (selected-window)) pop-win
-	      (bibtype (reftex-bib-or-thebib)))
+              (bibtype (reftex-bib-or-thebib)))
     ;; Find the citation mode and the file list
     (cond
 ;     ((assq 'bib (symbol-value reftex-docstruct-symbol))
      ((eq bibtype 'bib)
       (setq item nil
-	    files (reftex-get-bibfile-list)))
+            files (reftex-get-bibfile-list)))
 ;     ((assq 'thebib (symbol-value reftex-docstruct-symbol))
      ((eq bibtype 'thebib)
       (setq item t
-	    files (reftex-uniquify
-		   (mapcar 'cdr
-			   (reftex-all-assq
-			    'thebib (symbol-value reftex-docstruct-symbol))))))
+            files (reftex-uniquify
+                   (mapcar 'cdr
+                           (reftex-all-assq 
+                            'thebib (symbol-value reftex-docstruct-symbol))))))
      (reftex-default-bibliography
       (setq item nil
-	    files (reftex-default-bibliography)))
+            files (reftex-default-bibliography)))
      (how)  ;; don't throw for special display
      (t (error "Cannot display crossref")))
 
     (if (eq how 'echo)
-	;; Display in Echo area
-	(reftex-echo-cite key files item)
+        ;; Display in Echo area
+        (reftex-echo-cite key files item)
       ;; Display in a window
       (if (not (eq how 'tmp-window))
-	  ;; Normal display
-	  (reftex-pop-to-bibtex-entry key files nil t item)
-	;; A temporary window
-	(condition-case nil
-	    (reftex-pop-to-bibtex-entry key files nil t item)
-	  (error (goto-char pos)
-		 (message "cite: no such citation key %s" key)
-		 (error "")))
-	;; Resize the window
-	(setq size (max 1 (count-lines (point)
-				       (reftex-end-of-bib-entry item))))
-	(let ((window-min-height 2))
-	  (shrink-window (1- (- (window-height) size)))
-	  (recenter 0))
-	;; Arrange restoration
-	(add-hook 'pre-command-hook 'reftex-restore-window-conf))
+          ;; Normal display
+          (reftex-pop-to-bibtex-entry key files nil t item)
+        ;; A temporary window
+        (condition-case nil
+            (reftex-pop-to-bibtex-entry key files nil t item)
+          (error (goto-char pos)
+                 (message "cite: no such citation key %s" key)
+                 (error "")))
+        ;; Resize the window
+        (setq size (max 1 (count-lines (point)
+                                       (reftex-end-of-bib-entry item))))
+        (let ((window-min-height 2))
+          (shrink-window (1- (- (window-height) size)))
+          (recenter 0))
+        ;; Arrange restoration
+        (add-hook 'pre-command-hook 'reftex-restore-window-conf))
 
-	;; Normal display in other window
+        ;; Normal display in other window
       (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
       (setq pop-win (selected-window))
       (select-window win)
       (goto-char pos)
       (when (equal arg 2)
-	(select-window pop-win)))))
+        (select-window pop-win)))))
 
 (defun reftex-view-cr-ref (arg label how)
-  ;; View crossreference of a ref macro.  HOW can have the values
+  ;; View crossreference of a ref macro.  HOW can have the values 
   ;; nil:         Show in another window.
   ;; echo:        Show one-line info in echo area.
   ;; tmp-window:  Show in small window and arrange for window to disappear.
 
   ;; Ensure access to scanning info
   (reftex-access-scan-info (or arg current-prefix-arg))
-
+  
   (if (eq how 'tmp-window)
       ;; Remember the window configuration
-      (put 'reftex-auto-view-crossref 'last-window-conf
-	   (current-window-configuration)))
+      (put 'reftex-auto-view-crossref 'last-window-conf 
+           (current-window-configuration)))
 
   (let* ((xr-data (assoc 'xr (symbol-value reftex-docstruct-symbol)))
-	 (xr-re (nth 2 xr-data))
-	 (entry (assoc label (symbol-value reftex-docstruct-symbol)))
-	 (win (selected-window)) pop-win (pos (point)))
+         (xr-re (nth 2 xr-data))
+         (entry (assoc label (symbol-value reftex-docstruct-symbol)))
+         (win (selected-window)) pop-win (pos (point)))
 
     (if (and (not entry) (stringp label) xr-re (string-match xr-re label))
-	;; Label is defined in external document
-	(save-excursion
-	  (save-match-data
-	    (set-buffer
-	     (or (reftex-get-file-buffer-force
-		  (cdr (assoc (match-string 1 label) (nth 1
-							  xr-data))))
-		 (error "Problem with external label %s" label))))
-	  (setq label (substring label (match-end 1)))
-	  (reftex-access-scan-info)
-	  (setq entry
-		(assoc label (symbol-value reftex-docstruct-symbol)))))
+        ;; Label is defined in external document
+        (save-excursion
+          (save-match-data
+            (set-buffer 
+             (or (reftex-get-file-buffer-force
+                  (cdr (assoc (match-string 1 label) (nth 1
+                                                          xr-data))))
+                 (error "Problem with external label %s" label))))
+          (setq label (substring label (match-end 1)))
+          (reftex-access-scan-info)
+          (setq entry 
+                (assoc label (symbol-value reftex-docstruct-symbol)))))
     (if (eq how 'echo)
-	;; Display in echo area
-	(reftex-echo-ref label entry (symbol-value reftex-docstruct-symbol))
+        ;; Display in echo area
+        (reftex-echo-ref label entry (symbol-value reftex-docstruct-symbol))
       (let ((window-conf (current-window-configuration)))
-	(condition-case nil
-	    (reftex-show-label-location entry t nil t t)
-	  (error (set-window-configuration window-conf)
-		 (message "ref: Label %s not found" label)
-		 (error "ref: Label %s not found" label)))) ;; 2nd is line OK
+        (condition-case nil
+            (reftex-show-label-location entry t nil t t)
+          (error (set-window-configuration window-conf)
+                 (message "ref: Label %s not found" label)
+                 (error "ref: Label %s not found" label)))) ;; 2nd is line OK
       (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
 
       (when (eq how 'tmp-window)
-	;; Resize window and arrange restauration
-	(shrink-window (1- (- (window-height) 9)))
-	(recenter '(4))
-	(add-hook 'pre-command-hook 'reftex-restore-window-conf))
+        ;; Resize window and arrange restauration
+        (shrink-window (1- (- (window-height) 9)))
+        (recenter '(4))
+        (add-hook 'pre-command-hook 'reftex-restore-window-conf))
       (setq pop-win (selected-window))
       (select-window win)
       (goto-char pos)
       (when (equal arg 2)
-	(select-window pop-win)))))
+        (select-window pop-win)))))
 
 (defun reftex-mouse-view-crossref (ev)
   "View cross reference of \\ref or \\cite macro where you click.
@@ -240,28 +240,28 @@
        (or (eq reftex-auto-view-crossref 'window) (not (current-message)))
        ;; Make sure we are not already displaying this one
        (not (memq last-command '(reftex-view-crossref
-				 reftex-mouse-view-crossref)))
+                                 reftex-mouse-view-crossref)))
        ;; Quick precheck if this might be a relevant spot
        ;; FIXME: Can fail with backslash in comment
-       (save-excursion
-	 (search-backward "\\" nil t)
-	 (looking-at "\\\\[a-zA-Z]*\\(cite\\|ref\\|bibentry\\)"))
+       (save-excursion  
+         (search-backward "\\" nil t)
+         (looking-at "\\\\[a-zA-Z]*\\(cite\\|ref\\|bibentry\\)"))
 
        (condition-case nil
-	   (let ((current-prefix-arg nil))
-	     (cond
-	      ((eq reftex-auto-view-crossref t)
-	       (reftex-view-crossref -1 'echo))
-	      ((eq reftex-auto-view-crossref 'window)
-	       (reftex-view-crossref -1 'tmp-window))
-	      (t nil)))
-	 (error nil))))
+           (let ((current-prefix-arg nil))
+             (cond
+              ((eq reftex-auto-view-crossref t)
+               (reftex-view-crossref -1 'echo))
+              ((eq reftex-auto-view-crossref 'window)
+               (reftex-view-crossref -1 'tmp-window))
+              (t nil)))
+         (error nil))))
 
 (defun reftex-restore-window-conf ()
   (set-window-configuration (get 'reftex-auto-view-crossref 'last-window-conf))
   (put 'reftex-auto-view-crossref 'last-window-conf nil)
   (remove-hook 'pre-command-hook 'reftex-restore-window-conf))
-
+                  
 (defun reftex-echo-ref (label entry docstruct)
   ;; Display crossref info in echo area.
   (cond
@@ -274,46 +274,46 @@
       (message "ref(%s): %s" (nth 1 entry) (nth 2 entry)))
     (let ((buf (get-buffer " *Echo Area*")))
       (when buf
-	(save-excursion
-	  (set-buffer buf)
-	  (run-hooks 'reftex-display-copied-context-hook)))))))
+        (save-excursion
+          (set-buffer buf)
+          (run-hooks 'reftex-display-copied-context-hook)))))))
 
 (defun reftex-echo-cite (key files item)
   ;; Display citation info in echo area.
   (let* ((cache (assq 'bibview-cache (symbol-value reftex-docstruct-symbol)))
-	 (cache-entry (assoc key (cdr cache)))
-	 entry string buf (all-files files))
+         (cache-entry (assoc key (cdr cache)))
+         entry string buf (all-files files))
 
     (if (and reftex-cache-cite-echo cache-entry)
-	;; We can just use the cache
-	(setq string (cdr cache-entry))
+        ;; We can just use the cache
+        (setq string (cdr cache-entry))
 
       ;; Need to look in the database
       (unless reftex-revisit-to-echo
-	(setq files (reftex-visited-files files)))
+        (setq files (reftex-visited-files files)))
 
-      (setq entry
-	    (condition-case nil
-		(save-excursion
-		  (reftex-pop-to-bibtex-entry key files nil nil item t))
-	      (error
-	       (if (and files (= (length all-files) (length files)))
-		   (message "cite: no such database entry: %s" key)
-		 (message (substitute-command-keys
-			   (format reftex-no-info-message "cite"))))
-	       nil)))
+      (setq entry 
+            (condition-case nil
+                (save-excursion
+                  (reftex-pop-to-bibtex-entry key files nil nil item t))
+              (error
+               (if (and files (= (length all-files) (length files)))
+                   (message "cite: no such database entry: %s" key)
+                 (message (substitute-command-keys 
+                           (format reftex-no-info-message "cite"))))
+               nil)))
       (when entry
-	(if item
-	    (setq string (reftex-nicify-text entry))
-	  (setq string (reftex-make-cite-echo-string
-			(reftex-parse-bibtex-entry entry)
-			reftex-docstruct-symbol)))))
+        (if item
+            (setq string (reftex-nicify-text entry))
+          (setq string (reftex-make-cite-echo-string
+                        (reftex-parse-bibtex-entry entry)
+                        reftex-docstruct-symbol)))))
     (unless (or (null string) (equal string ""))
       (message "cite: %s" string))
     (when (setq buf (get-buffer " *Echo Area*"))
       (save-excursion
-	(set-buffer buf)
-	(run-hooks 'reftex-display-copied-context-hook)))))
+        (set-buffer buf)
+        (run-hooks 'reftex-display-copied-context-hook)))))
 
 (defvar reftex-use-itimer-in-xemacs nil
   "*Non-nil means use the idle timers in XEmacs for crossref display.
@@ -326,34 +326,34 @@
   (interactive)
   (if reftex-auto-view-crossref-timer
       (progn
-	(if (featurep 'xemacs)
-	    (if reftex-use-itimer-in-xemacs
-		(delete-itimer reftex-auto-view-crossref-timer)
-	      (remove-hook 'post-command-hook 'reftex-start-itimer-once))
-	  (cancel-timer reftex-auto-view-crossref-timer))
-	(setq reftex-auto-view-crossref-timer nil)
-	(message "Automatic display of crossref information was turned off"))
+        (if (featurep 'xemacs)
+            (if reftex-use-itimer-in-xemacs
+                (delete-itimer reftex-auto-view-crossref-timer)
+              (remove-hook 'post-command-hook 'reftex-start-itimer-once))
+          (cancel-timer reftex-auto-view-crossref-timer))
+        (setq reftex-auto-view-crossref-timer nil)
+        (message "Automatic display of crossref information was turned off"))
     (setq reftex-auto-view-crossref-timer
-	  (if (featurep 'xemacs)
-	      (if reftex-use-itimer-in-xemacs
-		  (start-itimer "RefTeX Idle Timer"
-				'reftex-view-crossref-when-idle
-				reftex-idle-time reftex-idle-time t)
-		(add-hook 'post-command-hook 'reftex-start-itimer-once)
-		t)
-	    (run-with-idle-timer
-	     reftex-idle-time t 'reftex-view-crossref-when-idle)))
+          (if (featurep 'xemacs)
+              (if reftex-use-itimer-in-xemacs
+                  (start-itimer "RefTeX Idle Timer"
+                                'reftex-view-crossref-when-idle 
+                                reftex-idle-time reftex-idle-time t)
+                (add-hook 'post-command-hook 'reftex-start-itimer-once)
+                t)
+            (run-with-idle-timer
+             reftex-idle-time t 'reftex-view-crossref-when-idle)))
     (unless reftex-auto-view-crossref
       (setq reftex-auto-view-crossref t))
     (message "Automatic display of crossref information was turned on")))
 
 (defun reftex-start-itimer-once ()
    (and reftex-mode
-	(not (itimer-live-p reftex-auto-view-crossref-timer))
-	(setq reftex-auto-view-crossref-timer
-	      (start-itimer "RefTeX Idle Timer"
-			    'reftex-view-crossref-when-idle
-			    reftex-idle-time nil t))))
+        (not (itimer-live-p reftex-auto-view-crossref-timer))
+        (setq reftex-auto-view-crossref-timer
+              (start-itimer "RefTeX Idle Timer"
+                            'reftex-view-crossref-when-idle 
+                            reftex-idle-time nil t))))
 
 (defun reftex-view-crossref-from-bibtex (&optional arg)
   "View location in a LaTeX document which cites the BibTeX entry at point.
@@ -362,34 +362,34 @@
 link to a document, call the function with with a prefix arg.
 Calling this function several times find successive citation locations."
   (interactive "P")
-  (when arg
+  (when arg 
     ;; Break connection to reference buffer
     (put 'reftex-bibtex-view-cite-locations :ref-buffer nil))
   (let ((ref-buffer (get 'reftex-bibtex-view-cite-locations :ref-buffer)))
     ;; Establish connection to reference buffer
     (unless ref-buffer
       (setq ref-buffer
-	    (save-excursion
-	      (completing-read
-	       "Reference buffer: "
-	       (delq nil
-		     (mapcar
-		      (lambda (b)
-			(set-buffer b)
-			(if reftex-mode (list (buffer-name b)) nil))
-		      (buffer-list)))
-	       nil t)))
+            (save-excursion
+              (completing-read 
+               "Reference buffer: "
+               (delq nil
+                     (mapcar 
+                      (lambda (b)
+                        (set-buffer b)
+                        (if reftex-mode (list (buffer-name b)) nil))
+                      (buffer-list)))
+               nil t)))
       (put 'reftex-bibtex-view-cite-locations :ref-buffer ref-buffer))
     ;; Search for citations
     (bibtex-beginning-of-entry)
     (if (looking-at
-	 "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*\\([^, \t\r\n}]+\\)")
-	(progn
-	  (goto-char (match-beginning 1))
-	  (reftex-view-regexp-match
-	   (format reftex-find-citation-regexp-format
-		   (regexp-quote (match-string 1)))
-	   4 arg ref-buffer))
+         "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*\\([^, \t\r\n}]+\\)")
+        (progn
+          (goto-char (match-beginning 1))
+          (reftex-view-regexp-match
+           (format reftex-find-citation-regexp-format
+                   (regexp-quote (match-string 1)))
+           4 arg ref-buffer))
       (error "Cannot find citation key in BibTeX entry"))))
 
 (defun reftex-view-regexp-match (re &optional highlight-group new ref-buffer)
@@ -402,39 +402,39 @@
 
   ;;; Decide if new search or continued search
   (let* ((oldprop (get 'reftex-view-regexp-match :props))
-	 (newprop (list (current-buffer) re))
-	 (cont (and (not new) (equal oldprop newprop)))
-	 (cnt (if cont (get 'reftex-view-regexp-match :cnt) 0))
-	 (current-window (selected-window))
-	 (window-conf (current-window-configuration))
-	 match pop-window)
+         (newprop (list (current-buffer) re))
+         (cont (and (not new) (equal oldprop newprop)))
+         (cnt (if cont (get 'reftex-view-regexp-match :cnt) 0))
+         (current-window (selected-window))
+         (window-conf (current-window-configuration))
+         match pop-window)
     (switch-to-buffer-other-window (or ref-buffer (current-buffer)))
     ;; Search
     (condition-case nil
-	(if cont
-	    (setq match (reftex-global-search-continue))
-	  (reftex-access-scan-info)
-	  (setq match (reftex-global-search re (reftex-all-document-files))))
+        (if cont
+            (setq match (reftex-global-search-continue))
+          (reftex-access-scan-info)
+          (setq match (reftex-global-search re (reftex-all-document-files))))
       (error nil))
     ;; Evaluate the match.
     (if match
-	(progn
-	  (put 'reftex-view-regexp-match :props newprop)
-	  (put 'reftex-view-regexp-match :cnt (incf cnt))
-	  (reftex-highlight 0 (match-beginning highlight-group)
-			    (match-end highlight-group))
-	  (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
-	  (setq pop-window (selected-window)))
+        (progn
+          (put 'reftex-view-regexp-match :props newprop)
+          (put 'reftex-view-regexp-match :cnt (incf cnt))
+          (reftex-highlight 0 (match-beginning highlight-group)
+                            (match-end highlight-group))
+          (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
+          (setq pop-window (selected-window)))
       (put 'reftex-view-regexp-match :props nil)
       (or cont (set-window-configuration window-conf)))
     (select-window current-window)
     (if match
-	(progn
-	  (message "Match Nr. %s" cnt)
-	  pop-window)
+        (progn
+          (message "Match Nr. %s" cnt)
+          pop-window)
       (if cont
-	  (error "No further matches (total number of matches: %d)" cnt)
-	(error "No matches")))))
+          (error "No further matches (total number of matches: %d)" cnt)
+        (error "No matches")))))
 
 (defvar reftex-global-search-marker (make-marker))
 (defun reftex-global-search (regexp file-list)
@@ -449,11 +449,11 @@
   (unless (get 'reftex-global-search :file-list)
     (error "No global search to continue"))
   (let* ((file-list (get 'reftex-global-search :file-list))
-	 (regexp (get 'reftex-global-search :regexp))
-	 (buf (or (marker-buffer reftex-global-search-marker)
-		  (reftex-get-file-buffer-force (car file-list))))
-	 (pos (or (marker-position reftex-global-search-marker) 1))
-	 file)
+         (regexp (get 'reftex-global-search :regexp))
+         (buf (or (marker-buffer reftex-global-search-marker)
+                  (reftex-get-file-buffer-force (car file-list))))
+         (pos (or (marker-position reftex-global-search-marker) 1))
+         file)
     ;; Take up starting position
     (unless buf (error "No such buffer %s" buf))
     (switch-to-buffer buf)
@@ -461,21 +461,21 @@
     (goto-char pos)
     ;; Search and switch file if necessary
     (if (catch 'exit
-	  (while t
-	    (when (re-search-forward regexp nil t)
-	      (move-marker reftex-global-search-marker (point))
-	      (throw 'exit t))
-	    ;; No match - goto next file
-	    (pop file-list)
-	    (or file-list (throw 'exit nil))
-	    (setq file (car file-list)
-		  buf (reftex-get-file-buffer-force file))
-	    (unless buf (error "Cannot access file %s" file))
-	    (put 'reftex-global-search :file-list file-list)
-	    (switch-to-buffer buf)
-	    (widen)
-	    (goto-char 1)))
-	t
+          (while t
+            (when (re-search-forward regexp nil t)
+              (move-marker reftex-global-search-marker (point))
+              (throw 'exit t))
+            ;; No match - goto next file
+            (pop file-list)
+            (or file-list (throw 'exit nil))
+            (setq file (car file-list)
+                  buf (reftex-get-file-buffer-force file))
+            (unless buf (error "Cannot access file %s" file))
+            (put 'reftex-global-search :file-list file-list)
+            (switch-to-buffer buf)
+            (widen)
+            (goto-char 1)))
+        t
       (move-marker reftex-global-search-marker nil)
       (error "All files processed"))))
 
--- a/lisp/textmodes/reftex-global.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-global.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-global.el --- operations on entire documents with RefTeX
-;; Copyright (c) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 
 ;; This file is part of GNU Emacs.
 
@@ -107,26 +107,26 @@
   (reftex-access-scan-info t)
 
   (let ((master (reftex-TeX-master-file))
-	(cnt 0)
+        (cnt 0)
         (dlist
          (mapcar
-	  (lambda (x)
-	    (let (x1)
-	      (cond
-	       ((memq (car x)
-		      '(toc bof eof bib thebib label-numbers xr xr-doc
-			    master-dir file-error bibview-cache appendix
-			    is-multi index))
-		nil)
-	       (t
-		(setq x1 (reftex-all-assoc-string
-			  (car x) (symbol-value reftex-docstruct-symbol)))
-		(if (< 1 (length x1))
-		    (append (list (car x))
-			    (mapcar (lambda(x)
-				      (abbreviate-file-name (nth 3 x)))
-				    x1))
-		  (list nil))))))
+          (lambda (x)
+            (let (x1)
+              (cond
+               ((memq (car x)
+                      '(toc bof eof bib thebib label-numbers xr xr-doc
+                            master-dir file-error bibview-cache appendix
+                            is-multi index))
+                nil)
+               (t
+                (setq x1 (reftex-all-assoc-string
+                          (car x) (symbol-value reftex-docstruct-symbol)))
+                (if (< 1 (length x1))
+                    (append (list (car x))
+                            (mapcar (lambda(x)
+                                      (abbreviate-file-name (nth 3 x)))
+                                    x1))
+                  (list nil))))))
           (reftex-uniquify-by-car (symbol-value reftex-docstruct-symbol)))))
 
     (setq dlist (reftex-uniquify-by-car dlist))
@@ -135,19 +135,19 @@
     (set (make-local-variable 'TeX-master) master)
     (erase-buffer)
     (insert "                MULTIPLE LABELS IN CURRENT DOCUMENT:\n")
-    (insert
+    (insert 
      " Move point to label and type `r' to run a query-replace on the label\n"
      " and its references.  Type `q' to exit this buffer.\n\n")
     (insert " LABEL               FILE\n")
     (insert " -------------------------------------------------------------\n")
     (use-local-map (make-sparse-keymap))
     (local-set-key [?q] (lambda () "Kill this buffer." (interactive)
-			  (kill-buffer (current-buffer)) (delete-window)))
+                          (kill-buffer (current-buffer)) (delete-window)))
     (local-set-key [?r] 'reftex-change-label)
     (while dlist
       (when (and (car (car dlist))
                  (cdr (car dlist)))
-	(incf cnt)
+        (incf cnt)
         (insert (mapconcat 'identity (car dlist) "\n    ") "\n"))
       (pop dlist))
     (goto-char (point-min))
@@ -157,7 +157,7 @@
       (message "Document does not contain duplicate labels."))))
 
 (defun reftex-change-label (&optional from to)
-  "Run `query-replace-regexp' of FROM with TO in all \\label and \\ref commands.
+  "Run `query-replace-regexp' of FROM with TO in all macro arguments.
 Works on the entire multifile document.
 If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
 with the command \\[tags-loop-continue].
@@ -172,8 +172,8 @@
       (setq to (read-string (format "Replace label %s with: "
                                     from))))
     (reftex-query-replace-document
-     (concat "\\\\\\(label\\|[a-zA-Z]*ref\\){" (regexp-quote from) "}")
-     (format "\\\\\\1{%s}" to))))
+     (concat "{" (regexp-quote from) "}")
+     (format "{%s}" to))))
 
 (defun reftex-renumber-simple-labels ()
   "Renumber all simple labels in the document to make them sequentially.
@@ -190,33 +190,33 @@
   (reftex-access-scan-info 1)
   ;; Get some insurance
   (if (and (reftex-is-multi)
-	   (not (yes-or-no-p "Replacing all simple labels in multiple files is risky.  Continue? ")))
+           (not (yes-or-no-p "Replacing all simple labels in multiple files is risky.  Continue? ")))
       (error "Abort"))
   ;; Make the translation list
-  (let* ((re-core (concat "\\("
-			  (mapconcat 'cdr reftex-typekey-to-prefix-alist "\\|")
-			  "\\)"))
-	 (label-re (concat "\\`" re-core "\\([0-9]+\\)\\'"))
-	 (search-re (concat "[{,]\\(" re-core "\\([0-9]+\\)\\)[,}]"))
-	 (error-fmt "Undefined label or reference %s. Ignore and continue? ")
-	 (label-numbers-alist (mapcar (lambda (x) (cons (cdr x) 0))
-				      reftex-typekey-to-prefix-alist))
-	 (files (reftex-all-document-files))
-	 (list (symbol-value reftex-docstruct-symbol))
-	 translate-alist n entry label new-label nr-cell changed-sequence)
+  (let* ((re-core (concat "\\(" 
+                          (mapconcat 'cdr reftex-typekey-to-prefix-alist "\\|") 
+                          "\\)"))
+         (label-re (concat "\\`" re-core "\\([0-9]+\\)\\'"))
+         (search-re (concat "[{,]\\(" re-core "\\([0-9]+\\)\\)[,}]"))
+         (error-fmt "Undefined label or reference %s. Ignore and continue? ")
+         (label-numbers-alist (mapcar (lambda (x) (cons (cdr x) 0))
+                                      reftex-typekey-to-prefix-alist))
+         (files (reftex-all-document-files))
+         (list (symbol-value reftex-docstruct-symbol))
+         translate-alist n entry label new-label nr-cell changed-sequence)
 
     (while (setq entry (pop list))
       (when (and (stringp (car entry))
-		 (string-match label-re (car entry)))
-	(setq label (car entry)
-	      nr-cell (assoc (match-string 1 (car entry))
-			     label-numbers-alist))
-	(if (assoc label translate-alist)
-	    (error "Duplicate label %s" label))
-	(setq new-label (concat (match-string 1 (car entry))
-				(int-to-string (incf (cdr nr-cell)))))
-	(push (cons label new-label) translate-alist)
-	(or (string= label new-label) (setq changed-sequence t))))
+                 (string-match label-re (car entry)))
+        (setq label (car entry)
+              nr-cell (assoc (match-string 1 (car entry))
+                             label-numbers-alist))
+        (if (assoc label translate-alist)
+            (error "Duplicate label %s" label))
+        (setq new-label (concat (match-string 1 (car entry))
+                                (int-to-string (incf (cdr nr-cell)))))
+        (push (cons label new-label) translate-alist)
+        (or (string= label new-label) (setq changed-sequence t))))
 
     (unless changed-sequence
       (error "Simple labels are already in correct sequence"))
@@ -227,79 +227,79 @@
     (reftex-save-all-document-buffers)
 
     ;; First test to check for erros
-    (setq n (reftex-translate
-	     files search-re translate-alist error-fmt 'test))
+    (setq n (reftex-translate 
+             files search-re translate-alist error-fmt 'test))
 
     ;; Now the real thing.
-    (if (yes-or-no-p
-	 (format "Replace %d items at %d places in %d files? "
-		 (length translate-alist) n (length files)))
-	(progn
-	  (let ((inhibit-quit t))  ;; Do not disturb...
-	    (reftex-translate
-	     files search-re translate-alist error-fmt nil)
-	    (setq quit-flag nil))
-	  (if (and (reftex-is-multi)
-		   (yes-or-no-p "Save entire document? "))
-	      (reftex-save-all-document-buffers))
-	  ;; Rescan again...
-	  (reftex-access-scan-info 1)
-	  (message "Done replacing simple labels."))
+    (if (yes-or-no-p 
+         (format "Replace %d items at %d places in %d files? "
+                 (length translate-alist) n (length files)))
+        (progn
+          (let ((inhibit-quit t))  ;; Do not disturb...
+            (reftex-translate
+             files search-re translate-alist error-fmt nil)
+            (setq quit-flag nil))
+          (if (and (reftex-is-multi)
+                   (yes-or-no-p "Save entire document? "))
+              (reftex-save-all-document-buffers))
+          ;; Rescan again...
+          (reftex-access-scan-info 1)
+          (message "Done replacing simple labels."))
       (message "No replacements done"))))
 
 (defun reftex-translate (files search-re translate-alist error-fmt test)
   ;; In FILES, look for SEARCH-RE and replace match 1 of it with
-  ;; its association in TRANSLATE-ALSIT.
+  ;; its association in TRANSLATE-ALSIT.  
   ;; If we do not find an association and TEST is non-nil, query
-  ;; to ignore the problematic string.
+  ;; to ignore the problematic string.  
   ;; If TEST is nil, it is ignored without query.
   ;; Return the number of replacements.
   (let ((n 0) file label match-data buf macro pos cell)
     (while (setq file (pop files))
       (setq buf (reftex-get-file-buffer-force file))
       (unless buf
-	(error "No such file %s" file))
+        (error "No such file %s" file))
       (set-buffer buf)
       (save-excursion
-	(save-restriction
-	  (widen)
-	  (goto-char (point-min))
-	  (while (re-search-forward search-re nil t)
-	    (backward-char)
-	    (save-excursion
-	      (setq label (reftex-match-string 1)
-		    cell (assoc label translate-alist)
-		    match-data (match-data)
-		    macro (reftex-what-macro 1)
-		    pos (cdr macro))
-	      (goto-char (or pos (point)))
-	      (when (and macro
-			 (or (looking-at "\\\\ref")
-			     (looking-at "\\\\[a-zA-Z]*ref\\(range\\)?[^a-zA-Z]")
-			     (looking-at "\\\\ref[a-zA-Z]*[^a-zA-Z]")
-			     (looking-at (format
-					  reftex-find-label-regexp-format
-					  (regexp-quote label)))))
-		;; OK, we should replace it.
-		(set-match-data match-data)
-		(cond
-		 ((and test (not cell))
-		  ;; We've got a problem
-		  (unwind-protect
-		      (progn
-			(reftex-highlight 1 (match-beginning 0) (match-end 0))
-			(ding)
-			(or (y-or-n-p (format error-fmt label))
-			    (error "Abort")))
-		    (reftex-unhighlight 1)))
-		 ((and test cell)
-		  (incf n))
-		 ((and (not test) cell)
-		  ;; Replace
-		  (goto-char (match-beginning 1))
-		  (delete-region (match-beginning 1) (match-end 1))
-		  (insert (cdr cell)))
-		 (t nil))))))))
+        (save-restriction
+          (widen)
+          (goto-char (point-min))
+          (while (re-search-forward search-re nil t)
+            (backward-char)
+            (save-excursion
+              (setq label (reftex-match-string 1)
+                    cell (assoc label translate-alist)
+                    match-data (match-data)
+                    macro (reftex-what-macro 1)
+                    pos (cdr macro))
+              (goto-char (or pos (point)))
+              (when (and macro
+                         (or (looking-at "\\\\ref")
+                             (looking-at "\\\\[a-zA-Z]*ref\\(range\\)?[^a-zA-Z]")
+                             (looking-at "\\\\ref[a-zA-Z]*[^a-zA-Z]")
+                             (looking-at (format 
+                                          reftex-find-label-regexp-format
+                                          (regexp-quote label)))))
+                ;; OK, we should replace it.
+                (set-match-data match-data)
+                (cond
+                 ((and test (not cell))
+                  ;; We've got a problem
+                  (unwind-protect
+                      (progn
+                        (reftex-highlight 1 (match-beginning 0) (match-end 0))
+                        (ding)
+                        (or (y-or-n-p (format error-fmt label))
+                            (error "Abort")))
+                    (reftex-unhighlight 1)))
+                 ((and test cell)
+                  (incf n))
+                 ((and (not test) cell)
+                  ;; Replace
+                  (goto-char (match-beginning 1))
+                  (delete-region (match-beginning 1) (match-end 1))
+                  (insert (cdr cell)))
+                 (t nil))))))))
     n))
 
 (defun reftex-save-all-document-buffers ()
@@ -308,13 +308,13 @@
 labels."
   (interactive)
   (let ((files (reftex-all-document-files))
-	file buffer)
+        file buffer)
     (save-excursion
       (while (setq file (pop files))
-	(setq buffer (reftex-get-buffer-visiting file))
-	(when buffer
-	  (set-buffer buffer)
-	  (save-buffer))))))
+        (setq buffer (reftex-get-buffer-visiting file))
+        (when buffer
+          (set-buffer buffer)
+          (save-buffer))))))
 
 (defun reftex-ensure-write-access (files)
   "Make sure we have write access to all files in FILES.
@@ -322,20 +322,20 @@
   (let (file buf)
     (while (setq file (pop files))
       (unless (file-exists-p file)
-	(ding)
-	(or (y-or-n-p (format "No such file %s. Continue? " file))
-	    (error "Abort")))
+        (ding)
+        (or (y-or-n-p (format "No such file %s. Continue? " file))
+            (error "Abort")))
       (unless (file-writable-p file)
-	(ding)
-	(or (y-or-n-p (format "No write access to %s. Continue? " file))
-	    (error "Abort")))
+        (ding)
+        (or (y-or-n-p (format "No write access to %s. Continue? " file))
+            (error "Abort")))
       (when (and (setq buf (reftex-get-buffer-visiting file))
-		 (save-excursion
-		   (set-buffer buf)
-		   buffer-read-only))
-	(ding)
-	(or (y-or-n-p (format "Buffer %s is read-only. Continue? "
-			      (buffer-name buf)))
-	    (error "Abort"))))))
+                 (save-excursion
+                   (set-buffer buf)
+                   buffer-read-only))
+        (ding)
+        (or (y-or-n-p (format "Buffer %s is read-only. Continue? "
+                              (buffer-name buf)))
+            (error "Abort"))))))
 
 ;;; reftex-global.el ends here
--- a/lisp/textmodes/reftex-index.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-index.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-index.el --- index support with RefTeX
-;; Copyright (c) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 
 ;; This file is part of GNU Emacs.
 
@@ -47,48 +47,48 @@
 `reftex-index-math-format', which see."
   (interactive "P")
   (let* ((use-default (not (equal arg '(16))))  ; check for double prefix
-	 ;; check if we have an active selection
-	 (active (if (boundp 'zmacs-regions)
-		     (and zmacs-regions (region-exists-p))  ; XEmacs
-		   (and transient-mark-mode mark-active)))  ; Emacs
-	 (beg (if active
-		  (region-beginning)
-		(save-excursion
-		  (skip-syntax-backward "w\\") (point))))
-	 (end (if active
-		  (region-end)
-		(save-excursion
-		  (skip-syntax-forward "w\\") (point))))
-	 (sel (buffer-substring beg end))
-	 (mathp (condition-case nil (texmathp) (error nil)))
-	 (current-prefix-arg nil) ; we want to call reftex-index without prefix.
-	 key def-char def-tag full-entry)
+         ;; check if we have an active selection
+         (active (if (boundp 'zmacs-regions)
+                     (and zmacs-regions (region-exists-p))  ; XEmacs
+                   (and transient-mark-mode mark-active)))  ; Emacs
+         (beg (if active 
+                  (region-beginning)
+                (save-excursion 
+                  (skip-syntax-backward "w\\") (point))))
+         (end (if active
+                  (region-end)
+                (save-excursion 
+                  (skip-syntax-forward "w\\") (point))))
+         (sel (buffer-substring beg end))
+         (mathp (condition-case nil (texmathp) (error nil)))
+         (current-prefix-arg nil) ; we want to call reftex-index without prefix.
+         key def-char def-tag full-entry)
 
     (if phrase
-	(progn
-	  (reftex-index-visit-phrases-buffer)
-	  (reftex-index-new-phrase sel))
+        (progn
+          (reftex-index-visit-phrases-buffer)
+          (reftex-index-new-phrase sel))
 
       (if (equal sel "")
-	  ;; Nothing selected, no word, so use full reftex-index command
-	  (reftex-index)
-	;; OK, we have something to index here.
-	;; Add the dollars when necessary
-	(setq key (if mathp
-		      (format reftex-index-math-format sel)
-		    sel))
-	;; Get info from `reftex-index-default-macro'
-	(setq def-char  (if use-default (car reftex-index-default-macro)))
-	(setq def-tag   (if use-default (nth 1 reftex-index-default-macro)))
-	;; Does the user want to edit the entry?
-	(setq full-entry (if arg
-			     (reftex-index-complete-key
-			      def-tag nil (cons key 0))
-			   key))
-	;; Delete what is in the buffer and make the index entry
-	(delete-region beg end)
-	(reftex-index def-char full-entry def-tag sel)))))
-
+          ;; Nothing selected, no word, so use full reftex-index command
+          (reftex-index)
+        ;; OK, we have something to index here.
+        ;; Add the dollars when necessary
+        (setq key (if mathp
+                      (format reftex-index-math-format sel)
+                    sel))
+        ;; Get info from `reftex-index-default-macro'
+        (setq def-char  (if use-default (car reftex-index-default-macro)))
+        (setq def-tag   (if use-default (nth 1 reftex-index-default-macro)))
+        ;; Does the user want to edit the entry?
+        (setq full-entry (if arg
+                             (reftex-index-complete-key
+                              def-tag nil (cons key 0))
+                           key))
+        ;; Delete what is in the buffer and make the index entry
+        (delete-region beg end)
+        (reftex-index def-char full-entry def-tag sel)))))
+  
 (defun reftex-index (&optional char key tag sel no-insert)
   "Query for an index macro and insert it along with its argments.
 The index macros available are those defined in `reftex-index-macro' or
@@ -104,58 +104,58 @@
 
   ;; Find out which macro we are going to use
   (let* ((char (or char
-		   (reftex-select-with-char reftex-query-index-macro-prompt
-					    reftex-query-index-macro-help)))
-	 (macro (nth 1 (assoc char reftex-key-to-index-macro-alist)))
-	 (entry (or (assoc macro reftex-index-macro-alist)
-		    (error "No index macro associated with %c" char)))
-	 (ntag (nth 1 entry))
-	 (tag (or tag (nth 1 entry)))
-	 (nargs (nth 4 entry))
-	 (nindex (nth 5 entry))
-	 (opt-args (nth 6 entry))
-	 (repeat (nth 7 entry))
-	 opt tag1 value)
+                   (reftex-select-with-char reftex-query-index-macro-prompt
+                                            reftex-query-index-macro-help)))
+         (macro (nth 1 (assoc char reftex-key-to-index-macro-alist)))
+         (entry (or (assoc macro reftex-index-macro-alist)
+                    (error "No index macro associated with %c" char)))
+         (ntag (nth 1 entry))
+         (tag (or tag (nth 1 entry)))
+         (nargs (nth 4 entry))
+         (nindex (nth 5 entry))
+         (opt-args (nth 6 entry))
+         (repeat (nth 7 entry))
+         opt tag1 value)
 
     ;; Get the supported arguments
     (if (stringp tag)
-	(setq tag1 tag)
+        (setq tag1 tag)
       (setq tag1 (or (reftex-index-complete-tag tag opt-args) "")))
     (setq key (or key
-		  (reftex-index-complete-key
-		   (if (string= tag1 "") "idx" tag1)
-		   (member nindex opt-args))))
+                  (reftex-index-complete-key
+                   (if (string= tag1 "") "idx" tag1)
+                   (member nindex opt-args))))
 
     ;; Insert the macro and ask for any additional args
     (insert macro)
     (loop for i from 1 to nargs do
       (setq opt (member i opt-args)
-	    value (cond ((= nindex i) key)
-			((equal ntag i) tag1)
-			(t (read-string (concat "Macro arg nr. "
-						(int-to-string i)
-						(if opt " (optional)" "")
-						": ")))))
+            value (cond ((= nindex i) key)
+                        ((equal ntag i) tag1)
+                        (t (read-string (concat "Macro arg nr. "
+                                                (int-to-string i)
+                                                (if opt " (optional)" "")
+                                                ": ")))))
       (unless (and opt (string= value ""))
-	(insert (if opt "[" "{") value (if opt "]" "}"))))
+        (insert (if opt "[" "{") value (if opt "]" "}"))))
     (and repeat (stringp sel) (insert sel))
     (and key reftex-plug-into-AUCTeX (fboundp 'LaTeX-add-index-entries)
-	 (LaTeX-add-index-entries key))
+         (LaTeX-add-index-entries key))
     (reftex-index-update-taglist tag1)
     (reftex-notice-new)))
 
 (defun reftex-default-index ()
   (cond ((null reftex-index-default-tag) nil)
-	((stringp reftex-index-default-tag) reftex-index-default-tag)
-	(t (or (get reftex-docstruct-symbol 'default-index-tag)
-	       "idx"))))
+        ((stringp reftex-index-default-tag) reftex-index-default-tag)
+        (t (or (get reftex-docstruct-symbol 'default-index-tag)
+               "idx"))))
 
 (defun reftex-update-default-index (tag &optional tag-list)
   (if (and (not (equal tag ""))
-	   (stringp tag)
-	   (eq reftex-index-default-tag 'last)
-	   (or (null tag-list)
-	       (member tag tag-list)))
+           (stringp tag)
+           (eq reftex-index-default-tag 'last)
+           (or (null tag-list)
+               (member tag tag-list)))
       (put reftex-docstruct-symbol 'default-index-tag tag)))
 
 (defun reftex-index-complete-tag (&optional itag opt-args)
@@ -164,13 +164,13 @@
   ;; OPT-ARGS is a list of optional argument indices, as given by
   ;; `reftex-parse-args'.
   (let* ((opt (and (integerp itag) (member itag opt-args)))
-	 (index-tags (cdr (assq 'index-tags
-				(symbol-value reftex-docstruct-symbol))))
-	 (default (reftex-default-index))
-	 (prompt (concat "Index tag"
-			 (if default (format " (default: %s)" default) "")
-			 (if opt " (optional)" "") ": "))
-	 (tag (completing-read prompt (mapcar 'list index-tags))))
+         (index-tags (cdr (assq 'index-tags 
+                                (symbol-value reftex-docstruct-symbol))))
+         (default (reftex-default-index))
+         (prompt (concat "Index tag"
+                         (if default (format " (default: %s)" default) "")
+                         (if opt " (optional)" "") ": "))
+         (tag (completing-read prompt (mapcar 'list index-tags))))
     (if (and default (equal tag "")) (setq tag default))
     (reftex-update-default-index tag)
     tag))
@@ -178,70 +178,70 @@
 (defun reftex-index-select-tag ()
   ;; Have the user select an index tag.
   ;; FIXME: should we cache tag-alist, prompt and help?
-  (let* ((index-tags (cdr (assoc 'index-tags
-				 (symbol-value reftex-docstruct-symbol))))
-	 (default (reftex-default-index)))
-    (cond
+  (let* ((index-tags (cdr (assoc 'index-tags 
+                                 (symbol-value reftex-docstruct-symbol))))
+         (default (reftex-default-index)))
+    (cond 
      ((null index-tags)
       (error "No index tags available"))
 
      ((= (length index-tags) 1)
       ;; Just one index, use it
       (car index-tags))
-
+          
      ((> (length index-tags) 1)
       ;; Several indices, ask.
       (let* ((tags (copy-sequence index-tags))
-	     (cnt 0)
-	     tag-alist i val len tag prompt help rpl)
-	;; Move idx and glo up in the list to ensure ?i and ?g shortcuts
-	(if (member "glo" tags)
-	    (setq tags (cons "glo" (delete "glo" tags))))
-	(if (member "idx" tags)
-	    (setq tags (cons "idx" (delete "idx" tags))))
-	;; Find unique shortcuts for each index.
-	(while (setq tag (pop tags))
-	  (setq len (length tag)
-		i -1
-		val nil)
-	  (catch 'exit
-	    (while (and (< (incf i) len) (null val))
-	      (unless (assq (aref tag i) tag-alist)
-		(push (list (aref tag i)
-			    tag
-			    (concat (substring tag 0 i)
-				    "[" (substring tag i (incf i)) "]"
-				    (substring tag i)))
-		      tag-alist)
-		(throw 'exit t)))
-	    (push (list (+ ?0 (incf cnt)) tag
-			(concat "[" (int-to-string cnt) "]:" tag))
-		  tag-alist)))
-	(setq tag-alist (nreverse tag-alist))
-	;; Compute Prompt and Help strings
-	(setq prompt
-	      (concat
-	       (format "Select Index%s: "
-		       (if default (format " (Default <%s>)" default) ""))
-	       (mapconcat (lambda(x) (nth 2 x)) tag-alist "  ")))
-	(setq help
-	      (concat "Select an Index\n===============\n"
-		      (if default
-			  (format "[^M]  %s (the default)\n" default)
-			"")
-		      (mapconcat (lambda(x)
-				   (apply 'format "[%c]   %s" x))
-				 tag-alist "\n")))
-	;; Query the user for an index-tag
-	(setq rpl (reftex-select-with-char prompt help 3 t))
-	(message "")
-	(if (and default (equal rpl ?\C-m))
-	    default
-	  (if (assq rpl tag-alist)
-	      (progn
-		(reftex-update-default-index (nth 1 (assq rpl tag-alist)))
-		(nth 1 (assq rpl tag-alist)))
-	    (error "No index tag associated with %c" rpl)))))
+             (cnt 0)
+             tag-alist i val len tag prompt help rpl)
+        ;; Move idx and glo up in the list to ensure ?i and ?g shortcuts
+        (if (member "glo" tags)
+            (setq tags (cons "glo" (delete "glo" tags))))
+        (if (member "idx" tags)
+            (setq tags (cons "idx" (delete "idx" tags))))
+        ;; Find unique shortcuts for each index.
+        (while (setq tag (pop tags))
+          (setq len (length tag)
+                i -1
+                val nil)
+          (catch 'exit
+            (while (and (< (incf i) len) (null val))
+              (unless (assq (aref tag i) tag-alist)
+                (push (list (aref tag i)
+                            tag
+                            (concat (substring tag 0 i) 
+                                    "[" (substring tag i (incf i)) "]"
+                                    (substring tag i)))
+                      tag-alist)
+                (throw 'exit t)))
+            (push (list (+ ?0 (incf cnt)) tag 
+                        (concat "[" (int-to-string cnt) "]:" tag))
+                  tag-alist)))
+        (setq tag-alist (nreverse tag-alist))
+        ;; Compute Prompt and Help strings
+        (setq prompt
+              (concat
+               (format "Select Index%s: "
+                       (if default (format " (Default <%s>)" default) ""))
+               (mapconcat (lambda(x) (nth 2 x)) tag-alist "  ")))
+        (setq help
+              (concat "Select an Index\n===============\n"
+                      (if default
+                          (format "[^M]  %s (the default)\n" default)
+                        "")
+                      (mapconcat (lambda(x) 
+                                   (apply 'format "[%c]   %s" x))
+                                 tag-alist "\n")))
+        ;; Query the user for an index-tag
+        (setq rpl (reftex-select-with-char prompt help 3 t))
+        (message "")
+        (if (and default (equal rpl ?\C-m))
+            default
+          (if (assq rpl tag-alist)
+              (progn
+                (reftex-update-default-index (nth 1 (assq rpl tag-alist)))
+                (nth 1 (assq rpl tag-alist)))
+            (error "No index tag associated with %c" rpl)))))
      (t (error "This should not happen (reftex-index-select-tag)")))))
 
 (defun reftex-index-complete-key (&optional tag optional initial)
@@ -249,19 +249,19 @@
   ;; Restrict completion table on index tag TAG.
   ;; OPTIONAL indicates if the arg is optional.
   (let* ((table (reftex-sublist-nth
-		 (symbol-value reftex-docstruct-symbol) 6
-		 (lambda(x) (and (eq (car x) 'index)
-				 (string= (nth 1 x) (or tag ""))))
-		 t))
-	 (prompt (concat "Index key" (if optional " (optional)" "") ": "))
-	 (key (completing-read prompt table nil nil initial)))
+                 (symbol-value reftex-docstruct-symbol) 6
+                 (lambda(x) (and (eq (car x) 'index)
+                                 (string= (nth 1 x) (or tag ""))))
+                 t))
+         (prompt (concat "Index key" (if optional " (optional)" "") ": "))
+         (key (completing-read prompt table nil nil initial)))
     key))
 
 (defun reftex-index-update-taglist (newtag)
-  ;; add NEWTAG to the list of available index tags.
+  ;; add NEWTAG to the list of available index tags. 
   (let ((cell (assoc 'index-tags (symbol-value reftex-docstruct-symbol))))
     (and newtag (cdr cell) (not (member newtag (cdr cell)))
-	 (push newtag (cdr cell)))))
+         (push newtag (cdr cell)))))
 
 (defvar reftex-index-map (make-sparse-keymap)
   "Keymap used for *Index* buffers.")
@@ -290,16 +290,16 @@
   (interactive)
   (kill-all-local-variables)
   (setq major-mode 'reftex-index-mode
-	mode-name "RefTeX Index")
+        mode-name "RefTeX Index")
   (use-local-map reftex-index-map)
   (set (make-local-variable 'revert-buffer-function) 'reftex-index-revert)
   (set (make-local-variable 'reftex-index-restriction-data) nil)
   (set (make-local-variable 'reftex-index-restriction-indicator) nil)
   (setq mode-line-format
-	(list "----  " 'mode-line-buffer-identification
-	      "   " 'global-mode-string
-	      "  R<" 'reftex-index-restriction-indicator ">"
-	      " -%-"))
+        (list "----  " 'mode-line-buffer-identification
+              "   " 'global-mode-string
+              "  R<" 'reftex-index-restriction-indicator ">"
+              " -%-"))
   (setq truncate-lines t)
   (when (featurep 'xemacs)
     ;; XEmacs needs the call to make-local-hook
@@ -339,21 +339,21 @@
   ;; Note:  This function just looks for the nearest match of the
   ;; context string and may fail if the entry moved and an identical
   ;; entry is close to the old position.  Frequent rescans make this
-  ;; safer.
+  ;; safer. 
   (let* ((file (nth 3 data))
-	 (literal (nth 2 data))
-	 (pos (nth 4 data))
-	 (re (regexp-quote literal))
-	 (match
-	  (cond
-	   ((or (not no-revisit)
-		(reftex-get-buffer-visiting file))
-	    (switch-to-buffer-other-window
-	     (reftex-get-file-buffer-force file nil))
-	    (goto-char (or pos (point-min)))
-	    (or (looking-at re)
-		(reftex-nearest-match re (length literal))))
-	   (t (message reftex-no-follow-message) nil))))
+         (literal (nth 2 data))
+         (pos (nth 4 data))
+         (re (regexp-quote literal))
+         (match
+          (cond
+           ((or (not no-revisit)
+                (reftex-get-buffer-visiting file))
+            (switch-to-buffer-other-window
+             (reftex-get-file-buffer-force file nil))
+            (goto-char (or pos (point-min)))
+            (or (looking-at re)
+                (reftex-nearest-match re (length literal))))
+           (t (message reftex-no-follow-message) nil))))
     (when match
       (goto-char (match-beginning 0))
       (recenter '(4))
@@ -361,7 +361,7 @@
     match))
 
 (defun reftex-display-index (&optional tag overriding-restriction
-				       &rest locations)
+                                       &rest locations)
   "Display a buffer with an index compiled from the current document.
 When the document has multiple indices, first prompts for the correct one.
 When index support is turned off, offer to turn it on.
@@ -381,40 +381,40 @@
 
   ;; Determine the correct index to process
   (let* ((docstruct (symbol-value reftex-docstruct-symbol))
-	 (docstruct-symbol reftex-docstruct-symbol)
-	 (index-tag (or tag (reftex-index-select-tag)))
-	 (master (reftex-TeX-master-file))
-	 (calling-file (buffer-file-name))
-	 (restriction
-	  (or overriding-restriction
-	      (and (interactive-p)
-		   (reftex-get-restriction current-prefix-arg docstruct))))
-	 (locations
-	  ;; See if we are on an index macro as initial position
-	  (or locations
-	      (let* ((what-macro (reftex-what-macro-safe 1))
-		     (macro (car what-macro))
-		     (here-I-am (when (member macro reftex-macros-with-index)
-				  (save-excursion
-				    (goto-char (+ (cdr what-macro)
-						  (length macro)))
-				    (reftex-move-over-touching-args)
-				    (reftex-where-am-I)))))
-		(if (eq (car (car here-I-am)) 'index)
-		    (list (car here-I-am))))))
-	 buffer-name)
+         (docstruct-symbol reftex-docstruct-symbol)
+         (index-tag (or tag (reftex-index-select-tag)))
+         (master (reftex-TeX-master-file))
+         (calling-file (buffer-file-name))
+         (restriction
+          (or overriding-restriction
+              (and (interactive-p) 
+                   (reftex-get-restriction current-prefix-arg docstruct))))
+         (locations
+          ;; See if we are on an index macro as initial position
+          (or locations
+              (let* ((what-macro (reftex-what-macro-safe 1))
+                     (macro (car what-macro))
+                     (here-I-am (when (member macro reftex-macros-with-index)
+                                  (save-excursion
+                                    (goto-char (+ (cdr what-macro) 
+                                                  (length macro)))
+                                    (reftex-move-over-touching-args)
+                                    (reftex-where-am-I)))))
+                (if (eq (car (car here-I-am)) 'index)
+                    (list (car here-I-am))))))
+         buffer-name)
 
     (setq buffer-name (reftex-make-index-buffer-name index-tag))
 
     ;; Goto the buffer and put it into the correct mode
-
+                      
     (when (or restriction current-prefix-arg)
-	 (reftex-kill-buffer buffer-name))
+         (reftex-kill-buffer buffer-name))
 
     (if (get-buffer-window buffer-name)
-	(select-window (get-buffer-window buffer-name))
+        (select-window (get-buffer-window buffer-name))
       (let ((default-major-mode 'reftex-index-mode))
-	(switch-to-buffer buffer-name)))
+        (switch-to-buffer buffer-name)))
 
     (or (eq major-mode 'reftex-index-mode) (reftex-index-mode))
 
@@ -425,11 +425,11 @@
     (set (make-local-variable 'reftex-index-tag) index-tag)
     (set (make-local-variable 'reftex-docstruct-symbol) docstruct-symbol)
     (if restriction
-	(setq reftex-index-restriction-indicator (car restriction)
-	      reftex-index-restriction-data (cdr restriction))
+        (setq reftex-index-restriction-indicator (car restriction)
+              reftex-index-restriction-data (cdr restriction))
       (if (interactive-p)
-	  (setq reftex-index-restriction-indicator nil
-		reftex-index-restriction-data nil)))
+          (setq reftex-index-restriction-indicator nil
+                reftex-index-restriction-data nil)))
     (when (= (buffer-size) 0)
       ;; buffer is empty - fill it
       (message "Building %s buffer..." buffer-name)
@@ -466,22 +466,22 @@
   ;; it with whatever the DOCSTRUCT contains.
   ;; REMARK can be a note to add to the entry.
   (let* ((all docstruct)
-	 (indent "   ")
-	 (context reftex-index-include-context)
-	 (context-indent (concat indent "  "))
-	 (section-chars (mapcar 'identity reftex-index-section-letters))
-	 (this-section-char 0)
-	 (font (reftex-use-fonts))
-	 (bor (car reftex-index-restriction-data))
-	 (eor (nth 1 reftex-index-restriction-data))
-	 (mouse-face
-	  (if (memq reftex-highlight-selection '(mouse both))
-	      reftex-mouse-selected-face
-	    nil))
-	 (index-face (reftex-verified-face reftex-label-face
-					   'font-lock-constant-face
-					   'font-lock-reference-face))
-	 sublist cell from to first-char)
+         (indent "   ")
+         (context reftex-index-include-context)
+         (context-indent (concat indent "  "))
+         (section-chars (mapcar 'identity reftex-index-section-letters))
+         (this-section-char 0)
+         (font (reftex-use-fonts))
+         (bor (car reftex-index-restriction-data))
+         (eor (nth 1 reftex-index-restriction-data))
+         (mouse-face
+          (if (memq reftex-highlight-selection '(mouse both))
+              reftex-mouse-selected-face
+            nil))
+         (index-face (reftex-verified-face reftex-label-face
+                                           'font-lock-constant-face
+                                           'font-lock-reference-face))
+         sublist cell from to first-char)
 
     ;; Make the sublist and sort it
     (when bor
@@ -489,68 +489,68 @@
 
     (while (setq cell (pop all))
       (if (eq cell eor)
-	  (setq all nil)
-	(and (eq (car cell) 'index)
-	     (equal (nth 1 cell) tag)
-	     (push cell sublist))))
+          (setq all nil)
+        (and (eq (car cell) 'index)
+             (equal (nth 1 cell) tag)
+             (push cell sublist))))
     (setq sublist (sort (nreverse sublist)
-			(lambda (a b) (string< (nth 8 a) (nth 8 b)))))
+                        (lambda (a b) (string< (nth 8 a) (nth 8 b)))))
 
     (when update-one
       ;; Delete the entry at place
       (and (bolp) (forward-char 1))
       (delete-region (previous-single-property-change (1+ (point)) :data)
-		     (or (next-single-property-change (point) :data)
-			 (point-max))))
+                     (or (next-single-property-change (point) :data) 
+                         (point-max))))
 
     ;; Walk through the list and insert all entries
     (while (setq cell (pop sublist))
       (unless update-one
-	(setq first-char (upcase (string-to-char (nth 6 cell))))
-	(when (and (not (equal first-char this-section-char))
-		   (member first-char section-chars))
-	  ;; There is a new initial letter, so start a new section
-	  (reftex-index-insert-new-letter first-char font)
-	  (setq section-chars (delete first-char section-chars)
-		this-section-char first-char))
-	(when (= this-section-char 0)
-	  (setq this-section-char ?!)
-	  (reftex-index-insert-new-letter this-section-char font)))
+        (setq first-char (upcase (string-to-char (nth 6 cell))))
+        (when (and (not (equal first-char this-section-char))
+                   (member first-char section-chars))
+          ;; There is a new initial letter, so start a new section
+          (reftex-index-insert-new-letter first-char font)
+          (setq section-chars (delete first-char section-chars)
+                this-section-char first-char))
+        (when (= this-section-char 0)
+          (setq this-section-char ?!)
+          (reftex-index-insert-new-letter this-section-char font)))
 
       (setq from (point))
       (insert indent (nth 7 cell))
       (when font
-	(setq to (point))
-	(put-text-property
-	 (- (point) (length (nth 7 cell))) to
-	 'face index-face)
-	(goto-char to))
+        (setq to (point))
+        (put-text-property 
+         (- (point) (length (nth 7 cell))) to
+         'face index-face)
+        (goto-char to))
 
       (when (or remark (nth 9 cell))
-	(and (< (current-column) 40)
-	     ;; FIXME: maybe this is too slow?
-	     (insert (make-string (max (- 40 (current-column)) 0) ?\ )))
-	(and (nth 9 cell) (insert "   " (substring (nth 5 cell) (nth 9 cell))))
-	(and remark (insert "     " remark)))
+        (and (< (current-column) 40)
+             ;; FIXME: maybe this is too slow?
+             (insert (make-string (max (- 40 (current-column)) 0) ?\ )))
+        (and (nth 9 cell) (insert "   " (substring (nth 5 cell) (nth 9 cell))))
+        (and remark (insert "     " remark)))
 
       (insert "\n")
       (setq to (point))
 
       (when context
-	(insert context-indent (nth 2 cell) "\n")
-	(setq to (point)))
+        (insert context-indent (nth 2 cell) "\n")
+        (setq to (point)))
       (put-text-property from to :data cell)
       (when mouse-face
-	(put-text-property from (1- to)
-			   'mouse-face mouse-face))
+        (put-text-property from (1- to)
+                           'mouse-face mouse-face))
       (goto-char to))))
 
 
 (defun reftex-index-insert-new-letter (letter &optional font)
   ;; Start a new section in the index
   (let ((from (point)))
-    (insert "\n" letter letter letter
-	    "-----------------------------------------------------------------")
+    (insert "\n" letter letter letter 
+            "-----------------------------------------------------------------")
     (when font
       (put-text-property from (point) 'face reftex-index-section-face))
     (insert "\n")))
@@ -558,30 +558,30 @@
 (defun reftex-get-restriction (arg docstruct)
   ;; Interprete the prefix ARG and derive index restriction specs.
   (let* ((beg (min (point) (or (condition-case nil (mark) (error nil))
-			       (point-max))))
-	 (end (max (point) (or (condition-case nil (mark) (error nil))
-			       (point-min))))
-	 bor eor label here-I-am)
+                               (point-max))))
+         (end (max (point) (or (condition-case nil (mark) (error nil))
+                               (point-min))))
+         bor eor label here-I-am)
     (cond
      ((eq arg 2)
       (setq here-I-am (car (reftex-where-am-I))
-	    bor (if (eq (car here-I-am) 'toc)
-		    here-I-am
-		  (reftex-last-assoc-before-elt
-		   'toc here-I-am docstruct))
-	    eor (car (memq (assq 'toc (cdr (memq bor docstruct))) docstruct))
-	    label (nth 6 bor)))
+            bor (if (eq (car here-I-am) 'toc)
+                    here-I-am
+                  (reftex-last-assoc-before-elt
+                   'toc here-I-am docstruct))
+            eor (car (memq (assq 'toc (cdr (memq bor docstruct))) docstruct))
+            label (nth 6 bor)))
      ((eq arg 3)
       (save-excursion
-	(setq label "region")
-	(goto-char beg)
-	(setq bor (car (reftex-where-am-I)))
-	(setq bor (nth 1 (memq bor docstruct)))
-	(goto-char end)
-	(setq eor (nth 1 (memq (car (reftex-where-am-I)) docstruct)))))
+        (setq label "region")
+        (goto-char beg)
+        (setq bor (car (reftex-where-am-I)))
+        (setq bor (nth 1 (memq bor docstruct)))
+        (goto-char end)
+        (setq eor (nth 1 (memq (car (reftex-where-am-I)) docstruct)))))
      (t nil))
     (if (and label (or bor eor))
-	(list label bor eor)
+        (list label bor eor)
       nil)))
 
 (defun reftex-index-pre-command-hook ()
@@ -593,23 +593,23 @@
   ;; Used in the post-command-hook for the *Index* buffer
   (when (get-text-property (point) :data)
     (and (> (point) 1)
-	 (not (get-text-property (point) 'intangible))
-	 (memq reftex-highlight-selection '(cursor both))
-	 (reftex-highlight 1
-	   (or (previous-single-property-change (1+ (point)) :data)
-	       (point-min))
-	   (or (next-single-property-change (point) :data)
-	       (point-max)))))
+         (not (get-text-property (point) 'intangible))
+         (memq reftex-highlight-selection '(cursor both))
+         (reftex-highlight 1
+           (or (previous-single-property-change (1+ (point)) :data)
+               (point-min))
+           (or (next-single-property-change (point) :data)
+               (point-max)))))
   (if (integerp reftex-index-follow-mode)
       ;; Remove delayed action
       (setq reftex-index-follow-mode t)
     (and reftex-index-follow-mode
-	 (not (equal reftex-last-follow-point (point)))
-	 ;; Show context in other window
-	 (setq reftex-last-follow-point (point))
-	 (condition-case nil
-	     (reftex-index-visit-location nil (not reftex-revisit-to-follow))
-	   (error t)))))
+         (not (equal reftex-last-follow-point (point)))
+         ;; Show context in other window
+         (setq reftex-last-follow-point (point))
+         (condition-case nil
+             (reftex-index-visit-location nil (not reftex-revisit-to-follow))
+           (error t)))))
 
 (defun reftex-index-show-help ()
   "Show a summary of special key bindings."
@@ -626,20 +626,20 @@
   (interactive "p")
   (setq reftex-callback-fwd t)
   (or (eobp) (forward-char 1))
-  (goto-char (or (next-single-property-change (point) :data)
-		 (point)))
+  (goto-char (or (next-single-property-change (point) :data) 
+                 (point)))
   (unless (get-text-property (point) :data)
-    (goto-char (or (next-single-property-change (point) :data)
-		   (point)))))
+    (goto-char (or (next-single-property-change (point) :data) 
+                   (point)))))
 (defun reftex-index-previous (&optional arg)
   "Move to previous selectable item."
   (interactive "p")
   (setq reftex-callback-fwd nil)
   (goto-char (or (previous-single-property-change (point) :data)
-		 (point)))
+                 (point)))
   (unless (get-text-property (point) :data)
     (goto-char (or (previous-single-property-change (point) :data)
-		   (point)))))
+                   (point)))))
 (defun reftex-index-toggle-follow ()
   "Toggle follow (other window follows with context)."
   (interactive)
@@ -695,22 +695,22 @@
   (interactive)
   (let ((index-tag reftex-index-tag))
     (if (and reftex-enable-partial-scans
-	     (null current-prefix-arg))
-	(let* ((data (get-text-property (point) :data))
-	       (file (nth 3 data))
-	       (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
-	  (if (not file)
-	      (error "Don't know which file to rescan.  Try `C-u r'")
-	    (switch-to-buffer (reftex-get-file-buffer-force file))
-	    (setq current-prefix-arg '(4))
-	    (reftex-display-index index-tag nil line)))
+             (null current-prefix-arg))
+        (let* ((data (get-text-property (point) :data))
+               (file (nth 3 data))
+               (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
+          (if (not file)
+              (error "Don't know which file to rescan.  Try `C-u r'")
+            (switch-to-buffer (reftex-get-file-buffer-force file))
+            (setq current-prefix-arg '(4))
+            (reftex-display-index index-tag nil line)))
       (reftex-index-Rescan))
     (reftex-kill-temporary-buffers)))
 (defun reftex-index-Rescan (&rest ignore)
   "Regenerate the *Index* buffer after reparsing the entire document."
   (interactive)
   (let ((index-tag reftex-index-tag)
-	(line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
+        (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
     (switch-to-buffer
      (reftex-get-file-buffer-force reftex-last-index-file))
     (setq current-prefix-arg '(16))
@@ -719,14 +719,14 @@
   "Regenerate the *Index* from the internal lists.  No reparsing os done."
   (interactive)
   (let ((buf (current-buffer))
-	(index-tag reftex-index-tag)
-	(data (get-text-property (point) :data))
-	(line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
+        (index-tag reftex-index-tag)
+        (data (get-text-property (point) :data))
+        (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
     (switch-to-buffer
      (reftex-get-file-buffer-force reftex-last-index-file))
     (reftex-erase-buffer buf)
     (setq current-prefix-arg nil
-	  reftex-last-follow-point 1)
+          reftex-last-follow-point 1)
     (reftex-display-index index-tag nil data line)))
 (defun reftex-index-switch-index-tag (&rest ignore)
   "Switch to a different index of the same document."
@@ -741,23 +741,23 @@
   ;; Optional FORCE means, even if point is not on an index entry.
   (interactive)
   (let* ((data (get-text-property (point) :data))
-	 (docstruct (symbol-value reftex-docstruct-symbol))
-	 bor eor)
+         (docstruct (symbol-value reftex-docstruct-symbol))
+         bor eor)
     (if (and (not data) force)
-	(setq data (assq 'toc docstruct)))
+        (setq data (assq 'toc docstruct)))
     (when data
       (setq bor (reftex-last-assoc-before-elt 'toc data docstruct)
-	    eor (car (memq (assq 'toc (cdr (memq bor docstruct)))
-			   docstruct))
-	    reftex-index-restriction-data (list bor eor)
-	    reftex-index-restriction-indicator (nth 6 bor) )))
+            eor (car (memq (assq 'toc (cdr (memq bor docstruct)))
+                           docstruct))
+            reftex-index-restriction-data (list bor eor)
+            reftex-index-restriction-indicator (nth 6 bor) )))
   (reftex-index-revert))
 
 (defun reftex-index-widen (&rest ignore)
   "Show the unrestricted index (all entries)."
   (interactive)
   (setq reftex-index-restriction-indicator nil
-	reftex-index-restriction-data nil)
+        reftex-index-restriction-data nil)
   (reftex-index-revert)
   (message "Index widened"))
 (defun reftex-index-restriction-forward (&rest ignore)
@@ -766,15 +766,15 @@
 When index is restricted, select the next section as restriction criterion."
   (interactive)
   (let* ((docstruct (symbol-value reftex-docstruct-symbol))
-	 (bor (nth 1 reftex-index-restriction-data)))
+         (bor (nth 1 reftex-index-restriction-data)))
     (if (or (not bor)
-	    (not (eq (car bor) 'toc)))
-	(reftex-index-restrict-to-section t)
+            (not (eq (car bor) 'toc)))
+        (reftex-index-restrict-to-section t)
       (setq reftex-index-restriction-indicator (nth 6 bor)
-	    reftex-index-restriction-data
-	    (list bor
-		  (car (memq (assq 'toc (cdr (memq bor docstruct)))
-			     docstruct))))
+            reftex-index-restriction-data
+            (list bor 
+                  (car (memq (assq 'toc (cdr (memq bor docstruct)))
+                             docstruct))))
       (reftex-index-revert))))
 (defun reftex-index-restriction-backward (&rest ignore)
   "Restrict to next section.
@@ -782,14 +782,14 @@
 When index is restricted, select the previous section as restriction criterion."
   (interactive)
   (let* ((docstruct (symbol-value reftex-docstruct-symbol))
-	 (eor (car reftex-index-restriction-data))
-	 (bor (reftex-last-assoc-before-elt 'toc eor docstruct t)))
+         (eor (car reftex-index-restriction-data))
+         (bor (reftex-last-assoc-before-elt 'toc eor docstruct t)))
     (if (or (not bor)
-	    (not (eq (car bor) 'toc)))
-	(reftex-index-restrict-to-section t)
+            (not (eq (car bor) 'toc)))
+        (reftex-index-restrict-to-section t)
       (setq reftex-index-restriction-indicator (nth 6 bor)
-	    reftex-index-restriction-data
-	    (list bor eor))
+            reftex-index-restriction-data
+            (list bor eor))
       (reftex-index-revert))))
 
 (defun reftex-index-visit-location (&optional final no-revisit)
@@ -804,9 +804,9 @@
          show-window show-buffer match)
 
     (unless data (error "Don't know which index entry to visit"))
-
+    
     (if (eq (car data) 'index)
-	(setq match (reftex-index-show-entry data no-revisit)))
+        (setq match (reftex-index-show-entry data no-revisit)))
 
     (setq show-window (selected-window)
           show-buffer (current-buffer))
@@ -833,32 +833,32 @@
   ;; values are accessible individually.
   (interactive)
   (let* ((arg (nth 5 data))
-	 (context (nth 2 data))
-	 (sc reftex-index-special-chars)
-	 (boa (if (string-match (regexp-quote (concat "{" arg "}")) context)
-		  (1+ (match-beginning 0))
-		(error "Something is wrong here")))
-	 (eoa (1- (match-end 0)))
-	 (boactual (if (string-match (concat "[^" (nth 3 sc) "]" (nth 2 sc))
-				     context boa)
-		       (1+ (match-beginning 0))
-		     eoa))
-	 (boattr (if (string-match (concat "[^" (nth 3 sc) "]" (nth 1 sc))
-				   context boa)
-		     (1+ (match-beginning 0))
-		   boactual))
-	 (pre (substring context 0 boa))
-	 (key (substring context boa boattr))
-	 (attr (substring context boattr boactual))
-	 (actual (substring context boactual eoa))
-	 (post (substring context eoa)))
+         (context (nth 2 data))
+         (sc reftex-index-special-chars)
+         (boa (if (string-match (regexp-quote (concat "{" arg "}")) context)
+                  (1+ (match-beginning 0))
+                (error "Something is wrong here")))
+         (eoa (1- (match-end 0)))
+         (boactual (if (string-match (concat "[^" (nth 3 sc) "]" (nth 2 sc))
+                                     context boa)
+                       (1+ (match-beginning 0))
+                     eoa))
+         (boattr (if (string-match (concat "[^" (nth 3 sc) "]" (nth 1 sc))
+                                   context boa)
+                     (1+ (match-beginning 0))
+                   boactual))
+         (pre (substring context 0 boa))
+         (key (substring context boa boattr))
+         (attr (substring context boattr boactual))
+         (actual (substring context boactual eoa))
+         (post (substring context eoa)))
     (list pre key attr actual post)))
 
 (defun reftex-index-edit ()
   "Edit the index entry at point."
   (interactive)
   (let* ((data (get-text-property (point) :data))
-	 old new)
+         old new)
     (unless data (error "Don't know which index entry to edit"))
     (reftex-index-view-entry)
     (setq old (nth 2 data) new (read-string "Edit: " old))
@@ -868,33 +868,33 @@
   "Toggle the page range start attribute `|('."
   (interactive)
   (let* ((data (get-text-property (point) :data))
-	 (bor (concat (nth 1 reftex-index-special-chars) "("))
-	 new analyze attr)
+         (bor (concat (nth 1 reftex-index-special-chars) "("))
+         new analyze attr)
     (unless data (error "Don't know which index entry to edit"))
     (setq analyze (reftex-index-analyze-entry data)
-	  attr (nth 2 analyze))
+          attr (nth 2 analyze))
     (setf (nth 2 analyze) (if (string= attr bor) "" bor))
     (setq new (apply 'concat analyze))
-    (reftex-index-change-entry
+    (reftex-index-change-entry 
      new (if (string= (nth 2 analyze) bor)
-	     "Entry is now START-OF-PAGE-RANGE"
-	   "START-OF-PAGE-RANGE canceled"))))
+             "Entry is now START-OF-PAGE-RANGE"
+           "START-OF-PAGE-RANGE canceled"))))
 
 (defun reftex-index-toggle-range-end ()
   "Toggle the page-range-end attribute `|)'."
   (interactive)
   (let* ((data (get-text-property (point) :data))
-	 (eor (concat (nth 1 reftex-index-special-chars) ")"))
-	 new analyze attr)
+         (eor (concat (nth 1 reftex-index-special-chars) ")"))
+         new analyze attr)
     (unless data (error "Don't know which index entry to edit"))
     (setq analyze (reftex-index-analyze-entry data)
-	  attr (nth 2 analyze))
+          attr (nth 2 analyze))
     (setf (nth 2 analyze) (if (string= attr eor) "" eor))
     (setq new (apply 'concat analyze))
     (reftex-index-change-entry
      new (if (string= (nth 2 analyze) eor)
-	     "Entry is now END-OF-PAGE-RANGE"
-	   "END-OF-PAGE-RANGE canceled"))))
+             "Entry is now END-OF-PAGE-RANGE"
+           "END-OF-PAGE-RANGE canceled"))))
 
 (defun reftex-index-edit-key ()
   "Edit the KEY part of the index entry."
@@ -905,7 +905,7 @@
   "EDIT the ATTRIBUTE part of the entry.  With arg: remove entire ATTRIBUTE."
   (interactive "P")
   (reftex-index-edit-part arg 2 (nth 1 reftex-index-special-chars)
-			  "Attribute: "))
+                          "Attribute: "))
 
 (defun reftex-index-edit-visual (&optional arg)
   "EDIT the VISUAL part of the entry.  With arg: remove entire VISUAL string."
@@ -915,51 +915,51 @@
 (defun reftex-index-edit-part (arg n initial prompt &optional dont-allow-empty)
   ;; This function does the work for all partial editing commands
   (let* ((data (get-text-property (point) :data))
-	 new analyze opart npart)
+         new analyze opart npart)
     (unless data (error "Don't know which index entry to edit"))
     ;; Analyze the whole context string
     (setq analyze (reftex-index-analyze-entry data)
-	  opart (nth n analyze))
+          opart (nth n analyze))
     (and (> (length opart) 0) (setq opart (substring opart 1)))
     ;; Have the user editing the part
     (setq npart (if arg "" (read-string (concat prompt initial) opart)))
     ;; Tests:
     (cond ((string= npart opart)
-	   (error "Not changed"))
-	  ((string= npart "")
-	   (if dont-allow-empty
-	       (error "Illegal value")
-	     (setf (nth n analyze) npart)))
-	  (t (setf (nth n analyze) (concat initial npart))))
+           (error "Not changed"))
+          ((string= npart "")
+           (if dont-allow-empty
+               (error "Illegal value")
+             (setf (nth n analyze) npart)))
+          (t (setf (nth n analyze) (concat initial npart))))
     (setq new (apply 'concat analyze))
     ;; Change the entry and insert the changed version into the index.
-    (reftex-index-change-entry
+    (reftex-index-change-entry 
      new (if (string= npart "")
-	     (format "Deleted: %s" opart)
-	   (format "New value is: %s" npart)))))
+             (format "Deleted: %s" opart)
+           (format "New value is: %s" npart)))))
 
 (defun reftex-index-level-down ()
   "Make index entry a subitem of another entry."
   (interactive)
   (let* ((data (get-text-property (point) :data))
-	 (docstruct (symbol-value reftex-docstruct-symbol))
-	 old new prefix key)
+         (docstruct (symbol-value reftex-docstruct-symbol))
+         old new prefix key)
     (unless data (error "Don't know which index entry to change"))
     (setq old (nth 2 data)
-	  key (nth 6 data)
-	  prefix (completing-read
-		  "Prefix: "
-		  (reftex-sublist-nth
-		   docstruct 6
-		   (lambda (x)
-		     (and (eq (car x) 'index)
-			  (string= (nth 1 x) reftex-index-tag))) t)))
-    (unless (string-match
-	     (concat (regexp-quote (car reftex-index-special-chars)) "\\'")
-	     prefix)
+          key (nth 6 data)
+          prefix (completing-read 
+                  "Prefix: " 
+                  (reftex-sublist-nth 
+                   docstruct 6
+                   (lambda (x)
+                     (and (eq (car x) 'index)
+                          (string= (nth 1 x) reftex-index-tag))) t)))
+    (unless (string-match 
+             (concat (regexp-quote (car reftex-index-special-chars)) "\\'")
+             prefix)
       (setq prefix (concat prefix (car reftex-index-special-chars))))
     (if (string-match (regexp-quote key) old)
-	(setq new (replace-match (concat prefix key) t t old))
+        (setq new (replace-match (concat prefix key) t t old))
       (error "Cannot construct new index key"))
     (reftex-index-change-entry new (format "Added prefix: %s" prefix))))
 
@@ -967,17 +967,17 @@
   "Remove the highest level of a hierarchical index entry."
   (interactive)
   (let* ((data (get-text-property (point) :data))
-	 old new prefix)
+         old new prefix)
     (unless data (error "Don't know which entry to change"))
     (setq old (nth 2 data))
     (if (string-match (concat "{\\([^" (nth 0 reftex-index-special-chars) "]*"
-			      "[^" (nth 3 reftex-index-special-chars) "]"
-			      (regexp-quote (nth 0 reftex-index-special-chars))
-			      "\\)")
-		      old)
-	(setq prefix (substring old (match-beginning 1) (match-end 1))
-	      new (concat (substring old 0 (match-beginning 1))
-			  (substring old (match-end 1))))
+                              "[^" (nth 3 reftex-index-special-chars) "]"
+                              (regexp-quote (nth 0 reftex-index-special-chars))
+                              "\\)")
+                      old)
+        (setq prefix (substring old (match-beginning 1) (match-end 1))
+              new (concat (substring old 0 (match-beginning 1))
+                          (substring old (match-end 1))))
       (error "Entry is not a subitem"))
     (reftex-index-change-entry new (format "Removed prefix: %s" prefix))))
 
@@ -994,9 +994,9 @@
 (defun reftex-index-change-entry (new &optional message)
   ;; Change the full context string of the index entry at point to
   ;; NEW.  This actually edits the buffer where the entry is defined.
-
+  
   (let* ((data (get-text-property (point) :data))
-	 old beg end info)
+         old beg end info)
     (unless data (error "Cannot change entry"))
     (reftex-index-view-entry)
     (setq beg (match-beginning 0) end (match-end 0))
@@ -1006,19 +1006,19 @@
       (set-buffer (get-file-buffer (nth 3 data)))
       (goto-char beg)
       (unless (looking-at (regexp-quote old))
-	(error "This should not happen (reftex-index-change-entry)"))
+        (error "This should not happen (reftex-index-change-entry)"))
       (delete-region beg end)
       (insert new)
       (goto-char (1- beg))
       (when (and (re-search-forward (reftex-everything-regexp) nil t)
-		 (match-end 10)
-		 (< (abs (- (match-beginning 10) beg)) (length new))
-		 (setq info (reftex-index-info-safe buffer-file-name)))
-	(setcdr data (cdr info))))
+                 (match-end 10)
+                 (< (abs (- (match-beginning 10) beg)) (length new))
+                 (setq info (reftex-index-info-safe buffer-file-name)))
+        (setcdr data (cdr info))))
     (let ((buffer-read-only nil))
       (save-excursion
-	(reftex-insert-index (list data) reftex-index-tag t
-			     "EDITED")))
+        (reftex-insert-index (list data) reftex-index-tag t
+                             "EDITED")))
     (setq reftex-last-follow-point 1)
     (and message (message message))))
 
@@ -1033,33 +1033,33 @@
 
 (loop for x in
       '(("n"    . reftex-index-next)
-	("p"    . reftex-index-previous)
-	("?"    . reftex-index-show-help)
-	(" "    . reftex-index-view-entry)
-	("\C-m" . reftex-index-goto-entry-and-hide)
-	("\C-i" . reftex-index-goto-entry)
-	("\C-k" . reftex-index-kill)
-	("r"    . reftex-index-rescan)
-	("R"    . reftex-index-Rescan)
-	("g"    . revert-buffer)
-	("q"    . reftex-index-quit)
-	("k"    . reftex-index-quit-and-kill)
-	("f"    . reftex-index-toggle-follow)
-	("s"    . reftex-index-switch-index-tag)
-	("e"    . reftex-index-edit)
-	("^"    . reftex-index-level-up)
-	("_"    . reftex-index-level-down)
-	("}"    . reftex-index-restrict-to-section)
-	("{"    . reftex-index-widen)
-	(">"    . reftex-index-restriction-forward)
-	("<"    . reftex-index-restriction-backward)
-	("("    . reftex-index-toggle-range-beginning)
-	(")"    . reftex-index-toggle-range-end)
-	("|"    . reftex-index-edit-attribute)
-	("@"    . reftex-index-edit-visual)
-	("*"    . reftex-index-edit-key)
-	("\C-c=". reftex-index-goto-toc)
-	("c"    . reftex-index-toggle-context))
+        ("p"    . reftex-index-previous)
+        ("?"    . reftex-index-show-help)
+        (" "    . reftex-index-view-entry)
+        ("\C-m" . reftex-index-goto-entry-and-hide)
+        ("\C-i" . reftex-index-goto-entry)
+        ("\C-k" . reftex-index-kill)
+        ("r"    . reftex-index-rescan)
+        ("R"    . reftex-index-Rescan)
+        ("g"    . revert-buffer)
+        ("q"    . reftex-index-quit)
+        ("k"    . reftex-index-quit-and-kill)
+        ("f"    . reftex-index-toggle-follow)
+        ("s"    . reftex-index-switch-index-tag)
+        ("e"    . reftex-index-edit)
+        ("^"    . reftex-index-level-up)
+        ("_"    . reftex-index-level-down)
+        ("}"    . reftex-index-restrict-to-section)
+        ("{"    . reftex-index-widen)
+        (">"    . reftex-index-restriction-forward)
+        ("<"    . reftex-index-restriction-backward)
+        ("("    . reftex-index-toggle-range-beginning)
+        (")"    . reftex-index-toggle-range-end)
+        ("|"    . reftex-index-edit-attribute)
+        ("@"    . reftex-index-edit-visual)
+        ("*"    . reftex-index-edit-key)
+        ("\C-c=". reftex-index-goto-toc)
+        ("c"    . reftex-index-toggle-context))
       do (define-key reftex-index-map (car x) (cdr x)))
 
 (loop for key across "0123456789" do
@@ -1069,33 +1069,33 @@
 ;; The capital letters and the exclamation mark
 (loop for key across (concat "!" reftex-index-section-letters) do
       (define-key reftex-index-map (vector (list key))
-	(list 'lambda '() '(interactive)
-	      (list 'reftex-index-goto-letter key))))
+        (list 'lambda '() '(interactive)
+              (list 'reftex-index-goto-letter key))))
 
 (defun reftex-index-goto-letter (char)
   "Go to the CHAR section in the index."
   (let ((pos (point))
-	(case-fold-search nil))
+        (case-fold-search nil))
     (goto-line 3)
     (if (re-search-forward (concat "^" (char-to-string char)) nil t)
-	(progn
-	  (beginning-of-line)
-	  (recenter 0)
-	  (reftex-index-next))
+        (progn
+          (beginning-of-line)
+          (recenter 0)
+          (reftex-index-next))
       (goto-char pos)
       (if (eq char ?!)
-	  (error "This <%s> index does not contain entries sorted before the letters"
-		 reftex-index-tag)
-	(error "This <%s> index does not contain entries starting with `%c'"
-	       reftex-index-tag char)))))
+          (error "This <%s> index does not contain entries sorted before the letters"
+                 reftex-index-tag)
+        (error "This <%s> index does not contain entries starting with `%c'" 
+               reftex-index-tag char)))))
 
-(easy-menu-define
+(easy-menu-define 
  reftex-index-menu reftex-index-map
  "Menu for Index buffer"
  `("Index"
-   ["Goto section A-Z"
+   ["Goto section A-Z" 
     (message "To go to a section, just press any of: !%s"
-	     reftex-index-section-letters) t]
+             reftex-index-section-letters) t]
    ["Show Entry" reftex-index-view-entry t]
    ["Go To Entry" reftex-index-goto-entry t]
    ["Exit & Go To Entry" reftex-index-goto-entry-and-hide t]
@@ -1133,7 +1133,7 @@
     ["Context" reftex-index-toggle-context :style toggle
      :selected reftex-index-include-context]
     "--"
-    ["Follow Mode" reftex-index-toggle-follow :style toggle
+    ["Follow Mode" reftex-index-toggle-follow :style toggle 
      :selected reftex-index-follow-mode])
    "--"
    ["Help" reftex-index-show-help t]))
@@ -1185,79 +1185,79 @@
   (set-marker reftex-index-return-marker (point))
   (reftex-index-selection-or-word arg 'phrase)
   (if (eq major-mode 'reftex-index-phrases-mode)
-      (message
+      (message 
        (substitute-command-keys
-	"Return to LaTeX with \\[reftex-index-phrases-save-and-return]"))))
+        "Return to LaTeX with \\[reftex-index-phrases-save-and-return]"))))
 
 (defun reftex-index-visit-phrases-buffer ()
   "Switch to the phrases buffer, initialize if empty."
   (interactive)
   (reftex-access-scan-info)
   (let* ((master (reftex-TeX-master-file))
-	 (name (concat (file-name-sans-extension master)
-		       reftex-index-phrase-file-extension)))
+         (name (concat (file-name-sans-extension master)
+                       reftex-index-phrase-file-extension)))
     (find-file name)
     (unless (eq major-mode 'reftex-index-phrases-mode)
       (reftex-index-phrases-mode))
     (if (= (buffer-size) 0)
-	(reftex-index-initialize-phrases-buffer master))))
+        (reftex-index-initialize-phrases-buffer master))))
 
 (defun reftex-index-initialize-phrases-buffer (&optional master)
   "Initialize the phrases buffer by creating the header.
 If the buffer is non-empty, delete the old header first."
   (interactive)
   (let* ((case-fold-search t)
-	 (default-key (car reftex-index-default-macro))
-	 (default-macro (nth 1 (assoc default-key
-				      reftex-key-to-index-macro-alist)))
-	 (macro-alist
-	  (sort (copy-sequence reftex-index-macro-alist)
-		(lambda (a b) (equal (car a) default-macro))))
-	 macro entry key repeat)
-
+         (default-key (car reftex-index-default-macro))
+         (default-macro (nth 1 (assoc default-key
+                                      reftex-key-to-index-macro-alist)))
+         (macro-alist
+          (sort (copy-sequence reftex-index-macro-alist)
+                (lambda (a b) (equal (car a) default-macro))))
+         macro entry key repeat)
+    
     (if master (set (make-local-variable 'TeX-master)
-		    (file-name-nondirectory master)))
+                    (file-name-nondirectory master)))
 
     (when (> (buffer-size) 0)
       (goto-char 1)
       (set-mark (point))
       (while (re-search-forward reftex-index-phrases-macrodef-regexp nil t)
-	(end-of-line))
+        (end-of-line))
       (beginning-of-line 2)
       (if (looking-at reftex-index-phrases-comment-regexp)
-	  (beginning-of-line 2))
+          (beginning-of-line 2))
       (while (looking-at "^[ \t]*$")
-	  (beginning-of-line 2))
+          (beginning-of-line 2))          
       (cond ((fboundp 'zmacs-activate-region) (zmacs-activate-region))
-	    ((boundp 'make-active) (setq mark-active t)))
+            ((boundp 'make-active) (setq mark-active t)))
       (if (yes-or-no-p "Delete and rebuilt header ")
-	  (delete-region (point-min) (point))))
+          (delete-region (point-min) (point))))
 
     ;; Insert the mode line
     (insert
      (format "%% -*- mode: reftex-index-phrases; TeX-master: \"%s\" -*-\n"
-	     (file-name-nondirectory (reftex-index-phrase-tex-master))))
+             (file-name-nondirectory (reftex-index-phrase-tex-master))))
     ;; Insert the macro definitions
     (insert "%                              Key      Macro Format            Repeat\n")
     (insert "%---------------------------------------------------------------------\n")
     (while (setq entry (pop macro-alist))
       (setq macro (car entry)
-	    repeat (nth 7 entry)
-	    key (car (delq nil (mapcar (lambda (x) (if (equal (nth 1 x) macro)
-						       (car x)
-						     nil))
-				       reftex-key-to-index-macro-alist))))
+            repeat (nth 7 entry)
+            key (car (delq nil (mapcar (lambda (x) (if (equal (nth 1 x) macro)
+                                                       (car x)
+                                                     nil))
+                                       reftex-key-to-index-macro-alist))))
       (insert (format ">>>INDEX_MACRO_DEFINITION:\t%s\t%-20s\t%s\n"
-		      (char-to-string key) (concat macro "{%s}")
-		      (if repeat "t" "nil"))))
+                      (char-to-string key) (concat macro "{%s}")
+                      (if repeat "t" "nil"))))
     (insert "%---------------------------------------------------------------------\n\n\n")))
 
 (defvar TeX-master)
 (defun reftex-index-phrase-tex-master (&optional dir)
   "Return the name of the master file associated with a phrase buffer."
   (if (and (boundp 'TeX-master)
-	   (local-variable-p 'TeX-master (current-buffer))
-	   (stringp TeX-master))
+           (local-variable-p 'TeX-master (current-buffer))
+           (stringp TeX-master))
       ;; We have a local variable which tells us which file to use
       (expand-file-name TeX-master dir)
     ;; have to guess
@@ -1301,9 +1301,9 @@
   (interactive)
   (kill-all-local-variables)
   (setq major-mode 'reftex-index-phrases-mode
-	mode-name "Phrases")
+        mode-name "Phrases")
   (use-local-map reftex-index-phrases-map)
-  (set (make-local-variable 'font-lock-defaults)
+  (set (make-local-variable 'font-lock-defaults) 
        reftex-index-phrases-font-lock-defaults)
   (easy-menu-add reftex-index-phrases-menu reftex-index-phrases-map)
   (set (make-local-variable 'reftex-index-phrases-marker) (make-marker))
@@ -1313,31 +1313,31 @@
 ;; Font Locking stuff
 (let ((ss (if (featurep 'xemacs) 'secondary-selection ''secondary-selection)))
   (setq reftex-index-phrases-font-lock-keywords
-	(list
-	 (cons reftex-index-phrases-comment-regexp 'font-lock-comment-face)
-	 (list reftex-index-phrases-macrodef-regexp
-	       '(1 font-lock-type-face)
-	       '(2 font-lock-keyword-face)
-	       (list 3 ss)
-	       '(4 font-lock-function-name-face)
-	       (list 5 ss)
-	       '(6 font-lock-string-face))
-	 (list reftex-index-phrases-phrase-regexp1
-	       '(1 font-lock-keyword-face)
-	       (list 2 ss)
-	       '(3 font-lock-string-face)
-	       (list 4 ss))
-	 (list reftex-index-phrases-phrase-regexp2
-	       '(1 font-lock-keyword-face)
-	       (list 2 ss)
-	       '(3 font-lock-string-face)
-	       (list 4 ss)
-	       '(5 font-lock-function-name-face))
-	 (cons "^\t$" ss)))
+        (list 
+         (cons reftex-index-phrases-comment-regexp 'font-lock-comment-face)
+         (list reftex-index-phrases-macrodef-regexp
+               '(1 font-lock-type-face)
+               '(2 font-lock-keyword-face)
+               (list 3 ss)
+               '(4 font-lock-function-name-face)
+               (list 5 ss)
+               '(6 font-lock-string-face))
+         (list reftex-index-phrases-phrase-regexp1
+               '(1 font-lock-keyword-face)
+               (list 2 ss)
+               '(3 font-lock-string-face)
+               (list 4 ss))
+         (list reftex-index-phrases-phrase-regexp2
+               '(1 font-lock-keyword-face)
+               (list 2 ss)
+               '(3 font-lock-string-face)
+               (list 4 ss)
+               '(5 font-lock-function-name-face))
+         (cons "^\t$" ss)))
   (setq reftex-index-phrases-font-lock-defaults
-	'((reftex-index-phrases-font-lock-keywords)
-	  nil t nil beginning-of-line))
-  (put 'reftex-index-phrases-mode 'font-lock-defaults
+        '((reftex-index-phrases-font-lock-keywords)
+          nil t nil beginning-of-line))
+  (put 'reftex-index-phrases-mode 'font-lock-defaults 
        reftex-index-phrases-font-lock-defaults) ; XEmacs
   )
 
@@ -1350,9 +1350,9 @@
     (decf arg)
     (end-of-line)
     (if (re-search-forward reftex-index-phrases-phrase-regexp12 nil t)
-	(progn
-	  (goto-char (match-beginning 0))
-	  (reftex-index-this-phrase))
+        (progn
+          (goto-char (match-beginning 0))
+          (reftex-index-this-phrase))
       (error "No more phrase lines after point"))))
 
 (defun reftex-index-this-phrase ()
@@ -1364,48 +1364,48 @@
   (save-excursion
     (beginning-of-line)
     (cond ((looking-at reftex-index-phrases-comment-regexp)
-	   (if (interactive-p) (error "Comment line")))
-	  ((looking-at "^[ \t]*$")
-	   (if (interactive-p) (error "Empty line")))
-	  ((looking-at reftex-index-phrases-macrodef-regexp)
-	   (if (interactive-p) (error "Macro definition line")))
-	  ((looking-at reftex-index-phrases-phrase-regexp12)
-	   ;; This is a phrase
-	   (let* ((char (if (not (equal (match-string 1) ""))
-			    (string-to-char (match-string 1))))
-		  (phrase (match-string 3))
-		  (index-key (match-string 6))
-		  (macro-data (cdr (if (null char)
-				       (car reftex-index-phrases-macro-data)
-				     (assoc char reftex-index-phrases-macro-data))))
-		  (macro-fmt (car macro-data))
-		  (repeat (nth 1 macro-data))
-		  (files
-		   (cond ((and (stringp reftex-index-phrases-restrict-file)
-			       (file-regular-p reftex-index-phrases-restrict-file))
-			  (list reftex-index-phrases-restrict-file))
-			 ((stringp reftex-index-phrases-restrict-file)
-			  (error "Illegal restriction file %s"
-				 reftex-index-phrases-restrict-file))
-			 (t reftex-index-phrases-files)))
-		  (as-words reftex-index-phrases-search-whole-words))
-	     (unless macro-data
-	       (error "No macro associated with key %c" char))
-	     (unwind-protect
-		 (let ((overlay-arrow-string "=>")
-		       (overlay-arrow-position
-			reftex-index-phrases-marker)
-		       (replace-count 0))
-		   ;; Show the overlay arrow
-		   (move-marker reftex-index-phrases-marker
-				(match-beginning 0) (current-buffer))
-		   ;; Start the query-replace
-		   (reftex-query-index-phrase-globally
-		    files phrase macro-fmt
-		    index-key repeat as-words)
-		   (message "%s replaced"
-			    (reftex-number replace-count "occurrence"))))))
-	  (t (error "Cannot parse this line")))))
+           (if (interactive-p) (error "Comment line")))
+          ((looking-at "^[ \t]*$")
+           (if (interactive-p) (error "Empty line")))
+          ((looking-at reftex-index-phrases-macrodef-regexp)
+           (if (interactive-p) (error "Macro definition line")))
+          ((looking-at reftex-index-phrases-phrase-regexp12)
+           ;; This is a phrase
+           (let* ((char (if (not (equal (match-string 1) ""))
+                            (string-to-char (match-string 1))))
+                  (phrase (match-string 3))
+                  (index-key (match-string 6))
+                  (macro-data (cdr (if (null char)
+                                       (car reftex-index-phrases-macro-data)
+                                     (assoc char reftex-index-phrases-macro-data))))
+                  (macro-fmt (car macro-data))
+                  (repeat (nth 1 macro-data))
+                  (files
+                   (cond ((and (stringp reftex-index-phrases-restrict-file)
+                               (file-regular-p reftex-index-phrases-restrict-file))
+                          (list reftex-index-phrases-restrict-file))
+                         ((stringp reftex-index-phrases-restrict-file)
+                          (error "Illegal restriction file %s"
+                                 reftex-index-phrases-restrict-file))
+                         (t reftex-index-phrases-files)))
+                  (as-words reftex-index-phrases-search-whole-words))
+             (unless macro-data
+               (error "No macro associated with key %c" char))
+             (unwind-protect
+                 (let ((overlay-arrow-string "=>")
+                       (overlay-arrow-position
+                        reftex-index-phrases-marker)
+                       (replace-count 0))
+                   ;; Show the overlay arrow
+                   (move-marker reftex-index-phrases-marker
+                                (match-beginning 0) (current-buffer))
+                   ;; Start the query-replace
+                   (reftex-query-index-phrase-globally 
+                    files phrase macro-fmt 
+                    index-key repeat as-words)
+                   (message "%s replaced" 
+                            (reftex-number replace-count "occurrence"))))))
+          (t (error "Cannot parse this line")))))
 
 (defun reftex-index-all-phrases ()
   "Index all phrases in the phrases buffer.
@@ -1428,7 +1428,7 @@
   (reftex-index-phrases-parse-header t)
   (goto-char beg)
   (while (not (or (eobp)
-		  (>= (point) end)))
+                  (>= (point) end)))
     (save-excursion (reftex-index-this-phrase))
     (beginning-of-line 2)))
 
@@ -1438,31 +1438,31 @@
 Also switches to the LaTeX document to find out which files belong to
 the document and stores the list in `reftex-index-phrases-files'."
   (let* ((master (reftex-index-phrase-tex-master))
-	 buf)
+         buf)
     (if get-files
-	;; Get the file list
-	(save-excursion
-	  (setq buf (reftex-get-file-buffer-force master))
-	  (unless buf (error "Master file %s not found" master))
-	  (set-buffer buf)
-	  (reftex-access-scan-info)
-	  (setq reftex-index-phrases-files
-		(reftex-all-document-files))))
+        ;; Get the file list
+        (save-excursion
+          (setq buf (reftex-get-file-buffer-force master))
+          (unless buf (error "Master file %s not found" master))
+          (set-buffer buf)
+          (reftex-access-scan-info)
+          (setq reftex-index-phrases-files 
+                (reftex-all-document-files))))
     ;; Parse the files header for macro definitions
     (setq reftex-index-phrases-macro-data nil)
     (save-excursion
       (goto-char (point-min))
       (while (re-search-forward reftex-index-phrases-macrodef-regexp nil t)
-	(push (list
-	       (string-to-char (match-string 2))
-	       (match-string 4)
-	       (equal (match-string 6) "t"))
-	      reftex-index-phrases-macro-data))
+        (push (list
+               (string-to-char (match-string 2))
+               (match-string 4)
+               (equal (match-string 6) "t"))
+              reftex-index-phrases-macro-data))
       ;; Reverse the list, so that the first macro is first
       (if (null reftex-index-phrases-macro-data)
-	  (error "No valid MACRO DEFINITION line in %s file (make sure to use TAB separators)" reftex-index-phrase-file-extension))
-      (setq reftex-index-phrases-macro-data
-	    (nreverse reftex-index-phrases-macro-data))
+          (error "No valid MACRO DEFINITION line in %s file (make sure to use TAB separators)" reftex-index-phrase-file-extension))
+      (setq reftex-index-phrases-macro-data 
+            (nreverse reftex-index-phrases-macro-data))
       (goto-char (point-min)))))
 
 (defun reftex-index-phrases-apply-to-region (beg end)
@@ -1473,34 +1473,34 @@
 index the new part without having to go over the unchanged parts again."
   (interactive "r")
   (let ((win-conf (current-window-configuration))
-	(reftex-index-phrases-restrict-file (buffer-file-name)))
+        (reftex-index-phrases-restrict-file (buffer-file-name)))        
   (save-excursion
     (save-restriction
       (narrow-to-region beg end)
       (unwind-protect
-	  (progn
-	    ;; Hide the region highlighting
-	    (cond ((fboundp 'zmacs-deactivate-region) (zmacs-deactivate-region))
-		  ((fboundp 'deactivate-mark) (deactivate-mark)))
-	    (delete-other-windows)
-	    (reftex-index-visit-phrases-buffer)
-	    (reftex-index-all-phrases))
-	(set-window-configuration win-conf))))))
+          (progn
+            ;; Hide the region highlighting
+            (cond ((fboundp 'zmacs-deactivate-region) (zmacs-deactivate-region))
+                  ((fboundp 'deactivate-mark) (deactivate-mark)))
+            (delete-other-windows)
+            (reftex-index-visit-phrases-buffer)
+            (reftex-index-all-phrases))
+        (set-window-configuration win-conf))))))
 
 (defun reftex-index-new-phrase (&optional text)
   "Open a new line in the phrases buffer, insert TEXT."
   (interactive)
   (if (and text (stringp text))
       (progn
-	;; Check if the phrase is already in the buffer
-	(setq text (reftex-index-simplify-phrase text))
-	(goto-char (point-min))
-	(if (re-search-forward
-	     (concat "^\\(\\S-*\\)\t\\(" (regexp-quote text)
-		     "\\) *[\t\n]") nil t)
-	    (progn
-	      (goto-char (match-end 2))
-	      (error "Phrase is already in phrases buffer")))))
+        ;; Check if the phrase is already in the buffer
+        (setq text (reftex-index-simplify-phrase text))
+        (goto-char (point-min))
+        (if (re-search-forward
+             (concat "^\\(\\S-*\\)\t\\(" (regexp-quote text) 
+                     "\\) *[\t\n]") nil t)
+            (progn
+              (goto-char (match-end 2))
+              (error "Phrase is already in phrases buffer")))))
   ;; Add the new phrase line after the last in the buffer
   (goto-char (point-max))
   (if (re-search-backward reftex-index-phrases-phrase-regexp12 nil t)
@@ -1521,19 +1521,19 @@
 this function repeatedly."
   (interactive "P")
   (if (catch 'exit
-	(while (re-search-forward reftex-index-phrases-phrase-regexp12 nil t)
-	  (goto-char (match-beginning 3))
-	  (let* ((phrase (match-string 3))
-		 (case-fold-search reftex-index-phrases-case-fold-search)
-		 (re (reftex-index-phrases-find-dup-re phrase t)))
-	    (if (save-excursion
-		  (goto-char (point-min))
-		  (and (re-search-forward re nil t)
-		       (re-search-forward re nil t)))
-		(throw 'exit t)))))
+        (while (re-search-forward reftex-index-phrases-phrase-regexp12 nil t)
+          (goto-char (match-beginning 3))
+          (let* ((phrase (match-string 3))
+                 (case-fold-search reftex-index-phrases-case-fold-search)
+                 (re (reftex-index-phrases-find-dup-re phrase t)))
+            (if (save-excursion 
+                  (goto-char (point-min))
+                  (and (re-search-forward re nil t)
+                       (re-search-forward re nil t)))
+                (throw 'exit t)))))
       (progn
-	(reftex-index-phrases-info)
-	(message "Phrase with match conflict discovered"))
+        (reftex-index-phrases-info)
+        (message "Phrase with match conflict discovered"))
     (goto-char (point-max))
     (error "No further problematic phrases found")))
 
@@ -1546,82 +1546,82 @@
       (error "Not a phrase line"))
     (save-match-data (reftex-index-phrases-parse-header t))
     (let* ((char (if (not (equal (match-string 1) ""))
-		     (string-to-char (match-string 1))))
-	   (phrase (match-string 3))
-	   (index-key (match-string 6))
-	   (index-keys (split-string
-			(or index-key phrase)
-			reftex-index-phrases-logical-or-regexp))
-	   (macro-data (cdr (if (null char)
-				(car reftex-index-phrases-macro-data)
-			      (assoc char reftex-index-phrases-macro-data))))
-	   (macro-fmt (car macro-data))
-	   (repeat (nth 1 macro-data))
-	   (as-words reftex-index-phrases-search-whole-words)
-	   (example (reftex-index-make-replace-string
-		     macro-fmt (downcase phrase) (car index-keys) repeat))
-	   (re (reftex-index-make-phrase-regexp phrase as-words t))
-	   (re1 (reftex-index-phrases-find-dup-re phrase))
-	   (re2 (reftex-index-phrases-find-dup-re phrase 'sub))
-	   superphrases
-	   (nmatches 0)
-	   (ntimes1 0)
-	   (ntimes2 0)
-	   (case-fold-search reftex-index-phrases-case-fold-search)
-	   file files buf)
+                     (string-to-char (match-string 1))))
+           (phrase (match-string 3))
+           (index-key (match-string 6))
+           (index-keys (split-string
+                        (or index-key phrase)
+                        reftex-index-phrases-logical-or-regexp))
+           (macro-data (cdr (if (null char)
+                                (car reftex-index-phrases-macro-data)
+                              (assoc char reftex-index-phrases-macro-data))))
+           (macro-fmt (car macro-data))
+           (repeat (nth 1 macro-data))
+           (as-words reftex-index-phrases-search-whole-words)
+           (example (reftex-index-make-replace-string
+                     macro-fmt (downcase phrase) (car index-keys) repeat))
+           (re (reftex-index-make-phrase-regexp phrase as-words t))
+           (re1 (reftex-index-phrases-find-dup-re phrase))
+           (re2 (reftex-index-phrases-find-dup-re phrase 'sub))
+           superphrases
+           (nmatches 0)
+           (ntimes1 0)
+           (ntimes2 0)
+           (case-fold-search reftex-index-phrases-case-fold-search)
+           file files buf)
       (setq files reftex-index-phrases-files)
       (save-excursion
-	(save-restriction
-	  (widen)
-	  (goto-char (point-min))
-	  (while (re-search-forward re1 nil t)
-	    (incf ntimes1))
-	  (goto-char (point-min))
-	  (while (re-search-forward re2 nil t)
-	    (push (cons (count-lines 1 (point)) (match-string 1)) superphrases)
-	    (incf ntimes2))))
+        (save-restriction
+          (widen)
+          (goto-char (point-min))
+          (while (re-search-forward re1 nil t)
+            (incf ntimes1))
+          (goto-char (point-min))
+          (while (re-search-forward re2 nil t)
+            (push (cons (count-lines 1 (point)) (match-string 1)) superphrases)
+            (incf ntimes2))))
       (save-excursion
-	(while (setq file (pop files))
-	  (setq buf (reftex-get-file-buffer-force file))
-	  (when buf
-	    (set-buffer buf)
-	    (save-excursion
-	      (save-restriction
-		(widen)
-		(goto-char (point-min))
-		(let ((case-fold-search reftex-index-phrases-case-fold-search))
-		  (while (re-search-forward re nil t)
-		    (or (reftex-in-comment)
-			(incf nmatches)))))))))
+        (while (setq file (pop files))
+          (setq buf (reftex-get-file-buffer-force file))
+          (when buf
+            (set-buffer buf)
+            (save-excursion
+              (save-restriction
+                (widen)
+                (goto-char (point-min))
+                (let ((case-fold-search reftex-index-phrases-case-fold-search))
+                  (while (re-search-forward re nil t)
+                    (or (reftex-in-comment)
+                        (incf nmatches)))))))))
       (with-output-to-temp-buffer "*Help*"
-	(princ (format "       Phrase:  %s\n" phrase))
-	(princ (format "    Macro key:  %s\n" char))
-	(princ (format " Macro format:  %s\n" macro-fmt))
-	(princ (format "       Repeat:  %s\n" repeat))
-	(cond
-	 (index-key
-	  (let ((iks index-keys) (cnt 0) ik)
-	    (while (setq ik (pop iks))
-	      (princ (format "Index entry %d:  %s\n" (incf cnt) ik)))))
-	 (repeat
-	  (princ (format "  Index entry:  %s\n" phrase)))
-	 (t
-	  (princ (format "    Index key:  <<Given by the match>>\n"))))
-	(princ (format "      Example:  %s\n" example))
-	(terpri)
-	(princ (format "Total matches:  %s in %s\n"
-		       (reftex-number nmatches "match" "es")
-		       (reftex-number (length reftex-index-phrases-files)
-				      "LaTeX file")))
-	(princ (format "   Uniqueness:  Phrase occurs %s in phrase buffer\n"
-		       (reftex-number ntimes1 "time")))
-	(if (> ntimes2 1)
-	    (progn
-	      (princ (format " Superphrases:  Phrase matches the following %s in the phrase buffer:\n"
-			     (reftex-number ntimes2 "line")))
-	      (mapcar (lambda(x)
-			(princ (format "                Line %4d:  %s\n" (car x) (cdr x))))
-		      (nreverse superphrases))))))))
+        (princ (format "       Phrase:  %s\n" phrase))
+        (princ (format "    Macro key:  %s\n" char))
+        (princ (format " Macro format:  %s\n" macro-fmt))
+        (princ (format "       Repeat:  %s\n" repeat))
+        (cond
+         (index-key
+          (let ((iks index-keys) (cnt 0) ik)
+            (while (setq ik (pop iks))
+              (princ (format "Index entry %d:  %s\n" (incf cnt) ik)))))
+         (repeat
+          (princ (format "  Index entry:  %s\n" phrase)))
+         (t
+          (princ (format "    Index key:  <<Given by the match>>\n"))))
+        (princ (format "      Example:  %s\n" example))
+        (terpri)
+        (princ (format "Total matches:  %s in %s\n"
+                       (reftex-number nmatches "match" "es")
+                       (reftex-number (length reftex-index-phrases-files)
+                                      "LaTeX file")))
+        (princ (format "   Uniqueness:  Phrase occurs %s in phrase buffer\n"
+                       (reftex-number ntimes1 "time")))
+        (if (> ntimes2 1)
+            (progn
+              (princ (format " Superphrases:  Phrase matches the following %s in the phrase buffer:\n"
+                             (reftex-number ntimes2 "line")))
+              (mapcar (lambda(x) 
+                        (princ (format "                Line %4d:  %s\n" (car x) (cdr x))))
+                      (nreverse superphrases))))))))
 
 (defun reftex-index-phrases-set-macro-key ()
   "Change the macro key for the current line.
@@ -1634,32 +1634,32 @@
   (save-excursion
     (beginning-of-line)
     (unless (or (looking-at reftex-index-phrases-phrase-regexp12)
-		(looking-at "\t"))
+                (looking-at "\t"))
       (error "This is not a phrase line"))
     (let* ((nc (reftex-index-select-phrases-macro 0))
-	   (macro-data (assoc nc reftex-index-phrases-macro-data))
-	   macro-fmt repeat)
+           (macro-data (assoc nc reftex-index-phrases-macro-data))
+           macro-fmt repeat)
       (cond (macro-data)
-	    ((equal nc ?\ )
-	     (setq nc ""
-		   macro-data (car reftex-index-phrases-macro-data)))
-	    ((equal nc ?\C-m)
-	     (setq nc (char-after (point)))
-	     (if (equal nc ?\t)
-		 (setq nc ""
-		       macro-data (car reftex-index-phrases-macro-data))
-	       (setq macro-data (assoc nc reftex-index-phrases-macro-data))))
-	    (t (error "No macro associated with %c" nc)))
+            ((equal nc ?\ )
+             (setq nc ""
+                   macro-data (car reftex-index-phrases-macro-data)))
+            ((equal nc ?\C-m)
+             (setq nc (char-after (point)))
+             (if (equal nc ?\t)
+                 (setq nc ""
+                       macro-data (car reftex-index-phrases-macro-data))
+               (setq macro-data (assoc nc reftex-index-phrases-macro-data))))
+            (t (error "No macro associated with %c" nc)))
 
       (setq macro-fmt (nth 1 macro-data)
-	    repeat (nth 2 macro-data))
+            repeat (nth 2 macro-data))
       (if macro-data
-	  (progn
-	    (if (looking-at "[^\t]") (delete-char 1))
-	    (insert nc)
-	    (message "Line will use %s %s repeat" macro-fmt
-		     (if repeat "with" "without")))
-	(error "Abort")))))
+          (progn
+            (if (looking-at "[^\t]") (delete-char 1))
+            (insert nc)
+            (message "Line will use %s %s repeat" macro-fmt
+                     (if repeat "with" "without")))
+        (error "Abort")))))
 
 (defun reftex-index-sort-phrases (&optional chars-first)
   "Sort the phrases lines in the buffer alphabetically.
@@ -1668,28 +1668,28 @@
   (interactive "P")
   ;; Remember the current line, so that we can return
   (let ((line (buffer-substring (progn (beginning-of-line) (point))
-				(progn (end-of-line) (point))))
-	beg end)
+                                (progn (end-of-line) (point))))
+        beg end)
     (goto-char (point-min))
     ;; Find first and last phrase line in buffer
-    (setq beg
-	  (and (re-search-forward reftex-index-phrases-phrase-regexp12 nil t)
-	       (match-beginning 0)))
+    (setq beg 
+          (and (re-search-forward reftex-index-phrases-phrase-regexp12 nil t)
+               (match-beginning 0)))
     (goto-char (point-max))
     (setq end (re-search-backward reftex-index-phrases-phrase-regexp12 nil t))
     (if end (setq end (progn (goto-char end) (end-of-line) (point))))
     ;; Take the lines, sort them and re-insert.
     (if (and beg end)
-	(progn
-	  (message "Sorting lines...")
-	  (let* ((lines (split-string (buffer-substring beg end) "\n"))
-		 (lines1 (sort lines 'reftex-compare-phrase-lines)))
-	    (message "Sorting lines...done")
-	    (let ((inhibit-quit t))  ;; make sure we do not loose lines
-	      (delete-region beg end)
-	      (insert (mapconcat 'identity lines1 "\n"))))
-	  (goto-char (point-max))
-	  (re-search-backward (concat "^" (regexp-quote line) "$") nil t))
+        (progn
+          (message "Sorting lines...")
+          (let* ((lines (split-string (buffer-substring beg end) "\n"))
+                 (lines1 (sort lines 'reftex-compare-phrase-lines)))
+            (message "Sorting lines...done")
+            (let ((inhibit-quit t))  ;; make sure we do not loose lines
+              (delete-region beg end)
+              (insert (mapconcat 'identity lines1 "\n"))))
+          (goto-char (point-max))
+          (re-search-backward (concat "^" (regexp-quote line) "$") nil t))
       (error "Cannot find phrases lines to sort"))))
 
 (defvar chars-first)
@@ -1697,28 +1697,28 @@
   "The comparison function used for sorting."
   (let (ca cb pa pb c-p p-p)
     (if (string-match reftex-index-phrases-phrase-regexp12 a)
-	(progn
-	  ;; Extract macro char and phrase-or-key for a
-	  (setq ca (match-string 1 a)
-		pa (downcase
-		    (or (and reftex-index-phrases-sort-prefers-entry
-			     (match-string 6 a))
-			(match-string 3 a))))
-	  (if (string-match reftex-index-phrases-phrase-regexp12 b)
-	      (progn
-		;; Extract macro char and phrase-or-key for b
-		(setq cb (match-string 1 b)
-		      pb (downcase
-			  (or (and reftex-index-phrases-sort-prefers-entry
-				   (match-string 6 b))
-			      (match-string 3 b))))
-		(setq c-p (string< ca cb)
-		      p-p (string< pa pb))
-		;; Do the right comparison, based on the value of `chars-first'
-		;; `chars-first' is bound locally in the calling function
-		(if chars-first
-		    (if (string= ca cb) p-p c-p)
-		  (if (string= pa pb) c-p p-p)))))
+        (progn
+          ;; Extract macro char and phrase-or-key for a
+          (setq ca (match-string 1 a) 
+                pa (downcase 
+                    (or (and reftex-index-phrases-sort-prefers-entry
+                             (match-string 6 a))
+                        (match-string 3 a))))
+          (if (string-match reftex-index-phrases-phrase-regexp12 b)
+              (progn
+                ;; Extract macro char and phrase-or-key for b
+                (setq cb (match-string 1 b) 
+                      pb (downcase
+                          (or (and reftex-index-phrases-sort-prefers-entry
+                                   (match-string 6 b))
+                              (match-string 3 b))))
+                (setq c-p (string< ca cb)
+                      p-p (string< pa pb))
+                ;; Do the right comparison, based on the value of `chars-first'
+                ;; `chars-first' is bound locally in the calling function               
+                (if chars-first
+                    (if (string= ca cb) p-p c-p)
+                  (if (string= pa pb) c-p p-p)))))
       ;; If line a does not match, the answer we return determines
       ;; if non-matching lines are collected at the beginning.
       ;; When we return t here, non-matching lines form
@@ -1726,22 +1726,22 @@
       (not reftex-index-phrases-sort-in-blocks))))
 
 (defvar reftex-index-phrases-menu)
-(defun reftex-index-make-phrase-regexp (phrase &optional
-					       as-words allow-newline)
+(defun reftex-index-make-phrase-regexp (phrase &optional 
+                                               as-words allow-newline)
   "Return a regexp matching PHRASE, even if distributed over lines.
 With optional arg AS-WORDS, require word boundary at beginning and end.
 With optional arg ALLOW-NEWLINE, allow single newline between words."
   (let* ((words (split-string phrase))
-	 (space-re (if allow-newline
-		       "\\([ \t]*\\(\n[ \t]*\\)?\\|[ \t]\\)"
-		     "\\([ \t]+\\)")))
+         (space-re (if allow-newline
+                       "\\([ \t]*\\(\n[ \t]*\\)?\\|[ \t]\\)"
+                     "\\([ \t]+\\)")))
     (concat (if (and as-words (string-match "\\`\\w" (car words)))
-		"\\<" "")
-	    (mapconcat (lambda (w) (regexp-quote (downcase w)))
-		       words space-re)
-	    (if (and as-words
-		     (string-match "\\w\\'" (nth (1- (length words)) words)))
-		"\\>" ""))))
+                "\\<" "")
+            (mapconcat (lambda (w) (regexp-quote (downcase w)))
+                       words space-re)
+            (if (and as-words 
+                     (string-match "\\w\\'" (nth (1- (length words)) words)))
+                "\\>" ""))))
 
 (defun reftex-index-simplify-phrase (phrase)
   "Make phrase single spaces and single line."
@@ -1752,40 +1752,40 @@
 When SUB ins non-nil, the regexp will also match when PHRASE is a subphrase
 of another phrase.  The regexp works lonly in the phrase buffer."
   (concat (if sub "^\\S-?\t\\([^\t\n]*" "^\\S-?\t")
-	  (mapconcat 'regexp-quote (split-string phrase) " +")
-	  (if sub "[^\t\n]*\\)\\([\t\n]\\|$\\)" " *\\([\t\n]\\|$\\)")))
+          (mapconcat 'regexp-quote (split-string phrase) " +")
+          (if sub "[^\t\n]*\\)\\([\t\n]\\|$\\)" " *\\([\t\n]\\|$\\)")))
 
 (defun reftex-index-make-replace-string (macro-fmt match index-key
-						   &optional repeat mathp)
+                                                   &optional repeat mathp)
   "Return the string which can be used as replacement.
 Treats the logical `and' for index phrases."
   (let ((index-keys (split-string (or index-key match)
-				  reftex-index-phrases-logical-and-regexp)))
+                                  reftex-index-phrases-logical-and-regexp)))
     (concat
-     (mapconcat (lambda (x)
-		  (format macro-fmt
-			  (format (if mathp reftex-index-math-format "%s") x)))
-		index-keys "")
+     (mapconcat (lambda (x) 
+                  (format macro-fmt 
+                          (format (if mathp reftex-index-math-format "%s") x)))
+                index-keys "")
    (if repeat (reftex-index-simplify-phrase match) ""))))
 
 (defun reftex-query-index-phrase-globally (files &rest args)
   "Call `reftex-query-index-phrase' for all files in FILES."
   (let ((win-conf (current-window-configuration))
-	(file))
+        (file))
     (unless files (error "No files"))
     (unwind-protect
-	(progn
-	  (switch-to-buffer-other-window (reftex-get-file-buffer-force
-					  (car files)))
-	  (catch 'no-more-files
-	    (while (setq file (pop files))
-	      (switch-to-buffer (reftex-get-file-buffer-force file))
-	      (save-excursion
-		(save-restriction
-		  (unless (stringp reftex-index-phrases-restrict-file)
-		    (widen))
-		  (goto-char (point-min))
-		  (apply 'reftex-query-index-phrase args))))))
+        (progn
+          (switch-to-buffer-other-window (reftex-get-file-buffer-force 
+                                          (car files)))
+          (catch 'no-more-files
+            (while (setq file (pop files))
+              (switch-to-buffer (reftex-get-file-buffer-force file))
+              (save-excursion
+                (save-restriction
+                  (unless (stringp reftex-index-phrases-restrict-file)
+                    (widen))
+                  (goto-char (point-min))
+                  (apply 'reftex-query-index-phrase args))))))
       (reftex-unhighlight 0)
       (set-window-configuration win-conf))))
 
@@ -1806,7 +1806,7 @@
 
 (defvar replace-count)
 (defun reftex-query-index-phrase (phrase macro-fmt &optional
-					 index-key repeat as-words)
+                                         index-key repeat as-words)
   "Search through buffer for PHRASE, and offer to replace it with an indexed
 version.  The index version is derived by applying `format' with MACRO-FMT
 to INDEX-KEY or PHRASE.  When REPEAT is non-nil, the PHRASE is inserted
@@ -1814,140 +1814,142 @@
 AS-WORDS means, the search for PHRASE should require word boundaries at
 both ends."
   (let* ((re (reftex-index-make-phrase-regexp phrase as-words 'allow-newline))
-	 (case-fold-search reftex-index-phrases-case-fold-search)
-	 (index-keys (split-string
-		      (or index-key phrase)
-		      reftex-index-phrases-logical-or-regexp))
-	 (nkeys (length index-keys))
-	 (ckey (nth 0 index-keys))
-	 (all-yes nil)
-	 match rpl char beg end mathp)
+         (case-fold-search reftex-index-phrases-case-fold-search)
+         (index-keys (split-string 
+                      (or index-key phrase)
+                      reftex-index-phrases-logical-or-regexp))
+         (nkeys (length index-keys))
+         (ckey (nth 0 index-keys))
+         (all-yes nil) 
+         match rpl char beg end mathp)
     (unwind-protect
-	(while (re-search-forward re nil t)
-	  (catch 'next-match
-	    (if (and (fboundp reftex-index-verify-function)
-		     (not (funcall reftex-index-verify-function)))
-		(throw 'next-match nil))
-	    (setq match (match-string 0))
-	    (setq mathp
-		  (save-match-data
-		    (condition-case nil (texmathp) (error nil))))
-	    (setq beg (car (match-data))
-		  end (nth 1 (match-data)))
-	    (if (and reftex-index-phrases-skip-indexed-matches
-		     (save-match-data
-		       (reftex-index-phrase-match-is-indexed beg
-							     end)))
-		(throw 'next-match nil))
-	    (reftex-highlight 0 (match-beginning 0) (match-end 0))
-	    (setq rpl
-		  (save-match-data
-		    (reftex-index-make-replace-string
-		     macro-fmt (match-string 0) ckey repeat mathp)))
-	    (while
-		(not
-		 (catch 'loop
-		   (message "REPLACE: %s?   (yn!qoe%s?)"
-			    rpl
-			    (if (> nkeys 1)
-				(concat "1-" (int-to-string nkeys))
-			      ""))
-		   (setq char (if all-yes ?y (read-char-exclusive)))
-		   (cond ((member char '(?y ?Y ?\ ))
-			  ;; Yes!
-			  (replace-match rpl t t)
-			  (incf replace-count)
-			  ;; See if we should insert newlines to shorten lines
-			  (and reftex-index-phrases-wrap-long-lines
-			       (reftex-index-phrases-fixup-line beg end))
-			  (throw 'loop t))
-			 ((member char '(?n ?N ?\C-h ?\C-?));; FIXME: DEL
-			  ;; No
-			  (throw 'loop t))
-			 ((equal char ?!)
-			  ;; Yes for all in this buffer
-			  (setq all-yes t))
-			 ((equal char ?q)
-			  ;; Stop this one in this file
-			  (goto-char (point-max))
-			  (throw 'loop t))
-			 ((equal char ?Q)
-			  ;; Stop this one
-			  (throw 'no-more-files t))
-			 ((equal char ?s)
-			  (save-buffer))
-			 ((equal char ?S)
-			  (reftex-save-all-document-buffers))
-			 ((equal char ?\C-g)
-			  (keyboard-quit))
-			 ((member char '(?o ?O))
-			  ;; Select a differnt macro
-			  (let* ((nc (reftex-index-select-phrases-macro 2))
-				 (macro-data
-				  (cdr (assoc nc reftex-index-phrases-macro-data)))
-				 (macro-fmt (car macro-data))
-				 (repeat (nth 1 macro-data)))
-			    (if macro-data
-				(setq rpl (save-match-data
-					    (reftex-index-make-replace-string
-					     macro-fmt match
-					     ckey repeat mathp)))
-			      (ding))))
-			 ((equal char ?\?)
-			  ;; Help
-			  (with-output-to-temp-buffer "*Help*"
-			    (princ reftex-index-phrases-help)))
-			 ((equal char ?\C-r)
-			  ;; Recursive edit
-			  (save-match-data
-			    (save-excursion
-			      (message
-			       (substitute-command-keys
-				"Recursive edit.  Resume with \\[exit-recursive-edit]"))
-			      (recursive-edit))))
-			 ((equal char ?e)
-			  (setq rpl (read-string "Edit: " rpl)))
-			 ((equal char ?0)
-			  (setq ckey (or index-key phrase)
-				rpl (save-match-data
-				      (reftex-index-make-replace-string
-				       macro-fmt match ckey repeat mathp))))
-			 ((and (> char ?0)
-			       (<= char (+ ?0 nkeys)))
-			  (setq ckey (nth (1- (- char ?0)) index-keys)
-				rpl (save-match-data
-				      (reftex-index-make-replace-string
-				       macro-fmt match ckey repeat mathp))))
-			 (t (ding)))
-		   nil)))))
+        (while (re-search-forward re nil t)
+          (catch 'next-match
+            (if (and (fboundp reftex-index-verify-function)
+                     (not (funcall reftex-index-verify-function)))
+                (throw 'next-match nil))
+            (setq match (match-string 0))
+            (setq mathp
+                  (save-match-data
+                    (condition-case nil (texmathp) (error nil))))
+            (setq beg (car (match-data))
+                  end (nth 1 (match-data)))
+            (if (and reftex-index-phrases-skip-indexed-matches
+                     (save-match-data
+                       (reftex-index-phrase-match-is-indexed beg
+                                                             end)))
+                (throw 'next-match nil))
+            (reftex-highlight 0 (match-beginning 0) (match-end 0))
+            (setq rpl 
+                  (save-match-data
+                    (reftex-index-make-replace-string
+                     macro-fmt (match-string 0) ckey repeat mathp)))
+            (while 
+                (not
+                 (catch 'loop
+                   (message "REPLACE: %s?   (yn!qoe%s?)"
+                            rpl
+                            (if (> nkeys 1) 
+                                (concat "1-" (int-to-string nkeys))
+                              ""))
+                   (setq char (if all-yes ?y (read-char-exclusive)))
+                   (cond ((member char '(?y ?Y ?\ ))
+                          ;; Yes!
+                          (replace-match rpl t t)
+                          (incf replace-count)
+                          ;; See if we should insert newlines to shorten lines
+                          (and reftex-index-phrases-wrap-long-lines
+                               (reftex-index-phrases-fixup-line beg end))
+                          (throw 'loop t))
+                         ((member char '(?n ?N ?\C-h ?\C-?));; FIXME: DEL
+                          ;; No
+                          (throw 'loop t))
+                         ((equal char ?!)
+                          ;; Yes for all in this buffer
+                          (setq all-yes t))
+                         ((equal char ?q)
+                          ;; Stop this one in this file
+                          (goto-char (point-max))
+                          (throw 'loop t))
+                         ((equal char ?Q)
+                          ;; Stop this one
+                          (throw 'no-more-files t))
+                         ((equal char ?s)
+                          (save-buffer))
+                         ((equal char ?S)
+                          (reftex-save-all-document-buffers))
+                         ((equal char ?\C-g)
+                          (keyboard-quit))
+                         ((member char '(?o ?O))
+                          ;; Select a differnt macro
+                          (let* ((nc (reftex-index-select-phrases-macro 2))
+                                 (macro-data 
+                                  (cdr (assoc nc reftex-index-phrases-macro-data)))
+                                 (macro-fmt (car macro-data))
+                                 (repeat (nth 1 macro-data)))
+                            (if macro-data
+                                (setq rpl (save-match-data
+                                            (reftex-index-make-replace-string
+                                             macro-fmt match
+                                             ckey repeat mathp)))
+                              (ding))))
+                         ((equal char ?\?)
+                          ;; Help
+                          (with-output-to-temp-buffer "*Help*"
+                            (princ reftex-index-phrases-help)))
+                         ((equal char ?\C-r)
+                          ;; Recursive edit
+                          (save-match-data
+                            (save-excursion
+                              (message 
+                               (substitute-command-keys
+                                "Recursive edit.  Resume with \\[exit-recursive-edit]"))
+                              (recursive-edit))))
+                         ((equal char ?e)
+                          (setq rpl (read-string "Edit: " rpl)))
+                         ((equal char ?0)
+                          (setq ckey (or index-key phrase)
+                                rpl (save-match-data
+                                      (reftex-index-make-replace-string
+                                       macro-fmt match ckey repeat mathp))))
+                         ((and (> char ?0)
+                               (<= char (+ ?0 nkeys)))
+                          (setq ckey (nth (1- (- char ?0)) index-keys)
+                                rpl (save-match-data
+                                      (reftex-index-make-replace-string
+                                       macro-fmt match ckey repeat mathp))))
+                         (t (ding)))
+                   nil)))))
       (message "")
       (setq all-yes nil)
       (reftex-unhighlight 0))))
 
 (defun reftex-index-phrase-match-is-indexed (beg end)
+  ;; CHeck if match is in an argument of an index macro, or if an
+  ;; index macro is directly attached to the match.
   (save-excursion
     (goto-char end)
-    (let* ((this-macro (car (reftex-what-macro 1)))
-	   (before-char (char-before beg))
-	   (after-char (char-after end))
-	   (before-macro
-	    (and (> beg 2)
-		 (goto-char (1- beg))
-		 (memq (char-after (point)) '(?\] ?\}))
-		 (car (reftex-what-macro 1))))
-	   (after-macro
-	    (and (goto-char end)
-		 (looking-at "\\(\\\\[a-zA-Z]+\\*?\\)[[{]")
-		 (match-string 1))))
-      (or (and this-macro
-	       (member before-char '(?\{ ?\[))
-	       (member after-char '(?\} ?\]))
-	       (member this-macro reftex-macros-with-index))
-	  (and before-macro
-	       (member before-macro reftex-macros-with-index))
-	  (and after-macro
-	       (member after-macro reftex-macros-with-index))))))
-
+    (let* ((all-macros (reftex-what-macro t))
+           (this-macro (car (car all-macros)))
+           (before-macro
+            (and (> beg 2)
+                 (goto-char (1- beg))
+                 (memq (char-after (point)) '(?\] ?\}))
+                 (car (reftex-what-macro 1))))
+           (after-macro
+            (and (goto-char end)
+                 (looking-at "\\(\\\\[a-zA-Z]+\\*?\\)[[{]")
+                 (match-string 1)))
+           macro)
+      (or (catch 'matched
+            (while (setq macro (pop all-macros))
+              (if (member (car macro) reftex-macros-with-index)
+                  (throw 'matched t)))
+            nil)
+          (and before-macro
+               (member before-macro reftex-macros-with-index))
+          (and after-macro
+               (member after-macro reftex-macros-with-index))))))
 
 (defun reftex-index-phrases-fixup-line (beg end)
   "Insert newlines before BEG and/or after END to shorten line."
@@ -1961,38 +1963,38 @@
       (goto-char beg)
       (skip-chars-backward "^ \n")
       (if (and (equal (preceding-char) ?\ )
-	       (string-match "\\S-" (buffer-substring bol (point))))
-	  (setq space1 (1- (point))))
+               (string-match "\\S-" (buffer-substring bol (point))))
+          (setq space1 (1- (point))))
       (goto-char end)
       (skip-chars-forward "^ \n")
       (if (and (equal (following-char) ?\ )
-	       (string-match "\\S-" (buffer-substring (point) eol)))
-	  (setq space2 (point)))
+               (string-match "\\S-" (buffer-substring (point) eol)))
+          (setq space2 (point)))
       ;; Now check what we have and insert the newlines
       (if (<= (- eol bol) fill-column)
-	  ;; Line is already short
-	  nil
-	(cond
-	 ((and (not space1) (not space2))) ; No spaces available
-	 ((not space2)			; Do space1
-	  (reftex-index-phrases-replace-space space1))
-	 ((not space1)			; Do space2
-	  (reftex-index-phrases-replace-space space2))
-	 (t ; We have both spaces
-	  (let ((l1 (- space1 bol))
-		(l2 (- space2 space1))
-		(l3 (- eol space2)))
-	    (if (> l2 fill-column)
-		;; The central part alone is more than one line
-		(progn
-		  (reftex-index-phrases-replace-space space1)
-		  (reftex-index-phrases-replace-space space2))
-	      (if (> (+ l1 l2) fill-column)
-		  ;; Need to split beginning
-		  (reftex-index-phrases-replace-space space1))
-	      (if (> (+ l2 l3) fill-column)
-		  ;; Need to split end
-		  (reftex-index-phrases-replace-space space2))))))))))
+          ;; Line is already short
+          nil
+        (cond
+         ((and (not space1) (not space2))) ; No spaces available
+         ((not space2)                  ; Do space1
+          (reftex-index-phrases-replace-space space1))
+         ((not space1)                  ; Do space2
+          (reftex-index-phrases-replace-space space2))
+         (t ; We have both spaces
+          (let ((l1 (- space1 bol))
+                (l2 (- space2 space1))
+                (l3 (- eol space2)))
+            (if (> l2 fill-column)
+                ;; The central part alone is more than one line
+                (progn
+                  (reftex-index-phrases-replace-space space1)
+                  (reftex-index-phrases-replace-space space2))
+              (if (> (+ l1 l2) fill-column)
+                  ;; Need to split beginning
+                  (reftex-index-phrases-replace-space space1))
+              (if (> (+ l2 l3) fill-column)
+                  ;; Need to split end
+                  (reftex-index-phrases-replace-space space2))))))))))
 
 (defun reftex-index-phrases-replace-space (pos)
   "If there is a space at POS, replace it with a newline char.
@@ -2005,34 +2007,34 @@
 (defun reftex-index-select-phrases-macro (&optional delay)
   "Offer a list of possible index macros and have the user select one."
   (let* ((prompt (concat "Select macro: ["
-			 (mapconcat (lambda (x) (char-to-string (car x)))
-				    reftex-index-phrases-macro-data "")
-			 "] "))
-	 (help (concat "Select an indexing macro\n========================\n"
-		       (mapconcat (lambda (x)
-				    (format " [%c]     %s"
-					    (car x) (nth 1 x)))
-				  reftex-index-phrases-macro-data "\n"))))
+                         (mapconcat (lambda (x) (char-to-string (car x)))
+                                    reftex-index-phrases-macro-data "")
+                         "] "))
+         (help (concat "Select an indexing macro\n========================\n"
+                       (mapconcat (lambda (x)
+                                    (format " [%c]     %s"
+                                            (car x) (nth 1 x)))
+                                  reftex-index-phrases-macro-data "\n"))))
     (reftex-select-with-char prompt help delay)))
 
 ;; Keybindings and Menu for phrases buffer
 
 (loop for x in
       '(("\C-c\C-c" . reftex-index-phrases-save-and-return)
-	("\C-c\C-x" . reftex-index-this-phrase)
-	("\C-c\C-f" . reftex-index-next-phrase)
-	("\C-c\C-r" . reftex-index-region-phrases)
-	("\C-c\C-a" . reftex-index-all-phrases)
-	("\C-c\C-d" . reftex-index-remaining-phrases)
-	("\C-c\C-s" . reftex-index-sort-phrases)
-	("\C-c\C-n" . reftex-index-new-phrase)
-	("\C-c\C-m" . reftex-index-phrases-set-macro-key)
-	("\C-c\C-i" . reftex-index-phrases-info)
-	("\C-c\C-t" . reftex-index-find-next-conflict-phrase)
-	("\C-i"     . self-insert-command))
+        ("\C-c\C-x" . reftex-index-this-phrase)
+        ("\C-c\C-f" . reftex-index-next-phrase)
+        ("\C-c\C-r" . reftex-index-region-phrases)
+        ("\C-c\C-a" . reftex-index-all-phrases)
+        ("\C-c\C-d" . reftex-index-remaining-phrases)
+        ("\C-c\C-s" . reftex-index-sort-phrases)
+        ("\C-c\C-n" . reftex-index-new-phrase)
+        ("\C-c\C-m" . reftex-index-phrases-set-macro-key)
+        ("\C-c\C-i" . reftex-index-phrases-info)
+        ("\C-c\C-t" . reftex-index-find-next-conflict-phrase)
+        ("\C-i"     . self-insert-command))
       do (define-key reftex-index-phrases-map (car x) (cdr x)))
 
-(easy-menu-define
+(easy-menu-define 
  reftex-index-phrases-menu reftex-index-phrases-map
  "Menu for Phrases buffer"
  '("Phrases"
@@ -2049,7 +2051,7 @@
     ["by Index Entry" (setq reftex-index-phrases-sort-prefers-entry t)
      :style radio :selected reftex-index-phrases-sort-prefers-entry]
     ["in Blocks" (setq reftex-index-phrases-sort-in-blocks
-			  (not reftex-index-phrases-sort-in-blocks))
+                          (not reftex-index-phrases-sort-in-blocks))
      :style toggle :selected reftex-index-phrases-sort-in-blocks])
    ["Describe Phrase" reftex-index-phrases-info t]
    ["Next Phrase Conflict" reftex-index-find-next-conflict-phrase t]
@@ -2063,17 +2065,17 @@
     "--"
     "Options"
     ["Match Whole Words" (setq reftex-index-phrases-search-whole-words
-			  (not reftex-index-phrases-search-whole-words))
+                          (not reftex-index-phrases-search-whole-words))
      :style toggle :selected reftex-index-phrases-search-whole-words]
     ["Case Sensitive Search" (setq reftex-index-phrases-case-fold-search
-				  (not  reftex-index-phrases-case-fold-search))
+                                  (not  reftex-index-phrases-case-fold-search))
      :style toggle :selected (not
-			      reftex-index-phrases-case-fold-search)]
+                              reftex-index-phrases-case-fold-search)]
     ["Wrap Long Lines" (setq reftex-index-phrases-wrap-long-lines
-			     (not reftex-index-phrases-wrap-long-lines))
+                             (not reftex-index-phrases-wrap-long-lines))
     :style toggle :selected reftex-index-phrases-wrap-long-lines]
     ["Skip Indexed Matches" (setq reftex-index-phrases-skip-indexed-matches
-				  (not reftex-index-phrases-skip-indexed-matches))
+                                  (not reftex-index-phrases-skip-indexed-matches))
      :style toggle :selected reftex-index-phrases-skip-indexed-matches])
    "--"
    ["Save and Return" reftex-index-phrases-save-and-return t]))
--- a/lisp/textmodes/reftex-parse.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-parse.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-parse.el --- parser functions for RefTeX
-;; Copyright (c) 1997, 1998, 1999, 2000, 2003  Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 ;;
 
 ;; This file is part of GNU Emacs.
@@ -33,10 +33,10 @@
 (defmacro reftex-with-special-syntax (&rest body)
   `(let ((saved-syntax (syntax-table)))
      (unwind-protect
-	 (progn
-	   (set-syntax-table reftex-syntax-table)
-	   (let ((case-fold-search nil))
-	     ,@body))
+         (progn
+           (set-syntax-table reftex-syntax-table)
+           (let ((case-fold-search nil))
+             ,@body))
        (set-syntax-table saved-syntax))))
 
 (defun reftex-parse-one ()
@@ -68,12 +68,12 @@
 
   (let* ((old-list (symbol-value reftex-docstruct-symbol))
          (master (reftex-TeX-master-file))
-	 (true-master (file-truename master))
-	 (master-dir (file-name-as-directory (file-name-directory master)))
+         (true-master (file-truename master))
+         (master-dir (file-name-as-directory (file-name-directory master)))
          (file (or file (buffer-file-name)))
-	 (true-file (file-truename file))
-	 (bibview-cache (assq 'bibview-cache old-list))
-	 (index-tags (cdr (assq 'index-tags old-list)))
+         (true-file (file-truename file))
+         (bibview-cache (assq 'bibview-cache old-list))
+         (index-tags (cdr (assq 'index-tags old-list)))
          from-file appendix docstruct tmp)
 
     ;; Make sure replacement is really an option here
@@ -97,9 +97,9 @@
 
     ;; Find active toc entry and initialize section-numbers
     (setq reftex-active-toc (reftex-last-assoc-before-elt
-			     'toc (list 'bof from-file) old-list)
-	  appendix (reftex-last-assoc-before-elt
-		    'appendix (list 'bof from-file) old-list))
+                             'toc (list 'bof from-file) old-list)
+          appendix (reftex-last-assoc-before-elt
+                    'appendix (list 'bof from-file) old-list))
 
     (reftex-init-section-numbers reftex-active-toc appendix)
 
@@ -110,11 +110,11 @@
     (reftex-with-special-syntax
      (save-window-excursion
        (save-excursion
-	 (unwind-protect
-	     (setq docstruct
-		   (reftex-parse-from-file
-		    from-file docstruct master-dir))
-	   (reftex-kill-temporary-buffers)))))
+         (unwind-protect
+             (setq docstruct
+                   (reftex-parse-from-file
+                    from-file docstruct master-dir))
+           (reftex-kill-temporary-buffers)))))
 
     (message "Scanning document... done")
 
@@ -141,27 +141,27 @@
     (and index-tags (setq index-tags (sort index-tags 'string<)))
     (let ((index-tag-cell (assq 'index-tags docstruct)))
       (if index-tag-cell
-	  (setcdr index-tag-cell index-tags)
-	(push (cons 'index-tags index-tags) docstruct)))
+          (setcdr index-tag-cell index-tags)
+        (push (cons 'index-tags index-tags) docstruct)))
     (unless (assq 'xr docstruct)
       (let* ((allxr (reftex-all-assq 'xr-doc docstruct))
-	     (alist (mapcar
-		     (lambda (x)
-		       (if (setq tmp (reftex-locate-file (nth 2 x) "tex"
-							 master-dir))
-			   (cons (nth 1 x) tmp)
-			 (message "Can't find external document %s"
-				  (nth 2 x))
-			 nil))
-		     allxr))
-	     (alist (delq nil alist))
-	     (allprefix (delq nil (mapcar 'car alist)))
-	     (regexp (if allprefix
-			 (concat "\\`\\("
-				 (mapconcat 'identity allprefix "\\|")
-				 "\\)")
-		       "\\\\\\\\\\\\")))   ; this will never match
-	(push (list 'xr alist regexp) docstruct)))
+             (alist (mapcar
+                     (lambda (x) 
+                       (if (setq tmp (reftex-locate-file (nth 2 x) "tex"
+                                                         master-dir))
+                           (cons (nth 1 x) tmp)
+                         (message "Can't find external document %s"
+                                  (nth 2 x))
+                         nil))
+                     allxr))
+             (alist (delq nil alist))
+             (allprefix (delq nil (mapcar 'car alist)))
+             (regexp (if allprefix
+                         (concat "\\`\\(" 
+                                 (mapconcat 'identity allprefix "\\|")
+                                 "\\)")
+                       "\\\\\\\\\\\\")))   ; this will never match
+        (push (list 'xr alist regexp) docstruct)))
 
     (set reftex-docstruct-symbol docstruct)
     (put reftex-docstruct-symbol 'modified t)))
@@ -201,8 +201,8 @@
     (catch 'exit
       (setq file-found (reftex-locate-file file "tex" master-dir))
       (if (and (not file-found)
-	       (setq buf (reftex-get-buffer-visiting file)))
-	  (setq file-found (buffer-file-name buf)))
+               (setq buf (reftex-get-buffer-visiting file)))
+          (setq file-found (buffer-file-name buf)))
 
       (unless file-found
         (push (list 'file-error file) docstruct)
@@ -221,106 +221,106 @@
         (setq file (buffer-file-name))
         (push (list 'bof file) docstruct)
 
-	(reftex-with-special-syntax
-	 (save-excursion
-	   (save-restriction
-	     (widen)
-	     (goto-char 1)
+        (reftex-with-special-syntax
+         (save-excursion
+           (save-restriction
+             (widen)
+             (goto-char 1)
 
-	     (while (re-search-forward regexp nil t)
+             (while (re-search-forward regexp nil t)
 
-	       (cond
+               (cond
 
-		((match-end 1)
-		 ;; It is a label
-		 (push (reftex-label-info (reftex-match-string 1) file bound)
-		       docstruct))
+                ((match-end 1)
+                 ;; It is a label
+                 (push (reftex-label-info (reftex-match-string 1) file bound)
+                       docstruct))
 
-		((match-end 3)
-		 ;; It is a section
-		 (setq bound (point))
+                ((match-end 3)
+                 ;; It is a section
+                 (setq bound (point))
 
-		 ;; Insert in List
-		 (setq toc-entry (reftex-section-info file))
-		 (when toc-entry
-		   ;; It can happen that section info returns nil
-		   (setq level (nth 5 toc-entry))
-		   (setq highest-level (min highest-level level))
-		   (if (= level highest-level)
-		       (message
-			"Scanning %s %s ..."
-			(car (rassoc level reftex-section-levels-all))
-			(nth 6 toc-entry)))
+                 ;; Insert in List
+                 (setq toc-entry (reftex-section-info file))
+                 (when toc-entry
+                   ;; It can happen that section info returns nil
+                   (setq level (nth 5 toc-entry))
+                   (setq highest-level (min highest-level level))
+                   (if (= level highest-level)
+                       (message
+                        "Scanning %s %s ..."
+                        (car (rassoc level reftex-section-levels-all))
+                        (nth 6 toc-entry)))
 
-		   (push toc-entry docstruct)
-		   (setq reftex-active-toc toc-entry)))
+                   (push toc-entry docstruct)
+                   (setq reftex-active-toc toc-entry)))
 
-		((match-end 7)
-		 ;; It's an include or input
-		 (setq include-file (reftex-match-string 7))
-		 ;; Test if this file should be ignored
-		 (unless (delq nil (mapcar
-				    (lambda (x) (string-match x include-file))
-				    reftex-no-include-regexps))
-		   ;; Parse it
-		   (setq docstruct
-			 (reftex-parse-from-file
-			  include-file
-			  docstruct master-dir))))
+                ((match-end 7)
+                 ;; It's an include or input
+                 (setq include-file (reftex-match-string 7))
+                 ;; Test if this file should be ignored
+                 (unless (delq nil (mapcar 
+                                    (lambda (x) (string-match x include-file))
+                                    reftex-no-include-regexps))
+                   ;; Parse it
+                   (setq docstruct
+                         (reftex-parse-from-file
+                          include-file
+                          docstruct master-dir))))
 
-		((match-end 9)
-		 ;; Appendix starts here
-		 (reftex-init-section-numbers nil t)
-		 (push (cons 'appendix t) docstruct))
+                ((match-end 9)
+                 ;; Appendix starts here
+                 (reftex-init-section-numbers nil t)
+                 (push (cons 'appendix t) docstruct))
 
-		((match-end 10)
-		 ;; Index entry
-		 (when reftex-support-index
-		   (setq index-entry (reftex-index-info file))
-		   (when index-entry
-		     (add-to-list 'index-tags (nth 1 index-entry))
-		     (push index-entry docstruct))))
+                ((match-end 10)
+                 ;; Index entry
+                 (when reftex-support-index
+                   (setq index-entry (reftex-index-info file))
+                   (when index-entry
+                     (add-to-list 'index-tags (nth 1 index-entry))
+                     (push index-entry docstruct))))
 
-		((match-end 11)
-		 ;; A macro with label
-		 (save-excursion
-		   (let* ((mac (reftex-match-string 11))
-			  (label (progn (goto-char (match-end 11))
-					(save-match-data
-					  (reftex-no-props
-					   (reftex-nth-arg-wrapper
-					    mac)))))
-			  (typekey (nth 1 (assoc mac reftex-env-or-mac-alist)))
-			  (entry (progn (if typekey
-					    ;; A typing macro
-					    (goto-char (match-end 0))
-					  ;; A neutral macro
-					  (goto-char (match-end 11))
-					  (reftex-move-over-touching-args))
-					(reftex-label-info
-					 label file bound nil nil))))
-		     (push entry docstruct))))
-		(t (error "This should not happen (reftex-parse-from-file)")))
-	       )
+                ((match-end 11)
+                 ;; A macro with label
+                 (save-excursion
+                   (let* ((mac (reftex-match-string 11))
+                          (label (progn (goto-char (match-end 11))
+                                        (save-match-data
+                                          (reftex-no-props
+                                           (reftex-nth-arg-wrapper
+                                            mac)))))
+                          (typekey (nth 1 (assoc mac reftex-env-or-mac-alist)))
+                          (entry (progn (if typekey
+                                            ;; A typing macro
+                                            (goto-char (match-end 0))
+                                          ;; A neutral macro
+                                          (goto-char (match-end 11))
+                                          (reftex-move-over-touching-args))
+                                        (reftex-label-info
+                                         label file bound nil nil))))
+                     (push entry docstruct))))
+                (t (error "This should not happen (reftex-parse-from-file)")))
+               )
 
-	     ;; Find bibliography statement
-	     (when (setq tmp (reftex-locate-bibliography-files master-dir))
-	       (push (cons 'bib tmp) docstruct))
-
-	     (goto-char 1)
-	     (when (re-search-forward
-		    "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
-	       (push (cons 'thebib file) docstruct))
+             ;; Find bibliography statement
+             (when (setq tmp (reftex-locate-bibliography-files master-dir))
+               (push (cons 'bib tmp) docstruct))
 
-	     ;; Find external document specifications
-	     (goto-char 1)
-	     (while (re-search-forward "[\n\r][ \t]*\\\\externaldocument\\(\\[\\([^]]*\\)\\]\\)?{\\([^}]+\\)}" nil t)
-	       (push (list 'xr-doc (reftex-match-string 2)
-			   (reftex-match-string 3))
-		     docstruct))
+             (goto-char 1)
+             (when (re-search-forward 
+                    "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
+               (push (cons 'thebib file) docstruct))
+                   
+             ;; Find external document specifications
+             (goto-char 1)
+             (while (re-search-forward "[\n\r][ \t]*\\\\externaldocument\\(\\[\\([^]]*\\)\\]\\)?{\\([^}]+\\)}" nil t)
+               (push (list 'xr-doc (reftex-match-string 2)
+                           (reftex-match-string 3))
+                     docstruct))
 
-	     ;; End of file mark
-	     (push (list 'eof file) docstruct)))))
+             ;; End of file mark
+             (push (list 'eof file) docstruct)))))
 
       ;; Kill the scanned buffer
       (reftex-kill-temporary-buffers next-buf))
@@ -330,31 +330,31 @@
 
 (defun reftex-locate-bibliography-files (master-dir &optional files)
   ;; Scan buffer for bibliography macro and return file list.
-
+  
   (unless files
     (save-excursion
       (goto-char (point-min))
       (if (re-search-forward
-	   (concat
-;	    "\\(\\`\\|[\n\r]\\)[^%]*\\\\\\("
-	    "\\(^\\)[^%]*\\\\\\("
-	    (mapconcat 'identity reftex-bibliography-commands "\\|")
-	    "\\){[ \t]*\\([^}]+\\)") nil t)
-	  (setq files
-		(split-string (reftex-match-string 3)
-			      "[ \t\n\r]*,[ \t\n\r]*")))))
+           (concat
+;           "\\(\\`\\|[\n\r]\\)[^%]*\\\\\\("
+            "\\(^\\)[^%\n\r]*\\\\\\("
+            (mapconcat 'identity reftex-bibliography-commands "\\|")
+            "\\){[ \t]*\\([^}]+\\)") nil t)
+          (setq files 
+                (split-string (reftex-match-string 3)
+                              "[ \t\n\r]*,[ \t\n\r]*")))))
   (when files
-    (setq files
-	  (mapcar
-	   (lambda (x)
-	     (if (or (member x reftex-bibfile-ignore-list)
-		     (delq nil (mapcar (lambda (re) (string-match re x))
-				       reftex-bibfile-ignore-regexps)))
-		 ;; excluded file
-		 nil
-	       ;; find the file
-	       (reftex-locate-file x "bib" master-dir)))
-	   files))
+    (setq files 
+          (mapcar
+           (lambda (x)
+             (if (or (member x reftex-bibfile-ignore-list)
+                     (delq nil (mapcar (lambda (re) (string-match re x))
+                                       reftex-bibfile-ignore-regexps)))
+                 ;; excluded file
+                 nil
+               ;; find the file
+               (reftex-locate-file x "bib" master-dir)))
+           files))
     (delq nil files)))
 
 (defun reftex-replace-label-list-segment (old insert &optional entirely)
@@ -387,24 +387,24 @@
   ;; Carefull: This function expects the match-data to be still in place!
   (let* ((marker (set-marker (make-marker) (1- (match-beginning 3))))
          (macro (reftex-match-string 3))
-	 (prefix (save-match-data
-		   (if (string-match "begin{\\([^}]+\\)}" macro)
-		       (match-string 1 macro))))
-	 (level-exp (cdr (assoc macro reftex-section-levels-all)))
+         (prefix (save-match-data
+                   (if (string-match "begin{\\([^}]+\\)}" macro)
+                       (match-string 1 macro))))
+         (level-exp (cdr (assoc macro reftex-section-levels-all)))
          (level (if (symbolp level-exp)
-		    (save-match-data (funcall level-exp))
-		  level-exp))
-	 (star (= ?* (char-after (match-end 3))))
-	 (unnumbered (or star (< level 0)))
-	 (level (abs level))
+                    (save-match-data (funcall level-exp))
+                  level-exp))
+         (star (= ?* (char-after (match-end 3))))
+         (unnumbered (or star (< level 0)))
+         (level (abs level))
          (section-number (reftex-section-number level unnumbered))
-         (text1 (save-match-data
-		  (save-excursion
-		    (reftex-context-substring prefix))))
+         (text1 (save-match-data 
+                  (save-excursion
+                    (reftex-context-substring prefix))))
          (literal (buffer-substring-no-properties
                    (1- (match-beginning 3))
                    (min (point-max) (+ (match-end 0) (length text1) 1))))
-	 ;; Literal can be too short since text1 too short. No big problem.
+         ;; Literal can be too short since text1 too short. No big problem. 
          (text (reftex-nicify-text text1)))
 
     ;; Add section number and indentation
@@ -413,7 +413,7 @@
            (make-string (* reftex-level-indent level) ?\ )
            (if (nth 1 reftex-label-menu-flags) ; section number flag
                (concat section-number " "))
-	   (if prefix (concat (capitalize prefix) ": ") "")
+           (if prefix (concat (capitalize prefix) ": ") "")
            text))
     (list 'toc "toc" text file marker level section-number
           literal (marker-position marker))))
@@ -426,12 +426,12 @@
    (reftex-support-index t)
    ((y-or-n-p "Turn on index support and rescan entire document? ")
     (setq reftex-support-index 'demanded
-	  current-prefix-arg '(16)))
+          current-prefix-arg '(16)))
    (t (if abort
-	  (error "No index support")
-	(message "No index support")
-	(ding)
-	(sit-for 1)))))
+          (error "No index support")
+        (message "No index support")
+        (ding)
+        (sit-for 1)))))
 
 (defun reftex-index-info-safe (file)
   (reftex-with-special-syntax
@@ -443,49 +443,49 @@
   ;; Carefull: This function expects the match-data to be still in place!
   (catch 'exit
     (let* ((macro (reftex-match-string 10))
-	   (bom (match-beginning 10))
-	   (boa (match-end 10))
-	   (entry (or (assoc macro reftex-index-macro-alist)
-		      (throw 'exit nil)))
-	   (exclude (nth 3 entry))
-	   ;; The following is a test if this match should be excluded
-	   (test-dummy (and (fboundp exclude)
-			    (funcall exclude)
-			    (throw 'exit nil)))
-	   (itag (nth 1 entry))
-	   (prefix (nth 2 entry))
-	   (index-tag
-	    (cond ((stringp itag) itag)
-		  ((integerp itag)
-		   (progn (goto-char boa)
-			  (or (reftex-nth-arg itag (nth 6 entry)) "idx")))
-		  (t "idx")))
-	   (arg (or (progn (goto-char boa)
-			   (reftex-nth-arg (nth 5 entry) (nth 6 entry)))
-		    ""))
-	   (end-of-args (progn (goto-char boa)
-			       (reftex-move-over-touching-args)
-			       (point)))
-	   (end-of-context (progn (skip-chars-forward "^ \t\n\r") (point)))
-	   (begin-of-context
-	    (progn (goto-char bom)
-		   (skip-chars-backward "^ \t\r\n")
-		   (point)))
-	   (context (buffer-substring-no-properties
-		     begin-of-context end-of-context))
-	   (key-end (if (string-match reftex-index-key-end-re arg)
-			(1+ (match-beginning 0))))
-	   (rawkey (substring arg 0 key-end))
-
-	   (key (if prefix (concat prefix rawkey) rawkey))
-	   (sortkey (downcase key))
-	   (showkey (mapconcat 'identity
-			       (split-string key reftex-index-level-re)
-			       " ! ")))
+           (bom (match-beginning 10))
+           (boa (match-end 10))
+           (entry (or (assoc macro reftex-index-macro-alist)
+                      (throw 'exit nil)))
+           (exclude (nth 3 entry))
+           ;; The following is a test if this match should be excluded
+           (test-dummy (and (fboundp exclude)
+                            (funcall exclude)
+                            (throw 'exit nil)))
+           (itag (nth 1 entry))
+           (prefix (nth 2 entry))
+           (index-tag 
+            (cond ((stringp itag) itag)
+                  ((integerp itag)
+                   (progn (goto-char boa)
+                          (or (reftex-nth-arg itag (nth 6 entry)) "idx")))
+                  (t "idx")))
+           (arg (or (progn (goto-char boa)
+                           (reftex-nth-arg (nth 5 entry) (nth 6 entry)))
+                    ""))
+           (end-of-args (progn (goto-char boa)
+                               (reftex-move-over-touching-args)
+                               (point)))
+           (end-of-context (progn (skip-chars-forward "^ \t\n\r") (point)))
+           (begin-of-context
+            (progn (goto-char bom)
+                   (skip-chars-backward "^ \t\r\n")
+                   (point)))
+           (context (buffer-substring-no-properties
+                     begin-of-context end-of-context))
+           (key-end (if (string-match reftex-index-key-end-re arg)
+                        (1+ (match-beginning 0))))
+           (rawkey (substring arg 0 key-end))
+                              
+           (key (if prefix (concat prefix rawkey) rawkey))
+           (sortkey (downcase key))
+           (showkey (mapconcat 'identity 
+                               (split-string key reftex-index-level-re)
+                               " ! ")))
       (goto-char end-of-args)
       ;;       0        1       2      3   4   5  6      7       8      9
       (list 'index index-tag context file bom arg key showkey sortkey key-end))))
-
+  
 (defun reftex-short-context (env parse &optional bound derive)
   ;; Get about one line of useful context for the label definition at point.
 
@@ -516,9 +516,9 @@
                    (match-string 1 (nth 7 reftex-active-toc)))
                "SECTION HEADING NOT FOUND")))
        (save-excursion
-	 (goto-char reftex-default-context-position)
-	 (unless (eq (string-to-char env) ?\\)
-	   (reftex-move-over-touching-args))
+         (goto-char reftex-default-context-position)
+         (unless (eq (string-to-char env) ?\\)
+           (reftex-move-over-touching-args))
          (reftex-context-substring))))
 
     ((stringp parse)
@@ -593,7 +593,7 @@
                          ((looking-at (reftex-make-regexp-allow-for-ctrl-m
                                        (nth 7 (car list))))
                           ;; Same title: remember, but keep looking
-			  (setq rtn-if-no-other (car list)))))
+                          (setq rtn-if-no-other (car list)))))
                     (pop list))
                   rtn1))
                ((match-end 7)
@@ -601,35 +601,35 @@
                 (car
                  (member (list 'eof (reftex-locate-file
                                      (reftex-match-string 7) "tex"
-				     (cdr (assq 'master-dir docstruct))))
+                                     (cdr (assq 'master-dir docstruct))))
                          docstruct)))
-	       ((match-end 9)
-		(assq 'appendix (symbol-value reftex-docstruct-symbol)))
-	       ((match-end 10)
-		;; Index entry
-		(when reftex-support-index
-		  (let* ((index-info (save-excursion
-				       (reftex-index-info-safe nil)))
-			 (list (member (list 'bof (buffer-file-name))
-				       docstruct))
-			 (endelt (car (member (list 'eof (buffer-file-name))
-					      list)))
-			 dist last-dist last (n 0))
-		    ;; Check all index entries with equal text
-		    (while (and list (not (eq endelt (car list))))
-		      (when (and (eq (car (car list)) 'index)
-				 (string= (nth 2 index-info)
-					  (nth 2 (car list))))
-			(incf n)
-			(setq dist (abs (- (point) (nth 4 (car list)))))
-			(if (or (not last-dist) (< dist last-dist))
-			    (setq last-dist dist last (car list))))
-		      (setq list (cdr list)))
-		    ;; We are sure if we have only one, or a zero distance
-		    (cond ((or (= n 1) (= dist 0)) last)
-			  ((> n 1) (setq cnt 2) last)
-			  (t nil)))))
-	       ((match-end 11)
+               ((match-end 9)
+                (assq 'appendix (symbol-value reftex-docstruct-symbol)))
+               ((match-end 10)
+                ;; Index entry
+                (when reftex-support-index
+                  (let* ((index-info (save-excursion 
+                                       (reftex-index-info-safe nil)))
+                         (list (member (list 'bof (buffer-file-name))
+                                       docstruct))
+                         (endelt (car (member (list 'eof (buffer-file-name))
+                                              list)))
+                         dist last-dist last (n 0))
+                    ;; Check all index entries with equal text
+                    (while (and list (not (eq endelt (car list))))
+                      (when (and (eq (car (car list)) 'index)
+                                 (string= (nth 2 index-info) 
+                                          (nth 2 (car list))))
+                        (incf n)
+                        (setq dist (abs (- (point) (nth 4 (car list)))))
+                        (if (or (not last-dist) (< dist last-dist))
+                            (setq last-dist dist last (car list))))
+                      (setq list (cdr list)))
+                    ;; We are sure if we have only one, or a zero distance
+                    (cond ((or (= n 1) (equal dist 0)) last)
+                          ((> n 1) (setq cnt 2) last)
+                          (t nil)))))
+               ((match-end 11)
                 (save-excursion
                   (goto-char (match-end 11))
                   (assoc (reftex-no-props
@@ -641,88 +641,88 @@
     ;; Check if there was only a by-name match for the section.
     (when (and (not rtn) rtn-if-no-other)
       (setq rtn rtn-if-no-other
-	    cnt 2))
+            cnt 2))
     (cons rtn (eq cnt 1))))
 
 (defun reftex-notice-new (&optional n force)
   "Hook to handshake with RefTeX after something new has been inserted."
   ;; Add a new entry to the docstruct list.  If it is a section, renumber
   ;; the following sections.
-  ;; FIXME:  Put in a WHAT parameter
+  ;; FIXME:  Put in a WHAT parameter and search backward until one is found.
   ;; When N is given, go back that many matches of reftex-everything-regexp
   ;; When FORCE is non-nil, also insert if `reftex-where-am-I' was uncertain.
   (condition-case nil
       (catch 'exit
-	(unless reftex-mode (throw 'exit nil))
-	(reftex-access-scan-info)
-	(let* ((docstruct (symbol-value reftex-docstruct-symbol))
-	       here-I-am appendix tail entry star level
-	       section-number context)
+        (unless reftex-mode (throw 'exit nil))
+        (reftex-access-scan-info)
+        (let* ((docstruct (symbol-value reftex-docstruct-symbol))
+               here-I-am appendix tail entry star level
+               section-number context)
 
      (save-excursion
        (when (re-search-backward (reftex-everything-regexp) nil t (or n 1))
 
-	 ;; Find where we are
-	 (setq here-I-am (reftex-where-am-I))
-	 (or here-I-am (throw 'exit nil))
-	 (unless (or force (cdr here-I-am)) (throw 'exit nil))
-	 (setq tail (memq (car here-I-am) docstruct))
-	 (or tail (throw 'exit nil))
-	 (setq reftex-active-toc (reftex-last-assoc-before-elt
-				  'toc (car here-I-am) docstruct)
-	       appendix (reftex-last-assoc-before-elt
-			 'appendix (car here-I-am) docstruct))
+         ;; Find where we are
+         (setq here-I-am (reftex-where-am-I))
+         (or here-I-am (throw 'exit nil))
+         (unless (or force (cdr here-I-am)) (throw 'exit nil))
+         (setq tail (memq (car here-I-am) docstruct))
+         (or tail (throw 'exit nil))
+         (setq reftex-active-toc (reftex-last-assoc-before-elt
+                                  'toc (car here-I-am) docstruct)
+               appendix (reftex-last-assoc-before-elt
+                         'appendix (car here-I-am) docstruct))
 
-	 ;; Initialize section numbers
-	 (if (eq (car (car here-I-am)) 'appendix)
-	     (reftex-init-section-numbers nil t)
-	   (reftex-init-section-numbers reftex-active-toc appendix))
+         ;; Initialize section numbers
+         (if (eq (car (car here-I-am)) 'appendix)
+             (reftex-init-section-numbers nil t)
+           (reftex-init-section-numbers reftex-active-toc appendix))
 
-	 ;; Match the section command
-	 (when (re-search-forward (reftex-everything-regexp) nil t)
-	   (cond
-	    ((match-end 1)
-	     (push (reftex-label-info (reftex-match-string 1) buffer-file-name)
-		   (cdr tail)))
-
-	    ((match-end 3)
-	     (setq star (= ?* (char-after (match-end 3)))
-		   entry (reftex-section-info (buffer-file-name))
-		   level (nth 5 entry))
-	     ;; Insert the section info
-	     (push entry (cdr tail))
+         ;; Match the section command
+         (when (re-search-forward (reftex-everything-regexp) nil t)
+           (cond
+            ((match-end 1)
+             (push (reftex-label-info (reftex-match-string 1) buffer-file-name)
+                   (cdr tail)))
 
-	     ;; We are done unless we use section numbers
-	     (unless (nth 1 reftex-label-menu-flags) (throw 'exit nil))
+            ((match-end 3)
+             (setq star (= ?* (char-after (match-end 3)))
+                   entry (reftex-section-info (buffer-file-name))
+                   level (nth 5 entry))
+             ;; Insert the section info
+             (push entry (cdr tail))
+             
+             ;; We are done unless we use section numbers
+             (unless (nth 1 reftex-label-menu-flags) (throw 'exit nil))
 
-	     ;; Update the remaining toc items
-	     (setq tail (cdr tail))
-	     (while (and (setq tail (memq (assq 'toc (cdr tail)) tail))
-			 (setq entry (car tail))
-			 (>= (nth 5 entry) level))
-	       (setq star (string-match "\\*" (nth 6 entry))
-		     context (nth 2 entry)
-		     section-number
-		     (reftex-section-number (nth 5 entry) star))
-	       (when (string-match "\\`\\([ \t]*\\)\\([.0-9A-Z]+\\)\\(.*\\)"
-				   context)
-		 (when (and (not appendix)
-			    (>= (string-to-char (match-string 2)) ?A))
-		   ;; Just entered the appendex.  Get out.
-		   (throw 'exit nil))
+             ;; Update the remaining toc items
+             (setq tail (cdr tail))
+             (while (and (setq tail (memq (assq 'toc (cdr tail)) tail))
+                         (setq entry (car tail))
+                         (>= (nth 5 entry) level))
+               (setq star (string-match "\\*" (nth 6 entry))
+                     context (nth 2 entry)
+                     section-number
+                     (reftex-section-number (nth 5 entry) star))
+               (when (string-match "\\`\\([ \t]*\\)\\([.0-9A-Z]+\\)\\(.*\\)"
+                                   context)
+                 (when (and (not appendix)
+                            (>= (string-to-char (match-string 2)) ?A))
+                   ;; Just entered the appendex.  Get out.
+                   (throw 'exit nil))
 
-		 ;; Change the section number.
-		 (setf (nth 2 entry)
-		       (concat (match-string 1 context)
-			       section-number
-			       (match-string 3 context))))))
-	    ((match-end 10)
-	     ;; Index entry
-	     (and reftex-support-index
-		  (setq entry (reftex-index-info-safe buffer-file-name))
-		  ;; FIXME: (add-to-list 'index-tags (nth 1 index-entry))
-		  (push entry (cdr tail))))))))))
-
+                 ;; Change the section number.
+                 (setf (nth 2 entry)
+                       (concat (match-string 1 context)
+                               section-number
+                               (match-string 3 context))))))
+            ((match-end 10)
+             ;; Index entry
+             (and reftex-support-index
+                  (setq entry (reftex-index-info-safe buffer-file-name))
+                  ;; FIXME: (add-to-list 'index-tags (nth 1 index-entry))
+                  (push entry (cdr tail))))))))))
+            
     (error nil))
   )
 
@@ -736,8 +736,8 @@
    ((memq (preceding-char) '(?\] ?\})))
    ;; Do a search
    ((and reftex-allow-detached-macro-args
-	 (re-search-backward
-	  "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\=" bound t))
+         (re-search-backward
+          "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\=" bound t))
     (goto-char (1+ (match-beginning 0)))
     t)
    (t nil)))
@@ -774,7 +774,7 @@
           pos cmd-list cmd cnt cnt-opt entry)
       (save-restriction
         (save-excursion
-          (narrow-to-region (max (point-min) bound) (point-max))
+          (narrow-to-region (max 1 bound) (point-max))
           ;; move back out of the current parenthesis
           (while (condition-case nil
                      (progn (up-list -1) t)
@@ -782,29 +782,29 @@
             (setq cnt 1 cnt-opt 0)
             ;; move back over any touching sexps
             (while (and (reftex-move-to-previous-arg bound)
-			(condition-case nil
-			    (progn (backward-sexp) t)
-			  (error nil)))
-	      (if (eq (following-char) ?\[) (incf cnt-opt))
+                        (condition-case nil
+                            (progn (backward-sexp) t)
+                          (error nil)))
+              (if (eq (following-char) ?\[) (incf cnt-opt))
               (incf cnt))
             (setq pos (point))
             (when (and (or (= (following-char) ?\[)
                            (= (following-char) ?\{))
                        (re-search-backward "\\\\[*a-zA-Z]+\\=" nil t))
               (setq cmd (reftex-match-string 0))
-	      (when (looking-at "\\\\begin{[^}]*}")
-		(setq cmd (reftex-match-string 0)
-		      cnt (1- cnt)))
-	      ;; This does ignore optional arguments.  Very hard to fix.
-	      (when (setq entry (assoc cmd reftex-env-or-mac-alist))
-		(if (> cnt (or (nth 4 entry) 100))
-		    (setq cmd nil)))
+              (when (looking-at "\\\\begin{[^}]*}")
+                (setq cmd (reftex-match-string 0)
+                      cnt (1- cnt)))
+              ;; This does ignore optional arguments.  Very hard to fix.
+              (when (setq entry (assoc cmd reftex-env-or-mac-alist))
+                (if (> cnt (or (nth 4 entry) 100))
+                    (setq cmd nil)))
               (cond
-	       ((null cmd))
-	       ((eq t which)
-		(push (cons cmd (point)) cmd-list))
-	       ((or (eq 1 which) (member cmd which))
-		(throw 'exit (cons cmd (point))))))
+               ((null cmd))
+               ((eq t which)
+                (push (cons cmd (point)) cmd-list))
+               ((or (eq 1 which) (member cmd which))
+                (throw 'exit (cons cmd (point))))))
             (goto-char pos)))
         (nreverse cmd-list)))))
 
@@ -837,7 +837,7 @@
                      (match-beginning 2) (match-end 2)))
           (cond
            ((string= (match-string 1) "end")
-	    (push env end-list))
+            (push env end-list))
            ((equal env (car end-list))
             (setq end-list (cdr end-list)))
            ((eq t which)
@@ -867,25 +867,25 @@
       (let ((bound (or bound (save-excursion (re-search-backward
                                               reftex-section-regexp nil 1)
                                              (point))))
-	    (fun-list (if (listp which)
-			  (mapcar (lambda (x) (if (memq x which) x nil))
-				  reftex-special-env-parsers)
-			reftex-special-env-parsers))
+            (fun-list (if (listp which)
+                          (mapcar (lambda (x) (if (memq x which) x nil))
+                                  reftex-special-env-parsers)
+                        reftex-special-env-parsers))
             specials rtn)
-	;; Call all functions
-	(setq specials (mapcar
-			(lambda (fun)
-			  (save-excursion
-			    (setq rtn (and fun (funcall fun bound)))
-			    (if rtn (cons (symbol-name fun) rtn) nil)))
-			fun-list))
-	;; Delete the non-matches
-	(setq specials (delq nil specials))
-	;; Sort
-	(setq specials (sort specials (lambda (a b) (> (cdr a) (cdr b)))))
-	(if (eq which t)
-	    specials
-	  (car specials))))))
+        ;; Call all functions
+        (setq specials (mapcar 
+                        (lambda (fun)
+                          (save-excursion
+                            (setq rtn (and fun (funcall fun bound)))
+                            (if rtn (cons (symbol-name fun) rtn) nil)))
+                        fun-list))
+        ;; Delete the non-matches
+        (setq specials (delq nil specials))
+        ;; Sort
+        (setq specials (sort specials (lambda (a b) (> (cdr a) (cdr b)))))
+        (if (eq which t) 
+            specials
+          (car specials))))))
 
 (defsubst reftex-move-to-next-arg (&optional ignore)
   ;; Assuming that we are at the end of a macro name or a macro argument,
@@ -897,7 +897,7 @@
    ((memq (following-char) '(?\[ ?\{)))
    ;; Do a search
    ((and reftex-allow-detached-macro-args
-	 (looking-at "[ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*[[{]"))
+         (looking-at "[ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*[[{]"))
     (goto-char (1- (match-end 0)))
     t)
    (t nil)))
@@ -916,39 +916,39 @@
   (if (= n 1000)
       ;; Special case:  Skip all touching arguments
       (progn
-	(reftex-move-over-touching-args)
-	(reftex-context-substring))
+        (reftex-move-over-touching-args)
+        (reftex-context-substring))
 
     ;; Do the real thing.
     (let ((cnt 1))
-
+      
       (when (reftex-move-to-next-arg)
+        
+        (while (< cnt n)
+          (while (and (member cnt opt-args)
+                      (eq (following-char) ?\{))
+            (incf cnt))
+          (when (< cnt n)
+            (unless (and (condition-case nil
+                             (or (forward-list 1) t)
+                           (error nil))
+                         (reftex-move-to-next-arg)
+                         (incf cnt))
+              (setq cnt 1000))))
 
-	(while (< cnt n)
-	  (while (and (member cnt opt-args)
-		      (eq (following-char) ?\{))
-	    (incf cnt))
-	  (when (< cnt n)
-	    (unless (and (condition-case nil
-			     (or (forward-list 1) t)
-			   (error nil))
-			 (reftex-move-to-next-arg)
-			 (incf cnt))
-	      (setq cnt 1000))))
-
-	(while (and (memq cnt opt-args)
-		    (eq (following-char) ?\{))
-	  (incf cnt)))
+        (while (and (memq cnt opt-args)
+                    (eq (following-char) ?\{))
+          (incf cnt)))
       (if (and (= n cnt)
-	       (> (skip-chars-forward "{\\[") 0))
-	  (reftex-context-substring)
-	nil))))
+               (> (skip-chars-forward "{\\[") 0))
+          (reftex-context-substring)
+        nil))))
 
 (defun reftex-move-over-touching-args ()
   (condition-case nil
       (while (memq (following-char) '(?\[ ?\{))
-	(forward-list 1))
-    (error nil)))
+        (forward-list 1))
+    (error nil)))  
 
 (defun reftex-context-substring (&optional to-end)
   ;; Return up to 150 chars from point
@@ -959,11 +959,11 @@
     (buffer-substring-no-properties
      (point)
      (min (+ (point) 150)
-	  (save-match-data
-	    ;; FIXME: THis is not perfect
-	    (if (re-search-forward "\\\\end{" nil t)
-		(match-beginning 0)
-	      (point-max))))))
+          (save-match-data
+            ;; FIXME: This is not perfect
+            (if (re-search-forward "\\\\end{" nil t)
+                (match-beginning 0)
+              (point-max))))))
    ((or (= (preceding-char) ?\{)
         (= (preceding-char) ?\[))
     ;; Inside a list - get only the list.
@@ -978,8 +978,8 @@
             (error (point-max))))))
    (t
     ;; no list - just grab 150 characters
-    (buffer-substring-no-properties (point)
-				    (min (+ (point) 150) (point-max))))))
+    (buffer-substring-no-properties (point) 
+                                    (min (+ (point) 150) (point-max))))))
 
 ;; Variable holding the vector with section numbers
 (defvar reftex-section-numbers (make-vector reftex-max-section-depth 0))
@@ -994,11 +994,11 @@
     (while (>= i 0)
       (if (> i level)
           (aset reftex-section-numbers i 0)
-	(setq number-string (or (car numbers) "0"))
-	(if (string-match "\\`[A-Z]\\'" number-string)
-	    (aset reftex-section-numbers i
-		  (- (string-to-char number-string) ?A -1))
-	    (aset reftex-section-numbers i (string-to-int number-string)))
+        (setq number-string (or (car numbers) "0"))
+        (if (string-match "\\`[A-Z]\\'" number-string)
+            (aset reftex-section-numbers i
+                  (- (string-to-char number-string) ?A -1))
+            (aset reftex-section-numbers i (string-to-int number-string)))
         (pop numbers))
       (decf i)))
   (put 'reftex-section-numbers 'appendix appendix))
@@ -1007,65 +1007,65 @@
   ;; Return a string with the current section number.
   ;; When LEVEL is non-nil, increase section numbers on that level.
   (let* ((depth (1- (length reftex-section-numbers))) idx n (string "")
-	 (appendix (get 'reftex-section-numbers 'appendix))
-	 (partspecial (and (not reftex-part-resets-chapter)
-			   (equal level 0))))
+         (appendix (get 'reftex-section-numbers 'appendix))
+         (partspecial (and (not reftex-part-resets-chapter)
+                           (equal level 0))))
     ;; partspecial means, this is a part statement.
     ;; Parts do not reset the chapter counter, and the part number is
     ;; not included in the numbering of other sectioning levels.
     (when level
       (when (and (> level -1) (not star))
-        (aset reftex-section-numbers
-	      level (1+ (aref reftex-section-numbers level))))
+        (aset reftex-section-numbers 
+              level (1+ (aref reftex-section-numbers level))))
       (setq idx (1+ level))
       (when (not star)
-	(while (<= idx depth)
-	  (if (or (not partspecial)
-		  (not (= idx 1)))
-	      (aset reftex-section-numbers idx 0))
-	  (incf idx))))
+        (while (<= idx depth)
+          (if (or (not partspecial)
+                  (not (= idx 1)))
+              (aset reftex-section-numbers idx 0))
+          (incf idx))))
     (if partspecial
-	(setq string (concat "Part " (reftex-roman-number
-				      (aref reftex-section-numbers 0))))
+        (setq string (concat "Part " (reftex-roman-number
+                                      (aref reftex-section-numbers 0))))
       (setq idx (if reftex-part-resets-chapter 0 1))
       (while (<= idx depth)
-	(setq n (aref reftex-section-numbers idx))
-	(if (not (and partspecial (not (equal string ""))))
-	    (setq string (concat string (if (not (string= string "")) "." "")
-				 (int-to-string n))))
-	(incf idx))
+        (setq n (aref reftex-section-numbers idx))
+        (if (not (and partspecial (not (equal string ""))))
+            (setq string (concat string (if (not (string= string "")) "." "")
+                                 (int-to-string n))))
+        (incf idx))
       (save-match-data
-	(if (string-match "\\`\\([@0]\\.\\)+" string)
-	    (setq string (replace-match "" nil nil string)))
-	(if (string-match "\\(\\.0\\)+\\'" string)
-	    (setq string (replace-match "" nil nil string)))
-	(if (and appendix
-		 (string-match "\\`[0-9]+" string))
-	    (setq string
-		  (concat
-		   (char-to-string
-		    (1- (+ ?A (string-to-int (match-string 0 string)))))
-		   (substring string (match-end 0))))))
+        (if (string-match "\\`\\([@0]\\.\\)+" string)
+            (setq string (replace-match "" nil nil string)))
+        (if (string-match "\\(\\.0\\)+\\'" string)
+            (setq string (replace-match "" nil nil string)))
+        (if (and appendix
+                 (string-match "\\`[0-9]+" string))
+            (setq string 
+                  (concat
+                   (char-to-string
+                    (1- (+ ?A (string-to-int (match-string 0 string)))))
+                   (substring string (match-end 0))))))
       (if star
-	  (concat (make-string (1- (length string)) ?\ ) "*")
-	string))))
+          (concat (make-string (1- (length string)) ?\ ) "*")
+        string))))
 
 (defun reftex-roman-number (n)
   ;; Return as a string the roman number equal to N.
   (let ((nrest n)
-	(string "")
-	(list '((1000 . "M") ( 900 . "CM") ( 500 . "D") ( 400 . "CD")
-		( 100 . "C") (  90 . "XC") (  50 . "L") (  40 . "XL")
-		(  10 . "X") (   9 . "IX") (   5 . "V") (   4 . "IV")
-		(   1 . "I")))
-	listel i s)
+        (string "")
+        (list '((1000 . "M") ( 900 . "CM") ( 500 . "D") ( 400 . "CD")
+                ( 100 . "C") (  90 . "XC") (  50 . "L") (  40 . "XL")
+                (  10 . "X") (   9 . "IX") (   5 . "V") (   4 . "IV")
+                (   1 . "I")))
+        listel i s)
     (while (>= nrest 1)
       (setq listel (pop list)
-	    i (car listel)
-	    s (cdr listel))
+            i (car listel)
+            s (cdr listel))
       (while (>= nrest i)
-	(setq string (concat string s)
-	      nrest (- nrest i))))
+        (setq string (concat string s)
+              nrest (- nrest i))))
     string))
 
 ;;; reftex-parse.el ends here
--- a/lisp/textmodes/reftex-ref.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-ref.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-ref.el --- code to create labels and references with RefTeX
-;; Copyright (c) 1997, 1998, 1999, 2000, 2003  Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 
 ;; This file is part of GNU Emacs.
 
@@ -36,11 +36,11 @@
 
   (let* ((loc1 (reftex-what-macro reftex-label-mac-list bound))
          (loc2 (reftex-what-environment reftex-label-env-list bound))
-	 (loc3 (reftex-what-special-env 1 bound))
+         (loc3 (reftex-what-special-env 1 bound))
          (p1 (or (cdr loc1) 0))
          (p2 (or (cdr loc2) 0))
-	 (p3 (or (cdr loc3) 0))
-	 (pmax (max p1 p2 p3)))
+         (p3 (or (cdr loc3) 0))
+         (pmax (max p1 p2 p3)))
 
     (setq reftex-location-start pmax)
     (cond
@@ -57,9 +57,9 @@
       (setq reftex-default-context-position p3)
       (setq loc3 (car loc3))
       (cond ((null loc3) "section")
-	    ((symbolp loc3) (symbol-name loc3))
-	    ((stringp loc3) loc3)
-	    (t "section")))
+            ((symbolp loc3) (symbol-name loc3))
+            ((stringp loc3) loc3)
+            (t "section")))
      (t ;; This should not happen, I think?
       "section"))))
 
@@ -83,11 +83,11 @@
           (goto-char 1)
 
           (if (or (re-search-forward
-		   (format reftex-find-label-regexp-format
-			   (regexp-quote label)) nil t)
-		  (re-search-forward
-		   (format reftex-find-label-regexp-format2
-			   (regexp-quote label)) nil t))
+                   (format reftex-find-label-regexp-format
+                           (regexp-quote label)) nil t)
+                  (re-search-forward
+                   (format reftex-find-label-regexp-format2
+                           (regexp-quote label)) nil t))
 
               (progn
                 (backward-char 1)
@@ -102,7 +102,7 @@
          (parse (nth 2 (assoc env-or-mac reftex-env-or-mac-alist)))
          (text (reftex-short-context env-or-mac parse reftex-location-start
                                      derive))
-	 (in-comment (reftex-in-comment)))
+         (in-comment (reftex-in-comment)))
     (list label typekey text file in-comment)))
 
 ;;; Creating labels ---------------------------------------------------------
@@ -132,18 +132,18 @@
   ;; Ok, go ahead.
   (catch 'exit
     (let* ((entry (assoc environment reftex-env-or-mac-alist))
-	   (typekey (nth 1 entry))
-	   (format (nth 3 entry))
-	   (macro-cell (reftex-what-macro 1))
-	   (entry1 (assoc (car macro-cell) reftex-env-or-mac-alist))
-	   label naked prefix valid default force-prompt rescan-is-useful)
+           (typekey (nth 1 entry))
+           (format (nth 3 entry))
+           (macro-cell (reftex-what-macro 1))
+           (entry1 (assoc (car macro-cell) reftex-env-or-mac-alist))
+           label naked prefix valid default force-prompt rescan-is-useful)
       (when (and (or (nth 5 entry) (nth 5 entry1))
-		 (memq (preceding-char) '(?\[ ?\{)))
-	;; This is an argument of a label macro.  Insert naked label.
-	(setq naked t format "%s"))
+                 (memq (preceding-char) '(?\[ ?\{)))
+        ;; This is an argument of a label macro.  Insert naked label.
+        (setq naked t format "%s"))
 
       (setq prefix (or (cdr (assoc typekey reftex-typekey-to-prefix-alist))
-		       (concat typekey "-")))
+                       (concat typekey "-")))
       ;; Replace any escapes in the prefix
       (setq prefix (reftex-replace-prefix-escapes prefix))
 
@@ -151,115 +151,115 @@
       (cond
 
        ((reftex-typekey-check typekey (nth 0 reftex-insert-label-flags))
-	;; Derive a label from context.
-	(setq reftex-active-toc (reftex-last-assoc-before-elt
-				 'toc (car (reftex-where-am-I))
-				 (symbol-value reftex-docstruct-symbol)))
-	(setq default (reftex-no-props
-		       (nth 2 (reftex-label-info " " nil nil t))))
-	;; Catch the cases where the is actually no context available.
-	(if (or (string-match "NO MATCH FOR CONTEXT REGEXP" default)
-		(string-match "ILLEGAL VALUE OF PARSE" default)
-		(string-match "SECTION HEADING NOT FOUND" default)
-		(string-match "HOOK ERROR" default)
-		(string-match "^[ \t]*$" default))
-	    (setq default prefix
-		  force-prompt t)	; need to prompt
-	  (setq default
-		(concat prefix
-			(funcall reftex-string-to-label-function default)))
+        ;; Derive a label from context.
+        (setq reftex-active-toc (reftex-last-assoc-before-elt
+                                 'toc (car (reftex-where-am-I))
+                                 (symbol-value reftex-docstruct-symbol)))
+        (setq default (reftex-no-props
+                       (nth 2 (reftex-label-info " " nil nil t))))
+        ;; Catch the cases where the is actually no context available.
+        (if (or (string-match "NO MATCH FOR CONTEXT REGEXP" default)
+                (string-match "ILLEGAL VALUE OF PARSE" default)
+                (string-match "SECTION HEADING NOT FOUND" default)
+                (string-match "HOOK ERROR" default)
+                (string-match "^[ \t]*$" default))
+            (setq default prefix
+                  force-prompt t)       ; need to prompt
+          (setq default 
+                (concat prefix 
+                        (funcall reftex-string-to-label-function default)))
 
-	  ;; Make it unique.
-	  (setq default (reftex-uniquify-label default nil "-"))))
+          ;; Make it unique.
+          (setq default (reftex-uniquify-label default nil "-"))))
 
        ((reftex-typekey-check typekey (nth 1 reftex-insert-label-flags))
-	;; Minimal default: the user will be prompted.
-	(setq default prefix))
+        ;; Minimal default: the user will be prompted.
+        (setq default prefix))
 
        (t
-	;; Make an automatic label.
-	(setq default (reftex-uniquify-label prefix t))))
+        ;; Make an automatic label.
+        (setq default (reftex-uniquify-label prefix t))))
 
       ;; Should we ask the user?
       (if (or (reftex-typekey-check typekey
-				    (nth 1 reftex-insert-label-flags)) ; prompt
-	      force-prompt)
+                                    (nth 1 reftex-insert-label-flags)) ; prompt
+              force-prompt)
 
-	  (while (not valid)
-	    ;; iterate until we get a legal label
+          (while (not valid)
+            ;; iterate until we get a legal label
 
-	    (setq label (read-string
-			 (if naked "Naked Label: " "Label: ")
-			 default))
+            (setq label (read-string
+                         (if naked "Naked Label: " "Label: ")
+                         default))
 
-	    ;; Lets make sure that this is a legal label
-	    (cond
+            ;; Lets make sure that this is a legal label
+            (cond
 
-	     ((string-match (concat "\\`\\(" (regexp-quote prefix)
-				    "\\)?[ \t]*\\'")
-			    label)
-	      ;; No label at all, please
-	      (message "No label inserted.")
-	      (throw 'exit nil))
+             ((string-match (concat "\\`\\(" (regexp-quote prefix)
+                                    "\\)?[ \t]*\\'")
+                            label)
+              ;; No label at all, please
+              (message "No label inserted.")
+              (throw 'exit nil))
 
-	     ;; Test if label contains strange characters
-	     ((string-match reftex-label-illegal-re label)
-	      (message "Label \"%s\" contains illegal characters" label)
-	      (ding)
-	      (sit-for 2))
+             ;; Test if label contains strange characters
+             ((string-match reftex-label-illegal-re label)
+              (message "Label \"%s\" contains illegal characters" label)
+              (ding)
+              (sit-for 2))
 
-	     ;; Look it up in the label list
-	     ((setq entry (assoc label
-				 (symbol-value reftex-docstruct-symbol)))
-	      (ding)
-	      (if (y-or-n-p
-		   (format "Label '%s' exists. Use anyway? " label))
-		  (setq valid t)))
+             ;; Look it up in the label list
+             ((setq entry (assoc label
+                                 (symbol-value reftex-docstruct-symbol)))
+              (ding)
+              (if (y-or-n-p 
+                   (format "Label '%s' exists. Use anyway? " label))
+                  (setq valid t)))
 
-	     ;; Label is ok
-	     (t
-	      (setq valid t))))
-	(setq label default))
+             ;; Label is ok
+             (t
+              (setq valid t))))
+        (setq label default))
 
       ;; Insert the label into the label list
-      (let* ((here-I-am-info
-	      (save-excursion
-		(if (and (or naked no-insert)
-			 (integerp (cdr macro-cell)))
-		    (goto-char (cdr macro-cell)))
-		(reftex-where-am-I)))
-	     (here-I-am (car here-I-am-info))
-	     (note (if (cdr here-I-am-info)
-		       ""
-		     "POSITION UNCERTAIN.  RESCAN TO FIX."))
-	     (file (buffer-file-name))
-	     (text nil)
-	     (tail (memq here-I-am (symbol-value reftex-docstruct-symbol))))
+      (let* ((here-I-am-info 
+              (save-excursion
+                (if (and (or naked no-insert) 
+                         (integerp (cdr macro-cell)))
+                    (goto-char (cdr macro-cell)))
+                (reftex-where-am-I)))
+             (here-I-am (car here-I-am-info))
+             (note (if (cdr here-I-am-info)
+                       ""
+                     "POSITION UNCERTAIN.  RESCAN TO FIX."))
+             (file (buffer-file-name))
+             (text nil)
+             (tail (memq here-I-am (symbol-value reftex-docstruct-symbol))))
 
-	(or (cdr here-I-am-info) (setq rescan-is-useful t))
+        (or (cdr here-I-am-info) (setq rescan-is-useful t))
 
-	(when tail
-	  (push (list label typekey text file nil note) (cdr tail))
-	  (put reftex-docstruct-symbol 'modified t)))
+        (when tail
+          (push (list label typekey text file nil note) (cdr tail))
+          (put reftex-docstruct-symbol 'modified t)))
 
       ;; Insert the label into the buffer
       (unless no-insert
-	(insert
-	 (if reftex-format-label-function
-	     (funcall reftex-format-label-function label format)
-	   (format format label)))
-	(if (and reftex-plug-into-AUCTeX
-		 (fboundp 'LaTeX-add-labels))
-	    ;; Tell AUCTeX about this
-	    (LaTeX-add-labels label)))
+        (insert
+         (if reftex-format-label-function
+             (funcall reftex-format-label-function label format)
+           (format format label)))
+        (if (and reftex-plug-into-AUCTeX
+                 (fboundp 'LaTeX-add-labels))
+            ;; Tell AUCTeX about this
+            (LaTeX-add-labels label)))
 
       ;; Delete the corresponding selection buffers to force update on next use.
       (when reftex-auto-update-selection-buffers
-	(reftex-erase-buffer (reftex-make-selection-buffer-name typekey))
-	(reftex-erase-buffer (reftex-make-selection-buffer-name " ")))
+        (reftex-erase-buffer (reftex-make-selection-buffer-name typekey))
+        (reftex-erase-buffer (reftex-make-selection-buffer-name " ")))
 
       (when (and rescan-is-useful reftex-allow-automatic-rescan)
-	(reftex-parse-one))
+        (reftex-parse-one))
 
       ;; return value of the function is the label
       label)))
@@ -269,24 +269,24 @@
 Uses `reftex-derive-label-parameters' and `reftex-label-illegal-re'.  It
 also applies `reftex-translate-to-ascii-function' to the string."
   (when (and reftex-translate-to-ascii-function
-	     (fboundp reftex-translate-to-ascii-function))
+             (fboundp reftex-translate-to-ascii-function))
     (setq string (funcall reftex-translate-to-ascii-function string)))
   (apply 'reftex-convert-string string
-	 "[-~ \t\n\r,;]+" reftex-label-illegal-re nil nil
-	 reftex-derive-label-parameters))
+         "[-~ \t\n\r,;]+" reftex-label-illegal-re nil nil
+         reftex-derive-label-parameters))
 
 (defun reftex-latin1-to-ascii (string)
   ;; Translate the upper 128 chars in the Latin-1 charset to ASCII equivalents
   (let ((tab "@@@@@@@@@@@@@@@@@@'@@@@@@@@@@@@@ icLxY|S\"ca<--R-o|23'uq..1o>423?AAAAAAACEEEEIIIIDNOOOOOXOUUUUYP3aaaaaaaceeeeiiiidnooooo:ouuuuypy")
-	(emacsp (not (featurep 'xemacs))))
-    (mapconcat
+        (emacsp (not (featurep 'xemacs))))
+    (mapconcat 
      (lambda (c)
        (cond ((and (> c 127) (< c 256))                 ; 8 bit Latin-1
-	      (char-to-string (aref tab (- c 128))))
-	     ((and emacsp                               ; Not for XEmacs
-		   (> c 2175) (< c 2304))               ; Mule Latin-1
-	      (char-to-string (aref tab (- c 2176))))
-	     (t (char-to-string c))))
+              (char-to-string (aref tab (- c 128))))
+             ((and emacsp                               ; Not for XEmacs
+                   (> c 2175) (< c 2304))               ; Mule Latin-1
+              (char-to-string (aref tab (- c 2176))))
+             (t (char-to-string c))))
      string "")))
 
 (defun reftex-replace-prefix-escapes (prefix)
@@ -309,21 +309,21 @@
                     file)))
                ((equal letter "u")
                 (or (user-login-name) ""))
-	       ((equal letter "S")
-		(let* (macro level-exp level)
-		  (save-excursion
-		    (save-match-data
-		      (when (re-search-backward reftex-section-regexp nil t)
-			(setq macro (reftex-match-string 2)
-			      level-exp (cdr (assoc macro reftex-section-levels-all))
-			      level (if (symbolp level-exp)
-					(abs (save-match-data
-					       (funcall level-exp)))
-				      (abs level-exp))))
-		      (cdr (or (assoc macro reftex-section-prefixes)
-			       (assoc level reftex-section-prefixes)
-			       (assq t reftex-section-prefixes)
-			       (list t "sec:")))))))
+               ((equal letter "S")
+                (let* (macro level-exp level)
+                  (save-excursion
+                    (save-match-data
+                      (when (re-search-backward reftex-section-regexp nil t)
+                        (setq macro (reftex-match-string 2)
+                              level-exp (cdr (assoc macro reftex-section-levels-all))
+                              level (if (symbolp level-exp)
+                                        (abs (save-match-data
+                                               (funcall level-exp)))
+                                      (abs level-exp))))
+                      (cdr (or (assoc macro reftex-section-prefixes)
+                               (assoc level reftex-section-prefixes)
+                               (assq t reftex-section-prefixes)
+                               (list t "sec:")))))))
                (t "")))
         (setq num (1- (+ (match-beginning 1) (length replace)))
               prefix (replace-match replace nil nil prefix)))
@@ -396,40 +396,40 @@
   ;; check for active recursive edits
   (reftex-check-recursive-edit)
 
-  ;; Ensure access to scanning info and rescan buffer if prefix arg is '(4)
+  ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
   (reftex-access-scan-info current-prefix-arg)
 
   (unless type
     ;; guess type from context
     (if (and reftex-guess-label-type
              (setq type (reftex-guess-label-type)))
-	(setq cut (cdr type)
-	      type (car type))
+        (setq cut (cdr type)
+              type (car type))
       (setq type (reftex-query-label-type))))
 
-  (let* ((refstyle
-	  (cond ((reftex-typekey-check type reftex-vref-is-default) "\\vref")
-		((reftex-typekey-check type reftex-fref-is-default) "\\fref")
-		(t "\\ref")))
-	 (reftex-format-ref-function reftex-format-ref-function)
-	 (form "\\ref{%s}")
-	 label labels sep sep1)
+  (let* ((refstyle 
+          (cond ((reftex-typekey-check type reftex-vref-is-default) "\\vref")
+                ((reftex-typekey-check type reftex-fref-is-default) "\\fref")
+                (t "\\ref")))
+         (reftex-format-ref-function reftex-format-ref-function)
+         (form "\\ref{%s}")
+         label labels sep sep1)
 
     ;; Have the user select a label
     (set-marker reftex-select-return-marker (point))
     (setq labels (save-excursion
-		   (reftex-offer-label-menu type)))
+                   (reftex-offer-label-menu type)))
     (reftex-ensure-compiled-variables)
     (set-marker reftex-select-return-marker nil)
     ;; If the first entry is the symbol 'concat, concat all labels.
     ;; We keep the cdr of the first label for typekey etc information.
     (if (eq (car labels) 'concat)
-	(setq labels (list (list (mapconcat 'car (cdr labels) ",")
-				 (cdr (nth 1 labels))))))
+        (setq labels (list (list (mapconcat 'car (cdr labels) ",")
+                                 (cdr (nth 1 labels))))))
     (setq type (nth 1 (car labels))
-	  form (or (cdr (assoc type reftex-typekey-to-format-alist))
-		   form))
-
+          form (or (cdr (assoc type reftex-typekey-to-format-alist))
+                   form))
+    
     (cond
      (no-insert
       ;; Just return the first label
@@ -439,60 +439,60 @@
       nil)
      (t
       (while labels
-	(setq label (car (car labels))
-	      sep (nth 2 (car labels))
-	      sep1 (cdr (assoc sep reftex-multiref-punctuation))
-	      labels (cdr labels))
-	(when cut
-	  (backward-delete-char cut)
-	  (setq cut nil))
+        (setq label (car (car labels))
+              sep (nth 2 (car labels))
+              sep1 (cdr (assoc sep reftex-multiref-punctuation))
+              labels (cdr labels))
+        (when cut 
+          (backward-delete-char cut)
+          (setq cut nil))
 
-	;; remove ~ if we do already have a space
-	(when (and (= ?~ (string-to-char form))
-		   (member (preceding-char) '(?\  ?\t ?\n)))
-	  (setq form (substring form 1)))
-	;; do we have a special format?
-	(setq reftex-format-ref-function
-	      (cond
-	       ((string= refstyle "\\vref") 'reftex-format-vref)
-	       ((string= refstyle "\\fref") 'reftex-format-fref)
-	       ((string= refstyle "\\Fref") 'reftex-format-Fref)
-	       (t reftex-format-ref-function)))
-	;; ok, insert the reference
-	(if sep1 (insert sep1))
-	(insert
-	 (if reftex-format-ref-function
-	     (funcall reftex-format-ref-function label form)
-	   (format form label label)))
-	;; take out the initial ~ for good
-	(and (= ?~ (string-to-char form))
-	     (setq form (substring form 1))))
+        ;; remove ~ if we do already have a space
+        (when (and (= ?~ (string-to-char form))
+                   (member (preceding-char) '(?\ ?\t ?\n ?. ?~)))
+          (setq form (substring form 1)))
+        ;; do we have a special format?
+        (setq reftex-format-ref-function
+              (cond
+               ((string= refstyle "\\vref") 'reftex-format-vref)
+               ((string= refstyle "\\fref") 'reftex-format-fref)
+               ((string= refstyle "\\Fref") 'reftex-format-Fref)
+               (t reftex-format-ref-function)))
+        ;; ok, insert the reference
+        (if sep1 (insert sep1))
+        (insert
+         (if reftex-format-ref-function
+             (funcall reftex-format-ref-function label form)
+           (format form label label)))
+        ;; take out the initial ~ for good
+        (and (= ?~ (string-to-char form))
+             (setq form (substring form 1))))
       (message "")
       label))))
 
 (defun reftex-guess-label-type ()
   ;; Examine context to guess what a \ref might want to reference.
   (let ((words reftex-words-to-typekey-alist)
-	(case-fold-search t)
-	(bound (max (point-min) (- (point) 35)))
-	matched	cell)
+        (case-fold-search t)
+        (bound (max (point-min) (- (point) 35)))
+        matched cell)
     (save-excursion
       (while (and (setq cell (pop words))
-		  (not (setq matched
-			     (re-search-backward (car cell) bound t))))))
+                  (not (setq matched 
+                             (re-search-backward (car cell) bound t))))))
     (if matched
-	(cons (cdr cell) (- (match-end 0) (match-end 1)))
+        (cons (cdr cell) (- (match-end 0) (match-end 1)))
       nil)))
 
 (defvar reftex-select-label-map)
 (defun reftex-offer-label-menu (typekey)
   ;; Offer a menu with the appropriate labels.
   (let* ((buf (current-buffer))
-	 (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
-	 (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
-	 (xr-index 0)
+         (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
+         (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
+         (xr-index 0)
          (here-I-am (car (reftex-where-am-I)))
-	 (here-I-am1 here-I-am)
+         (here-I-am1 here-I-am)
          (toc (reftex-typekey-check typekey reftex-label-menu-flags 0))
          (files (reftex-typekey-check typekey reftex-label-menu-flags 7))
          (context (not (reftex-typekey-check
@@ -502,158 +502,158 @@
          (follow  (reftex-typekey-check
                    typekey reftex-label-menu-flags 4))
          (commented (nth 5 reftex-label-menu-flags))
-	 (prefix "")
-	 selection-buffers
+         (prefix "")
+         selection-buffers
          offset rtn key data last-data entries)
 
     (unwind-protect
         (catch 'exit
           (while t
             (save-window-excursion
-	      (delete-other-windows)
-	      (setq reftex-call-back-to-this-buffer buf
-		    reftex-latex-syntax-table (syntax-table))
-	      (let ((default-major-mode 'reftex-select-label-mode))
-		(if reftex-use-multiple-selection-buffers
-		    (switch-to-buffer-other-window
-		     (save-excursion
-		       (set-buffer buf)
-		       (reftex-make-selection-buffer-name typekey)))
-		  (switch-to-buffer-other-window "*RefTeX Select*")
-		  (reftex-erase-buffer)))
-	      (unless (eq major-mode 'reftex-select-label-mode)
-		(reftex-select-label-mode))
-	      (add-to-list 'selection-buffers (current-buffer))
+              (delete-other-windows)
+              (setq reftex-call-back-to-this-buffer buf
+                    reftex-latex-syntax-table (syntax-table))
+              (let ((default-major-mode 'reftex-select-label-mode))
+                (if reftex-use-multiple-selection-buffers
+                    (switch-to-buffer-other-window
+                     (save-excursion
+                       (set-buffer buf)
+                       (reftex-make-selection-buffer-name typekey)))
+                  (switch-to-buffer-other-window "*RefTeX Select*")
+                  (reftex-erase-buffer)))
+              (unless (eq major-mode 'reftex-select-label-mode)
+                (reftex-select-label-mode))
+              (add-to-list 'selection-buffers (current-buffer))
               (setq truncate-lines t)
-	      (setq mode-line-format
-		    (list "----  " 'mode-line-buffer-identification
-			  "  " 'global-mode-string "   (" mode-name ")"
-			  "  S<" 'refstyle ">"
-			  " -%-"))
-	      (cond
-	       ((= 0 (buffer-size))
-		(let ((buffer-read-only nil))
-		  (message "Creating Selection Buffer...")
-		  (setq offset (reftex-insert-docstruct
-				buf
-				toc
-				typekey
-				nil ; index
-				files
-				context
-				counter
-				commented
-				(or here-I-am offset)
-				prefix
-				nil  ; no a toc buffer
-				))))
-	       (here-I-am
-		(setq offset (reftex-get-offset buf here-I-am typekey)))
-	       (t (setq offset t)))
-	      (setq buffer-read-only t)
-	      (setq offset (or offset t))
+              (setq mode-line-format
+                    (list "----  " 'mode-line-buffer-identification
+                          "  " 'global-mode-string "   (" mode-name ")"
+                          "  S<" 'refstyle ">"
+                          " -%-"))
+              (cond
+               ((= 0 (buffer-size))
+                (let ((buffer-read-only nil))
+                  (message "Creating Selection Buffer...")
+                  (setq offset (reftex-insert-docstruct
+                                buf
+                                toc
+                                typekey
+                                nil ; index
+                                files
+                                context
+                                counter
+                                commented
+                                (or here-I-am offset) 
+                                prefix
+                                nil  ; no a toc buffer 
+                                ))))
+               (here-I-am
+                (setq offset (reftex-get-offset buf here-I-am typekey)))
+               (t (setq offset t)))
+              (setq buffer-read-only t)
+              (setq offset (or offset t))
 
               (setq here-I-am nil) ; turn off determination of offset
               (setq rtn
                     (reftex-select-item
                      reftex-select-label-prompt
                      reftex-select-label-help
-		     reftex-select-label-map
+                     reftex-select-label-map
                      offset
                      'reftex-show-label-location follow))
               (setq key       (car rtn)
                     data      (nth 1 rtn)
                     last-data (nth 2 rtn)
-		    offset    t)
+                    offset    t)
               (unless key (throw 'exit nil))
               (cond
-	       ((eq key ?g)
-		;; update buffer
-		(reftex-erase-buffer))
+               ((eq key ?g)
+                ;; update buffer
+                (reftex-erase-buffer))
                ((or (eq key ?r)
                     (eq key ?R))
                 ;; rescan buffer
-		(and current-prefix-arg (setq key ?R))
-		(reftex-erase-buffer)
+                (and current-prefix-arg (setq key ?R))
+                (reftex-erase-buffer)
                 (reftex-reparse-document buf last-data key))
                ((eq key ?c)
                 ;; toggle context mode
-		(reftex-erase-buffer)
+                (reftex-erase-buffer)
                 (setq context (not context)))
                ((eq key ?s)
                 ;; switch type
-		(setq here-I-am here-I-am1)
+                (setq here-I-am here-I-am1)
                 (setq typekey (reftex-query-label-type)))
                ((eq key ?t)
                 ;; toggle table of contents display, or change depth
-		(reftex-erase-buffer)
-		(if current-prefix-arg
-		    (setq reftex-toc-max-level (prefix-numeric-value
-						current-prefix-arg))
-		  (setq toc (not toc))))
+                (reftex-erase-buffer)
+                (if current-prefix-arg
+                    (setq reftex-toc-max-level (prefix-numeric-value
+                                                current-prefix-arg))
+                  (setq toc (not toc))))
                ((eq key ?F)
                 ;; toggle display of included file borders
-		(reftex-erase-buffer)
+                (reftex-erase-buffer)
                 (setq files (not files)))
                ((eq key ?#)
                 ;; toggle counter display
-		(reftex-erase-buffer)
+                (reftex-erase-buffer)
                 (setq counter (not counter)))
                ((eq key ?%)
                 ;; toggle display of commented labels
-		(reftex-erase-buffer)
+                (reftex-erase-buffer)
                 (setq commented (not commented)))
                ((eq key ?l)
                 ;; reuse the last referenced label again
                 (setq entries reftex-last-used-reference)
                 (throw 'exit t))
-	       ((eq key ?x)
-		;; select an external document
-		(setq xr-index (reftex-select-external-document
-				xr-alist xr-index))
-		(setq buf (or (reftex-get-file-buffer-force
-			       (cdr (nth xr-index xr-alist)))
-			      (error "Cannot switch document"))
-		      prefix (or (car (nth xr-index xr-alist)) ""))
-		(set-buffer buf)
-		(reftex-access-scan-info))
-	       ((stringp key)
-		(setq entries
-		      (list
-		       (list
-			(or (assoc key (symbol-value reftex-docstruct-symbol))
-			    (list key typekey)))))
-		(throw 'exit t))
-	       ((memq key '(?a ?A return))
-		(cond
-		 (reftex-select-marked
-		  (setq entries (nreverse reftex-select-marked)))
-		 (data
-		  (setq entries (list (list data))))
-		 (t (setq entries nil)))
-		(when entries
-		  (if (equal key ?a) (push 'concat entries))
-		  (setq reftex-last-used-reference entries))
+               ((eq key ?x)
+                ;; select an external document
+                (setq xr-index (reftex-select-external-document
+                                xr-alist xr-index))
+                (setq buf (or (reftex-get-file-buffer-force
+                               (cdr (nth xr-index xr-alist)))
+                              (error "Cannot switch document"))
+                      prefix (or (car (nth xr-index xr-alist)) ""))
+                (set-buffer buf)
+                (reftex-access-scan-info))
+               ((stringp key)
+                (setq entries
+                      (list
+                       (list
+                        (or (assoc key (symbol-value reftex-docstruct-symbol))
+                            (list key typekey)))))
+                (throw 'exit t))
+               ((memq key '(?a ?A return))
+                (cond
+                 (reftex-select-marked
+                  (setq entries (nreverse reftex-select-marked)))
+                 (data
+                  (setq entries (list (list data))))
+                 (t (setq entries nil)))
+                (when entries
+                  (if (equal key ?a) (push 'concat entries))
+                  (setq reftex-last-used-reference entries))
                 (set-buffer buf)
                 (throw 'exit t))
-	       (t (error "This should not happen (reftex-offer-label-menu)"))))))
+               (t (error "This should not happen (reftex-offer-label-menu)"))))))
       (save-excursion
-	(while reftex-buffers-with-changed-invisibility
-	  (set-buffer (car (car reftex-buffers-with-changed-invisibility)))
-	  (setq buffer-invisibility-spec
-		(cdr (pop reftex-buffers-with-changed-invisibility)))))
+        (while reftex-buffers-with-changed-invisibility
+          (set-buffer (car (car reftex-buffers-with-changed-invisibility)))
+          (setq buffer-invisibility-spec 
+                (cdr (pop reftex-buffers-with-changed-invisibility)))))
       (mapcar (lambda (buf) (and (buffer-live-p buf) (bury-buffer buf)))
-	      selection-buffers)
+              selection-buffers)
       (reftex-kill-temporary-buffers))
     ;; Add the prefixes, put together the relevant information in the form
     ;; (LABEL TYPEKEY SEPARATOR) and return a list of those.
     (mapcar (lambda (x)
-	      (if (listp x)
-		  (list (concat prefix (car (car x)))
-			(nth 1 (car x))
-			(nth 2 x))
-		x))
-	    entries)))
+              (if (listp x)
+                  (list (concat prefix (car (car x)))
+                        (nth 1 (car x))
+                        (nth 2 x))
+                x))
+            entries)))
 
 (defun reftex-reparse-document (&optional buffer data key)
   ;; Rescan the document.
@@ -669,14 +669,14 @@
 
 (defun reftex-query-label-type ()
   ;; Ask for label type
-  (let ((key (reftex-select-with-char
-	      reftex-type-query-prompt reftex-type-query-help 3)))
+  (let ((key (reftex-select-with-char 
+              reftex-type-query-prompt reftex-type-query-help 3)))
     (unless (member (char-to-string key) reftex-typekey-list)
       (error "No such label type: %s" (char-to-string key)))
     (char-to-string key)))
 
-(defun reftex-show-label-location (data forward no-revisit
-					&optional stay error)
+(defun reftex-show-label-location (data forward no-revisit 
+                                        &optional stay error)
   ;; View the definition site of a label in another window.
   ;; DATA is an entry from the docstruct list.
   ;; FORWARD indicates if the label is likely forward from current point.
@@ -685,53 +685,53 @@
   ;; ERROR means throw an error exception when the label cannot be found.
   ;; If ERROR is nil, the return value of this function indicates success.
   (let* ((this-window (selected-window))
-	 (errorf (if error 'error 'message))
+         (errorf (if error 'error 'message))
          label file buffer re found)
 
     (catch 'exit
       (setq label (nth 0 data)
-	    file  (nth 3 data))
+            file  (nth 3 data))
 
       (unless file
-	(funcall errorf "Unknown label - reparse might help")
-	(throw 'exit nil))
+        (funcall errorf "Unknown label - reparse might help")
+        (throw 'exit nil))
 
       ;; Goto the file in another window
-      (setq buffer
-	    (if no-revisit
-		(reftex-get-buffer-visiting file)
-	      (reftex-get-file-buffer-force
-	       file (not reftex-keep-temporary-buffers))))
+      (setq buffer 
+            (if no-revisit
+                (reftex-get-buffer-visiting file)
+              (reftex-get-file-buffer-force
+               file (not reftex-keep-temporary-buffers))))
       (if buffer
           ;; good - the file is available
           (switch-to-buffer-other-window buffer)
         ;; we have got a problem here.  The file does not exist.
         ;; Let' get out of here..
-	(funcall errorf "Label %s not found" label)
-	(throw 'exit nil))
+        (funcall errorf "Label %s not found" label)
+        (throw 'exit nil))
 
       ;; search for that label
       (setq re (format reftex-find-label-regexp-format (regexp-quote label)))
       (setq found
-	    (if forward
-		(re-search-forward re nil t)
-	      (re-search-backward re nil t)))
+            (if forward
+                (re-search-forward re nil t)
+              (re-search-backward re nil t)))
       (unless found
         (goto-char (point-min))
-	(unless (setq found (re-search-forward re nil t))
-	  ;; Ooops.  Must be in a macro with distributed args.
-	  (setq found
-		(re-search-forward
-		 (format reftex-find-label-regexp-format2
-			 (regexp-quote label)) nil t))))
+        (unless (setq found (re-search-forward re nil t))
+          ;; Ooops.  Must be in a macro with distributed args.
+          (setq found
+                (re-search-forward
+                 (format reftex-find-label-regexp-format2
+                         (regexp-quote label)) nil t))))
       (if (match-end 3)
-	  (progn
-	    (reftex-highlight 0 (match-beginning 3) (match-end 3))
-	    (reftex-show-entry (match-beginning 3) (match-end 3))
-	    (recenter '(4))
-	    (unless stay (select-window this-window)))
-	(select-window this-window)
-	(funcall errorf "Label %s not found" label))
+          (progn
+            (reftex-highlight 0 (match-beginning 3) (match-end 3))
+            (reftex-show-entry (match-beginning 3) (match-end 3))
+            (recenter '(4))
+            (unless stay (select-window this-window)))
+        (select-window this-window)
+        (funcall errorf "Label %s not found" label))
       found)))
 
 (defvar font-lock-mode)
@@ -744,34 +744,34 @@
                 (re-search-forward  "[\n\r]" nil 1 n) (point))))
     (cond
      ((and (boundp 'buffer-invisibility-spec) buffer-invisibility-spec
-	   (get-char-property (1+ beg-hlt) 'invisible))
+           (get-char-property (1+ beg-hlt) 'invisible))
       ;; Invisible with text properties.  That is easy to change.
       (push (cons (current-buffer) buffer-invisibility-spec)
-	    reftex-buffers-with-changed-invisibility)
+            reftex-buffers-with-changed-invisibility)
       (setq buffer-invisibility-spec nil))
      ((string-match "\r" (buffer-substring beg end))
       ;; Invisible with selective display.  We need to copy it.
       (let ((string (buffer-substring-no-properties beg end)))
-	(switch-to-buffer "*RefTeX Context Copy*")
-	(setq buffer-read-only nil)
-	(erase-buffer)
-	(insert string)
-	(subst-char-in-region (point-min) (point-max) ?\r ?\n t)
-	(goto-char (- beg-hlt beg))
-	(reftex-highlight 0 (1+ (- beg-hlt beg)) (1+ (- end-hlt beg)))
-	(if (reftex-refontify)
-	    (when (or (not (eq major-mode 'latex-mode))
-		      (not font-lock-mode))
-	      (latex-mode)
-	      (run-hook-with-args
-	       'reftex-pre-refontification-functions
-	       reftex-call-back-to-this-buffer 'reftex-hidden)
-	      (turn-on-font-lock))
-	  (when (or (not (eq major-mode 'fundamental-mode))
-		    font-lock-mode)
-	    (fundamental-mode)))
-	(run-hooks 'reftex-display-copied-context-hook)
-	(setq buffer-read-only t))))))
+        (switch-to-buffer "*RefTeX Context Copy*")
+        (setq buffer-read-only nil)
+        (erase-buffer)
+        (insert string)
+        (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
+        (goto-char (- beg-hlt beg))
+        (reftex-highlight 0 (1+ (- beg-hlt beg)) (1+ (- end-hlt beg)))
+        (if (reftex-refontify)
+            (when (or (not (eq major-mode 'latex-mode))
+                      (not font-lock-mode))
+              (latex-mode)
+              (run-hook-with-args 
+               'reftex-pre-refontification-functions
+               reftex-call-back-to-this-buffer 'reftex-hidden)
+              (turn-on-font-lock))
+          (when (or (not (eq major-mode 'fundamental-mode))
+                    font-lock-mode)
+            (fundamental-mode)))
+        (run-hooks 'reftex-display-copied-context-hook)
+        (setq buffer-read-only t))))))
 
 (defun reftex-varioref-vref ()
   "Insert a reference using the `\\vref' macro from the varioref package."
@@ -782,15 +782,15 @@
   "Insert a reference using the `\\fref' macro from the fancyref package."
   (interactive)
   (let ((reftex-format-ref-function 'reftex-format-fref)
-	;;(reftex-guess-label-type nil) ;FIXME do we want this????
-	)
+        ;;(reftex-guess-label-type nil) ;FIXME do we want this????
+        )
     (reftex-reference)))
 (defun reftex-fancyref-Fref ()
   "Insert a reference using the `\\Fref' macro from the fancyref package."
   (interactive)
   (let ((reftex-format-ref-function 'reftex-format-Fref)
-	;;(reftex-guess-label-type nil) ;FIXME do we want this????
-	)
+        ;;(reftex-guess-label-type nil) ;FIXME do we want this????
+        )
     (reftex-reference)))
 
 (defun reftex-format-vref (label fmt)
@@ -802,34 +802,23 @@
 (defun reftex-format-fref (label def-fmt)
   (format "\\fref{%s}" label))
 
-
-;(defun reftex-goto-label ()
-;  (interactive)
-;  (reftex-access-scan-info)
-;  (let* ((docstruct (symbol-value reftex-docstruct-symbol))
-;	 (label (completing-read "Label: " docstruct
-;				 (lambda (x) (stringp (car x))) t))
-;	 (selection (assoc label docstruct)))
-;    (reftex-show-label-location selection t nil 'stay)
-;    (reftex-unhighlight 0)))
-
 (defun reftex-goto-label (&optional other-window)
   "Prompt for a label (with completion) and jump to the location of this label.
 Optional prefix argument OTHER-WINDOW goes to the label in another window."
   (interactive "P")
   (reftex-access-scan-info)
   (let* ((wcfg (current-window-configuration))
-	 (docstruct (symbol-value reftex-docstruct-symbol))
-	 (label (completing-read "Label: " docstruct
-				 (lambda (x) (stringp (car x))) t))
-	 (selection (assoc label docstruct))
-	 (where (progn
-		  (reftex-show-label-location selection t nil 'stay)
-		  (point-marker))))
+         (docstruct (symbol-value reftex-docstruct-symbol))
+         (label (completing-read "Label: " docstruct
+                                 (lambda (x) (stringp (car x))) t))
+         (selection (assoc label docstruct))
+         (where (progn
+                  (reftex-show-label-location selection t nil 'stay)
+                  (point-marker))))
     (unless other-window
       (set-window-configuration wcfg)
       (switch-to-buffer (marker-buffer where))
-      (goto-char where))
+      (goto-char where))      
     (reftex-unhighlight 0)))
 
 
--- a/lisp/textmodes/reftex-sel.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-sel.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-sel.el --- the selection modes for RefTeX
-;; Copyright (c) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 
 ;; This file is part of GNU Emacs.
 
@@ -38,7 +38,7 @@
 (defun reftex-select-label-mode ()
   "Major mode for selecting a label in a LaTeX document.
 This buffer was created with RefTeX.
-It only has a meaningful keymap when you are in the middle of a
+It only has a meaningful keymap when you are in the middle of a 
 selection process.
 To select a label, move the cursor to it and press RET.
 Press `?' for a summary of important key bindings.
@@ -54,7 +54,7 @@
     (make-local-hook 'pre-command-hook)
     (make-local-hook 'post-command-hook))
   (setq major-mode 'reftex-select-label-mode
-	mode-name "LSelect")
+        mode-name "LSelect")
   (set (make-local-variable 'reftex-select-marked) nil)
   (when (syntax-table-p reftex-latex-syntax-table)
     (set-syntax-table reftex-latex-syntax-table))
@@ -69,7 +69,7 @@
 (defun reftex-select-bib-mode ()
   "Major mode for selecting a citation key in a LaTeX document.
 This buffer was created with RefTeX.
-It only has a meaningful keymap when you are in the middle of a
+It only has a meaningful keymap when you are in the middle of a 
 selection process.
 In order to select a citation, move the cursor to it and press RET.
 Press `?' for a summary of important key bindings.
@@ -84,7 +84,7 @@
     (make-local-hook 'pre-command-hook)
     (make-local-hook 'post-command-hook))
   (setq major-mode 'reftex-select-bib-mode
-	mode-name "BSelect")
+        mode-name "BSelect")
   (set (make-local-variable 'reftex-select-marked) nil)
   ;; We do not set a local map - reftex-select-item does this.
   (run-hooks 'reftex-select-bib-mode-hook))
@@ -99,18 +99,18 @@
 ;;;       (set-buffer buf)
 ;;;       (reftex-access-scan-info)
 ;;;       (let* ((rest (memq here-am-I (symbol-value reftex-docstruct-symbol)))
-;;; 	     entry)
-;;; 	(while (setq entry (pop rest))
-;;; 	  (if (or (and typekey
-;;; 		       (stringp (car entry))
-;;; 		       (or (equal typekey " ")
-;;; 			   (equal typekey (nth 1 entry))))
-;;; 		  (and toc (eq (car entry) 'toc))
-;;; 		  (and index (eq (car entry) 'index))
-;;; 		  (and file
-;;; 		       (memq (car entry) '(bof eof file-error))))
-;;; 	      (throw 'exit entry)))
-;;; 	nil))))
+;;;          entry)
+;;;     (while (setq entry (pop rest))
+;;;       (if (or (and typekey
+;;;                    (stringp (car entry))
+;;;                    (or (equal typekey " ")
+;;;                        (equal typekey (nth 1 entry))))
+;;;               (and toc (eq (car entry) 'toc))
+;;;               (and index (eq (car entry) 'index))
+;;;               (and file
+;;;                    (memq (car entry) '(bof eof file-error))))
+;;;           (throw 'exit entry)))
+;;;     nil))))
 
 (defun reftex-get-offset (buf here-am-I &optional typekey toc index file)
   ;; Find the correct offset data, like insert-docstruct would, but faster.
@@ -122,24 +122,24 @@
       (set-buffer buf)
       (reftex-access-scan-info)
       (let* ((rest (symbol-value reftex-docstruct-symbol))
-	     lastentry entry)
-	(while (setq entry (pop rest))
-	  (if (or (and typekey
-		       (stringp (car entry))
-		       (or (equal typekey " ")
-			   (equal typekey (nth 1 entry))))
-		  (and toc (eq (car entry) 'toc))
-		  (and index (eq (car entry) 'index))
-		  (and file
-		       (memq (car entry) '(bof eof file-error))))
-	      (setq lastentry entry))
-	  (if (eq entry here-am-I)
-	      (throw 'exit (or lastentry entry))))
-	nil))))
+             lastentry entry)
+        (while (setq entry (pop rest))
+          (if (or (and typekey
+                       (stringp (car entry))
+                       (or (equal typekey " ")
+                           (equal typekey (nth 1 entry))))
+                  (and toc (eq (car entry) 'toc))
+                  (and index (eq (car entry) 'index))
+                  (and file
+                       (memq (car entry) '(bof eof file-error))))
+              (setq lastentry entry))
+          (if (eq entry here-am-I)
+              (throw 'exit (or lastentry entry))))
+        nil))))
 
 (defun reftex-insert-docstruct
   (buf toc labels index-entries files context counter show-commented
-	    here-I-am xr-prefix toc-buffer)
+            here-I-am xr-prefix toc-buffer)
   ;; Insert an excerpt of the docstruct list.
   ;; Return the data property of the entry corresponding to HERE-I-AM.
   ;; BUF is the buffer which has the correct docstruct-symbol.
@@ -163,18 +163,18 @@
          (context-indent
           (concat ".   "
                   (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
-	 (mouse-face
-	  (if (memq reftex-highlight-selection '(mouse both))
-	      reftex-mouse-selected-face
-	    nil))
-	 (label-face (reftex-verified-face reftex-label-face
-					   'font-lock-constant-face
-					   'font-lock-reference-face))
-	 (index-face (reftex-verified-face reftex-index-face
-					   'font-lock-constant-face
-					   'font-lock-reference-face))
+         (mouse-face
+          (if (memq reftex-highlight-selection '(mouse both))
+              reftex-mouse-selected-face
+            nil))
+         (label-face (reftex-verified-face reftex-label-face
+                                           'font-lock-constant-face
+                                           'font-lock-reference-face))
+         (index-face (reftex-verified-face reftex-index-face
+                                           'font-lock-constant-face
+                                           'font-lock-reference-face))
          all cell text label typekey note comment master-dir-re
-	 prev-inserted offset from to index-tag docstruct-symbol)
+         prev-inserted offset from to index-tag docstruct-symbol)
 
     ;; Pop to buffer buf to get the correct buffer-local variables
     (save-excursion
@@ -184,7 +184,7 @@
       (reftex-access-scan-info)
 
       (setq docstruct-symbol reftex-docstruct-symbol
-	    all (symbol-value reftex-docstruct-symbol)
+            all (symbol-value reftex-docstruct-symbol)
             reftex-active-toc nil
             master-dir-re
             (concat "\\`" (regexp-quote
@@ -192,7 +192,7 @@
 
     (set (make-local-variable 'reftex-docstruct-symbol) docstruct-symbol)
     (set (make-local-variable 'reftex-prefix)
-	 (cdr (assoc labels reftex-typekey-to-prefix-alist)))
+         (cdr (assoc labels reftex-typekey-to-prefix-alist)))
     (if (equal reftex-prefix " ") (setq reftex-prefix nil))
 
     ;; Walk the docstruct and insert the appropriate stuff
@@ -204,14 +204,14 @@
       (cond
 
        ((memq (car cell) '(bib thebib label-numbers appendix
-			       master-dir bibview-cache is-multi xr xr-doc)))
+                               master-dir bibview-cache is-multi xr xr-doc)))
        ;; These are currently ignored
 
        ((memq (car cell) '(bof eof file-error))
         ;; Beginning or end of a file
         (when files
-	  (setq prev-inserted cell)
-;	  (if (eq offset 'attention) (setq offset cell))
+          (setq prev-inserted cell)
+;         (if (eq offset 'attention) (setq offset cell))
           (insert
            " File " (if (string-match master-dir-re (nth 1 cell))
                    (substring (nth 1 cell) (match-end 0))
@@ -219,41 +219,41 @@
            (cond ((eq (car cell) 'bof) " starts here\n")
                  ((eq (car cell) 'eof) " ends here\n")
                  ((eq (car cell) 'file-error) " was not found\n")))
-	  (setq to (point))
+          (setq to (point))
           (when font
             (put-text-property from to
                                'face reftex-file-boundary-face))
-	  (when toc-buffer
-	    (if mouse-face
-		(put-text-property from (1- to)
-				   'mouse-face mouse-face))
-	    (put-text-property from to :data cell))))
+          (when toc-buffer
+            (if mouse-face
+                (put-text-property from (1- to)
+                                   'mouse-face mouse-face))
+            (put-text-property from to :data cell))))
 
        ((eq (car cell) 'toc)
         ;; a table of contents entry
         (when (and toc
-		   (<= (nth 5 cell) reftex-toc-max-level))
-	  (setq prev-inserted cell)
-;	  (if (eq offset 'attention) (setq offset cell))
+                   (<= (nth 5 cell) reftex-toc-max-level))
+          (setq prev-inserted cell)
+;         (if (eq offset 'attention) (setq offset cell))
           (setq reftex-active-toc cell)
           (insert (concat toc-indent (nth 2 cell) "\n"))
-	  (setq to (point))
-	  (when font
-	    (put-text-property from to
-			       'face reftex-section-heading-face))
-	  (when toc-buffer
-	    (if mouse-face
-		(put-text-property from (1- to)
-				   'mouse-face mouse-face))
-	    (put-text-property from to :data cell))
-	  (goto-char to)))
+          (setq to (point))
+          (when font
+            (put-text-property from to
+                               'face reftex-section-heading-face))
+          (when toc-buffer
+            (if mouse-face
+                (put-text-property from (1- to)
+                                   'mouse-face mouse-face))
+            (put-text-property from to :data cell))
+          (goto-char to)))
 
        ((stringp (car cell))
         ;; a label
         (when (null (nth 2 cell))
           ;; No context yet.  Quick update.
-	  (setcdr cell (cdr (reftex-label-info-update cell)))
-	  (put docstruct-symbol 'modified t))
+          (setcdr cell (cdr (reftex-label-info-update cell)))
+          (put docstruct-symbol 'modified t))
 
         (setq label   (car cell)
               typekey (nth 1 cell)
@@ -262,27 +262,27 @@
               note    (nth 5 cell))
 
         (when (and labels
-		   (or (eq labels t)
-		       (string= typekey labels)
-		       (string= labels " "))
+                   (or (eq labels t) 
+                       (string= typekey labels)
+                       (string= labels " "))
                    (or show-commented (null comment)))
 
           ;; Yes we want this one
           (incf cnt)
-	  (setq prev-inserted cell)
-;	  (if (eq offset 'attention) (setq offset cell))
+          (setq prev-inserted cell)
+;         (if (eq offset 'attention) (setq offset cell))
 
-	  (setq label (concat xr-prefix label))
+          (setq label (concat xr-prefix label))
           (when comment (setq label (concat "% " label)))
           (insert label-indent label)
           (when font
-	    (setq to (point))
+            (setq to (point))
             (put-text-property
              (- (point) (length label)) to
              'face (if comment
                        'font-lock-comment-face
                      label-face))
-	    (goto-char to))
+            (goto-char to))
 
           (insert (if counter (format " (%d) " cnt) "")
                   (if comment " LABEL IS COMMENTED OUT " "")
@@ -294,46 +294,46 @@
             (insert context-indent text "\n")
             (setq to (point)))
           (put-text-property from to :data cell)
-	  (when mouse-face
-	    (put-text-property from (1- to)
-			       'mouse-face mouse-face))
+          (when mouse-face
+            (put-text-property from (1- to)
+                               'mouse-face mouse-face))   
           (goto-char to)))
 
        ((eq (car cell) 'index)
-	;; index entry
-	(when (and index-entries
-		   (or (eq t index-entries)
-		       (string= index-entries (nth 1 cell))))
-	  (setq prev-inserted cell)
-;	  (if (eq offset 'attention) (setq offset cell))
-	  (setq index-tag (format "<%s>" (nth 1 cell)))
-	  (and font
-	       (put-text-property 0 (length index-tag)
-				  'face reftex-index-tag-face index-tag))
-	  (insert label-indent index-tag " " (nth 7 cell))
+        ;; index entry
+        (when (and index-entries
+                   (or (eq t index-entries)
+                       (string= index-entries (nth 1 cell))))
+          (setq prev-inserted cell)
+;         (if (eq offset 'attention) (setq offset cell))
+          (setq index-tag (format "<%s>" (nth 1 cell)))
+          (and font
+               (put-text-property 0 (length index-tag)
+                                  'face reftex-index-tag-face index-tag))
+          (insert label-indent index-tag " " (nth 7 cell))
 
-	  (when font
-	    (setq to (point))
-	    (put-text-property
-	     (- (point) (length (nth 7 cell))) to
-	     'face index-face)
-	    (goto-char to))
-	  (insert "\n")
-	  (setq to (point))
+          (when font
+            (setq to (point))
+            (put-text-property 
+             (- (point) (length (nth 7 cell))) to
+             'face index-face)
+            (goto-char to))
+          (insert "\n")
+          (setq to (point))
 
-	  (when context
-	    (insert context-indent (nth 2 cell) "\n")
-	    (setq to (point)))
-	  (put-text-property from to :data cell)
-	  (when mouse-face
-	    (put-text-property from (1- to)
-			       'mouse-face mouse-face))
+          (when context
+            (insert context-indent (nth 2 cell) "\n")
+            (setq to (point)))
+          (put-text-property from to :data cell)
+          (when mouse-face
+            (put-text-property from (1- to)
+                               'mouse-face mouse-face))   
           (goto-char to))))
 
-      (if (eq cell here-I-am)
-	  (setq offset 'attention))
+      (if (eq cell here-I-am) 
+          (setq offset 'attention))
       (if (and prev-inserted (eq offset 'attention))
-	  (setq offset prev-inserted))
+          (setq offset prev-inserted))
       )
 
     (when (reftex-refontify)
@@ -351,18 +351,18 @@
     (goto-char (point-min))
     (let (loc pos)
       (while locations
-	(setq loc (pop locations))
-	(cond
-	 ((null loc))
-	 ((listp loc)
-	  (setq pos (text-property-any (point-min) (point-max) :data loc))
-	  (when pos
-	    (goto-char pos)
-	    (throw 'exit t)))
-	 ((integerp loc)
-	  (when (<= loc (count-lines (point-min) (point-max)))
-	    (goto-line loc)
-	    (throw 'exit t)))))
+        (setq loc (pop locations))
+        (cond
+         ((null loc))
+         ((listp loc)
+          (setq pos (text-property-any (point-min) (point-max) :data loc))
+          (when pos
+            (goto-char pos) 
+            (throw 'exit t)))
+         ((integerp loc)
+          (when (<= loc (count-lines (point-min) (point-max)))
+            (goto-line loc)
+            (throw 'exit t)))))
       (goto-char fallback))))
 
 (defvar reftex-last-data nil)
@@ -370,8 +370,8 @@
 (defvar reftex-select-marked nil)
 
 (defun reftex-select-item (prompt help-string keymap
-				  &optional offset
-				  call-back cb-flag)
+                                  &optional offset
+                                  call-back cb-flag)
 ;; Select an item, using PROMPT. The function returns a key indicating
 ;; an exit status, along with a data structure indicating which item was
 ;; selected.
@@ -393,36 +393,36 @@
             (save-window-excursion
               (setq truncate-lines t)
 
-	      ;; Find a good starting point
-	      (reftex-find-start-point
-	       (point-min) offset reftex-last-data reftex-last-line)
+              ;; Find a good starting point
+              (reftex-find-start-point 
+               (point-min) offset reftex-last-data reftex-last-line)
               (beginning-of-line 1)
-	      (set (make-local-variable 'reftex-last-follow-point) (point))
+              (set (make-local-variable 'reftex-last-follow-point) (point))
 
       (unwind-protect
-	  (progn
-	    (use-local-map keymap)
-	    (add-hook 'pre-command-hook 'reftex-select-pre-command-hook nil t)
-	    (add-hook 'post-command-hook 'reftex-select-post-command-hook nil t)
-	    (princ prompt)
-	    (set-marker reftex-recursive-edit-marker (point))
-	    ;; XEmacs does not run post-command-hook here
-	    (and (featurep 'xemacs) (run-hooks 'post-command-hook))
-	    (recursive-edit))
+          (progn
+            (use-local-map keymap)
+            (add-hook 'pre-command-hook 'reftex-select-pre-command-hook nil t)
+            (add-hook 'post-command-hook 'reftex-select-post-command-hook nil t)
+            (princ prompt)
+            (set-marker reftex-recursive-edit-marker (point))
+            ;; XEmacs does not run post-command-hook here
+            (and (featurep 'xemacs) (run-hooks 'post-command-hook))
+            (recursive-edit))
 
-	(set-marker reftex-recursive-edit-marker nil)
-	(save-excursion
-	  (set-buffer selection-buffer)
-	  (use-local-map nil)
-	  (remove-hook 'pre-command-hook 'reftex-select-pre-command-hook t)
-	  (remove-hook 'post-command-hook
-		       'reftex-select-post-command-hook t))
-	;; Kill the mark overlays
-	(mapcar (lambda (c) (delete-overlay (nth 1 c)))
-		reftex-select-marked)))))
+        (set-marker reftex-recursive-edit-marker nil)
+        (save-excursion
+          (set-buffer selection-buffer)
+          (use-local-map nil)
+          (remove-hook 'pre-command-hook 'reftex-select-pre-command-hook t)
+          (remove-hook 'post-command-hook 
+                       'reftex-select-post-command-hook t))
+        ;; Kill the mark overlays
+        (mapcar (lambda (c) (delete-overlay (nth 1 c)))
+                reftex-select-marked)))))
 
     (set (make-local-variable 'reftex-last-line)
-	 (+ (count-lines (point-min) (point)) (if (bolp) 1 0)))
+         (+ (count-lines (point-min) (point)) (if (bolp) 1 0)))
     (set (make-local-variable 'reftex-last-data) last-data)
     (reftex-kill-buffer "*RefTeX Help*")
     (setq reftex-callback-fwd (not reftex-callback-fwd)) ;; ;-)))
@@ -451,25 +451,25 @@
   (let (b e)
     (setq data (get-text-property (point) :data))
     (setq last-data (or data last-data))
-
+  
     (when (and data cb-flag
-	       (not (equal reftex-last-follow-point (point))))
+               (not (equal reftex-last-follow-point (point))))
       (setq reftex-last-follow-point (point))
-      (funcall call-back data reftex-callback-fwd
-	       (not reftex-revisit-to-follow)))
+      (funcall call-back data reftex-callback-fwd 
+               (not reftex-revisit-to-follow)))
     (if data
-	(setq b (or (previous-single-property-change
-		     (1+ (point)) :data)
-		    (point-min))
-	      e (or (next-single-property-change
-		     (point) :data)
-		    (point-max)))
+        (setq b (or (previous-single-property-change
+                     (1+ (point)) :data)
+                    (point-min))
+              e (or (next-single-property-change
+                     (point) :data)
+                    (point-max)))
       (setq b (point) e (point)))
     (and (memq reftex-highlight-selection '(cursor both))
-	 (reftex-highlight 1 b e))
+         (reftex-highlight 1 b e))
     (if (or (not (pos-visible-in-window-p b))
-	    (not (pos-visible-in-window-p e)))
-	(recenter '(4)))
+            (not (pos-visible-in-window-p e)))
+        (recenter '(4)))
     (unless (current-message)
       (princ prompt))))
 
@@ -518,12 +518,12 @@
   (let (pos)
     (cond
      ((and (local-variable-p 'reftex-last-data (current-buffer))
-	   reftex-last-data
-	   (setq pos (text-property-any (point-min) (point-max)
-					:data reftex-last-data)))
+           reftex-last-data
+           (setq pos (text-property-any (point-min) (point-max)
+                                        :data reftex-last-data)))
       (goto-char pos))
      ((and (local-variable-p 'reftex-last-line (current-buffer))
-	   (integerp reftex-last-line))
+           (integerp reftex-last-line))
       (goto-line reftex-last-line))
      (t (ding)))))
 (defun reftex-select-toggle-follow ()
@@ -542,20 +542,20 @@
   "Toggle the macro used for referencing the label between \\ref and \\vref."
   (interactive)
   (setq refstyle
-	(cond ((string= refstyle "\\ref") "\\fref")
-	      ((string= refstyle "\\fref") "\\Fref")
-	      (t "\\ref")))
+        (cond ((string= refstyle "\\ref") "\\fref")
+              ((string= refstyle "\\fref") "\\Fref")
+              (t "\\ref")))
   (force-mode-line-update))
 (defun reftex-select-show-insertion-point ()
   "Show the point from where selection was started in another window."
   (interactive)
   (let ((this-window (selected-window)))
     (unwind-protect
-	(progn
-	  (switch-to-buffer-other-window
-	   (marker-buffer reftex-select-return-marker))
-	  (goto-char (marker-position reftex-select-return-marker))
-	  (recenter '(4)))
+        (progn
+          (switch-to-buffer-other-window
+           (marker-buffer reftex-select-return-marker))
+          (goto-char (marker-position reftex-select-return-marker))
+          (recenter '(4)))
       (select-window this-window))))
 (defun reftex-select-callback ()
   "Show full context in another window."
@@ -575,16 +575,16 @@
 (defun reftex-select-read-label ()
   "Use minibuffer to read a label to reference, with completion."
   (interactive)
-  (let ((label (completing-read
-		"Label: " (symbol-value reftex-docstruct-symbol)
-		nil nil reftex-prefix)))
+  (let ((label (completing-read 
+                "Label: " (symbol-value reftex-docstruct-symbol)
+                nil nil reftex-prefix)))
     (unless (or (equal label "") (equal label reftex-prefix))
       (throw 'myexit label))))
 (defun reftex-select-read-cite ()
   "Use minibuffer to read a citation key with completion."
   (interactive)
   (let* ((key (completing-read "Citation key: " found-list))
-	 (entry (assoc key found-list)))
+         (entry (assoc key found-list)))
     (cond
      ((or (null key) (equal key "")))
      (entry
@@ -597,23 +597,23 @@
   "Mark the entry."
   (interactive)
   (let* ((data (get-text-property (point) :data))
-	 boe eoe ovl)
+         boe eoe ovl)
     (or data (error "No entry to mark at point"))
     (if (assq data reftex-select-marked)
-	(error "Entry is already marked"))
+        (error "Entry is already marked"))
     (setq boe (or (previous-single-property-change (1+ (point)) :data)
-		  (point-min))
-	  eoe (or (next-single-property-change (point) :data) (point-max)))
+                  (point-min))
+          eoe (or (next-single-property-change (point) :data) (point-max)))
     (setq ovl (make-overlay boe eoe))
     (push (list data ovl separator) reftex-select-marked)
     (overlay-put ovl 'face reftex-select-mark-face)
     (if (featurep 'xemacs)
-	;; before-string property is broken in Emacs
-	(overlay-put ovl 'before-string
-		     (if separator
-			 (format "*%c%d* " separator
-				 (length reftex-select-marked))
-		       (format "*%d*  " (length reftex-select-marked)))))
+        ;; before-string property is broken in Emacs
+        (overlay-put ovl 'before-string
+                     (if separator
+                         (format "*%c%d* " separator
+                                 (length reftex-select-marked))
+                       (format "*%d*  " (length reftex-select-marked)))))
     (message "Entry has mark no. %d" (length reftex-select-marked))))
 
 (defun reftex-select-mark-comma ()
@@ -633,25 +633,25 @@
   "Unmark the entry."
   (interactive)
   (let* ((data (get-text-property (point) :data))
-	 (cell (assq data reftex-select-marked))
-	 (ovl (nth 1 cell))
-	 (cnt 0)
-	 sep)
+         (cell (assq data reftex-select-marked))
+         (ovl (nth 1 cell))
+         (cnt 0)
+         sep)
     (unless cell
       (error "No marked entry at point"))
     (and ovl (delete-overlay ovl))
     (setq reftex-select-marked (delq cell reftex-select-marked))
     (if (featurep 'xemacs)
-	;; before-string property is broken in Emacs
-	(progn
-	  (setq cnt (1+ (length reftex-select-marked)))
-	  (mapcar (lambda (c)
-		    (setq sep (nth 2 c))
-		    (overlay-put (nth 1 c) 'before-string
-				 (if sep
-				     (format "*%c%d* " sep (decf cnt))
-				   (format "*%d*  " (decf cnt)))))
-		  reftex-select-marked)))
+        ;; before-string property is broken in Emacs
+        (progn
+          (setq cnt (1+ (length reftex-select-marked)))
+          (mapcar (lambda (c)
+                    (setq sep (nth 2 c))
+                    (overlay-put (nth 1 c) 'before-string
+                                 (if sep
+                                     (format "*%c%d* " sep (decf cnt))
+                                   (format "*%d*  " (decf cnt)))))
+                  reftex-select-marked)))
     (message "Entry no longer marked")))
 
 (defun reftex-select-help ()
@@ -664,27 +664,27 @@
 ;; Common bindings in reftex-select-label-map and reftex-select-bib-map
 (let ((map (make-sparse-keymap)))
   (substitute-key-definition
-   'next-line 'reftex-select-next		       map global-map)
+   'next-line 'reftex-select-next                      map global-map)
   (substitute-key-definition
-   'previous-line 'reftex-select-previous	       map global-map)
+   'previous-line 'reftex-select-previous              map global-map)
   (substitute-key-definition
    'keyboard-quit 'reftex-select-keyboard-quit         map global-map)
   (substitute-key-definition
-   'newline 'reftex-select-accept		       map global-map)
+   'newline 'reftex-select-accept                      map global-map)
 
   (loop for x in
-	'((" "        . reftex-select-callback)
-	  ("n"        . reftex-select-next)
-	  ([(down)]   . reftex-select-next)
-	  ("p"        . reftex-select-previous)
-	  ([(up)]     . reftex-select-previous)
-	  ("f"        . reftex-select-toggle-follow)
-	  ("\C-m"     . reftex-select-accept)
-	  ([(return)] . reftex-select-accept)
-	  ("q"        . reftex-select-quit)
-	  ("."        . reftex-select-show-insertion-point)
-	  ("?"        . reftex-select-help))
-	do (define-key map (car x) (cdr x)))
+        '((" "        . reftex-select-callback)
+          ("n"        . reftex-select-next)
+          ([(down)]   . reftex-select-next)
+          ("p"        . reftex-select-previous)
+          ([(up)]     . reftex-select-previous)
+          ("f"        . reftex-select-toggle-follow)
+          ("\C-m"     . reftex-select-accept)
+          ([(return)] . reftex-select-accept) 
+          ("q"        . reftex-select-quit)
+          ("."        . reftex-select-show-insertion-point)
+          ("?"        . reftex-select-help))
+        do (define-key map (car x) (cdr x)))
 
   ;; The mouse-2 binding
   (if (featurep 'xemacs)
@@ -693,7 +693,7 @@
 
   ;; Digit arguments
   (loop for key across "0123456789" do
-	(define-key map (vector (list key)) 'digit-argument))
+        (define-key map (vector (list key)) 'digit-argument))
   (define-key map "-" 'negative-argument)
 
   ;; Make two maps
@@ -703,40 +703,40 @@
 ;; Specific bindings in reftex-select-label-map
 (loop for key across "aAcgFlrRstx#%" do
       (define-key reftex-select-label-map (vector (list key))
-	(list 'lambda '()
-	      "Press `?' during selection to find out about this key."
-	      '(interactive) (list 'throw '(quote myexit) key))))
+        (list 'lambda '() 
+              "Press `?' during selection to find out about this key."
+              '(interactive) (list 'throw '(quote myexit) key))))
 
 (loop for x in
       '(("b"        . reftex-select-jump-to-previous)
-	("z"        . reftex-select-jump)
-	("v"        . reftex-select-toggle-varioref)
-	("V"        . reftex-select-toggle-fancyref)
-	("m"        . reftex-select-mark)
-	("u"        . reftex-select-unmark)
-	(","        . reftex-select-mark-comma)
-	("-"        . reftex-select-mark-to)
-	("+"        . reftex-select-mark-and)
-	([(tab)]    . reftex-select-read-label)
-	("\C-i"     . reftex-select-read-label)
-	("\C-c\C-n" . reftex-select-next-heading)
-	("\C-c\C-p" . reftex-select-previous-heading))
+        ("z"        . reftex-select-jump)
+        ("v"        . reftex-select-toggle-varioref)
+        ("V"        . reftex-select-toggle-fancyref)
+        ("m"        . reftex-select-mark)
+        ("u"        . reftex-select-unmark)
+        (","        . reftex-select-mark-comma)
+        ("-"        . reftex-select-mark-to)
+        ("+"        . reftex-select-mark-and)
+        ([(tab)]    . reftex-select-read-label)
+        ("\C-i"     . reftex-select-read-label)
+        ("\C-c\C-n" . reftex-select-next-heading)
+        ("\C-c\C-p" . reftex-select-previous-heading))
       do
       (define-key reftex-select-label-map (car x) (cdr x)))
 
 ;; Specific bindings in reftex-select-bib-map
 (loop for key across "grRaA" do
       (define-key reftex-select-bib-map (vector (list key))
-	(list 'lambda '()
-	      "Press `?' during selection to find out about this key."
-	      '(interactive) (list 'throw '(quote myexit) key))))
+        (list 'lambda '() 
+              "Press `?' during selection to find out about this key."
+              '(interactive) (list 'throw '(quote myexit) key))))
 
 (loop for x in
       '(("\C-i"  . reftex-select-read-cite)
-	([(tab)] . reftex-select-read-cite)
-	("m"     . reftex-select-mark)
-	("u"     . reftex-select-unmark))
+        ([(tab)] . reftex-select-read-cite)
+        ("m"     . reftex-select-mark)
+        ("u"     . reftex-select-unmark))
       do (define-key reftex-select-bib-map (car x) (cdr x)))
-
+  
 
 ;;; reftex-sel.el ends here
--- a/lisp/textmodes/reftex-toc.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-toc.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-toc.el --- RefTeX's table of contents mode
-;; Copyright (c) 1997, 1998, 1999, 2000, 2003  Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 
 ;; This file is part of GNU Emacs.
 
@@ -46,21 +46,23 @@
   (interactive)
   (kill-all-local-variables)
   (setq major-mode 'reftex-toc-mode
-	mode-name "TOC")
+        mode-name "TOC")
   (use-local-map reftex-toc-map)
+  (set (make-local-variable 'transient-mark-mode) t)
+  (set (make-local-variable 'zmacs-regions) t)
   (set (make-local-variable 'revert-buffer-function) 'reftex-toc-revert)
   (set (make-local-variable 'reftex-toc-include-labels-indicator) "")
   (set (make-local-variable 'reftex-toc-max-level-indicator)
        (if (= reftex-toc-max-level 100)
-	   "ALL"
-	 (int-to-string reftex-toc-max-level)))
+           "ALL"
+         (int-to-string reftex-toc-max-level)))
   (setq mode-line-format
-	(list "----  " 'mode-line-buffer-identification
-	      "  " 'global-mode-string "   (" mode-name ")"
-	      "  L<" 'reftex-toc-include-labels-indicator ">"
-	      "  I<" 'reftex-toc-include-index-indicator ">"
-	      "  T<" 'reftex-toc-max-level-indicator ">"
-	      " -%-"))
+        (list "----  " 'mode-line-buffer-identification
+              "  " 'global-mode-string "   (" mode-name ")"
+              "  L<" 'reftex-toc-include-labels-indicator ">"
+              "  I<" 'reftex-toc-include-index-indicator ">"
+              "  T<" 'reftex-toc-max-level-indicator ">"
+              " -%-"))
   (setq truncate-lines t)
   (when (featurep 'xemacs)
     ;; XEmacs needs the call to make-local-hook
@@ -91,20 +93,26 @@
 SPC        Show the corresponding location of the LaTeX document.
 TAB        Goto the location and keep the *toc* window.
 RET        Goto the location and hide the *toc* window (also on mouse-2).
+< / >      Promote / Demote section, or all sections in region.
 C-c >      Display Index. With prefix arg, restrict index to current section.
 q / k      Hide/Kill *toc* buffer, return to position of reftex-toc command.
 l i c F    Toggle display of  [l]abels,  [i]ndex,  [c]ontext,  [F]ile borders.
 t          Change maximum toc depth (e.g. `3 t' hides levels greater than 3).
-f / a / g  Toggle follow mode / toggle auto recenter / Refresh *toc* buffer.
+f / g      Toggle follow mode / Refresh *toc* buffer.
+a / d      Toggle auto recenter / Toggle dedicated frame
 r / C-u r  Reparse the LaTeX document     / Reparse entire LaTeX document.
 .          In other window, show position from where `reftex-toc' was called.
+M-%        Global search and replace to rename label at point.
 x          Switch to TOC of external document (with LaTeX package `xr').
-z          Jump to a specific section (e.g. '3 z' goes to section 3")
+z          Jump to a specific section (e.g. '3 z' goes to section 3).")
 
-(defun reftex-toc (&optional rebuild)
+(defun reftex-toc (&optional rebuild reuse)
   "Show the table of contents for the current document.
 When called with a raw C-u prefix, rescan the document first."
 
+;; The REUSE argument means, search all visible frames for a window
+;; displaying the toc window.  If yes, reuse this window.
+
   (interactive)
 
   (if (or (not (string= reftex-last-toc-master (reftex-TeX-master-file)))
@@ -129,40 +137,50 @@
   (reftex-access-scan-info current-prefix-arg)
 
   (let* ((this-buf (current-buffer))
-	 (docstruct-symbol reftex-docstruct-symbol)
-	 (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
-	 (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
-	 (here-I-am (if (boundp 'reftex-rebuilding-toc)
-			(get 'reftex-toc :reftex-data)
-		      (car (reftex-where-am-I))))
-	 offset)
+         (docstruct-symbol reftex-docstruct-symbol)
+         (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
+         (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
+         (here-I-am (if (boundp 'reftex-rebuilding-toc)
+                        (get 'reftex-toc :reftex-data)
+                      (car (reftex-where-am-I))))
+         (unsplittable (if (fboundp 'frame-property)
+                           (frame-property (selected-frame) 'unsplittable)
+                         (frame-parameter (selected-frame) 'unsplittable)))
+         offset toc-window)
 
-    (if (get-buffer-window "*toc*")
-        (select-window (get-buffer-window "*toc*"))
+    (if (setq toc-window (get-buffer-window 
+                          "*toc*"
+                          (if reuse 'visible)))
+        (select-window toc-window)
       (when (or (not reftex-toc-keep-other-windows)
-		(< (window-height) (* 2 window-min-height)))
-	(delete-other-windows))
+                (< (window-height) (* 2 window-min-height)))
+        (delete-other-windows))
 
       (setq reftex-last-window-width (window-width)
-	    reftex-last-window-height (window-height))  ; remember
-      (if reftex-toc-split-windows-horizontally
-	  (split-window-horizontally
-	   (floor (* (frame-width) reftex-toc-split-windows-horizontally-fraction)))
-	(split-window))
+            reftex-last-window-height (window-height))  ; remember
+
+      (unless unsplittable
+        (if reftex-toc-split-windows-horizontally
+            (split-window-horizontally
+             (floor (* (window-width)
+                       reftex-toc-split-windows-fraction)))
+          (split-window-vertically 
+           (floor (* (window-height)
+                     reftex-toc-split-windows-fraction)))))
 
       (let ((default-major-mode 'reftex-toc-mode))
-	(switch-to-buffer "*toc*")))
+        (switch-to-buffer "*toc*")))
 
     (or (eq major-mode 'reftex-toc-mode) (reftex-toc-mode))
     (set (make-local-variable 'reftex-docstruct-symbol) docstruct-symbol)
     (setq reftex-toc-include-labels-indicator
-	  (if (eq reftex-toc-include-labels t)
-	      "ALL"
-	    reftex-toc-include-labels))
+          (if (eq reftex-toc-include-labels t)
+              "ALL"
+            reftex-toc-include-labels))
     (setq reftex-toc-include-index-indicator
-	  (if (eq reftex-toc-include-index-entries t)
-	      "ALL"
-	    reftex-toc-include-index-entries))
+          (if (eq reftex-toc-include-index-entries t)
+              "ALL"
+            reftex-toc-include-index-entries))
 
     (cond
      ((= (buffer-size) 0)
@@ -182,34 +200,34 @@
       (put-text-property (point-min) (1+ (point-min)) 'xr-alist xr-alist)
 
       (setq offset
-	    (reftex-insert-docstruct
-	     this-buf
-	     t ; include toc
-	     reftex-toc-include-labels
-	     reftex-toc-include-index-entries
-	     reftex-toc-include-file-boundaries
-	     reftex-toc-include-context
-	     nil ; counter
-	     nil ; commented
-	     here-I-am
-	     ""     ; xr-prefix
-	     t      ; a toc buffer
-	     ))
-
+            (reftex-insert-docstruct
+             this-buf
+             t ; include toc
+             reftex-toc-include-labels
+             reftex-toc-include-index-entries
+             reftex-toc-include-file-boundaries
+             reftex-toc-include-context
+             nil ; counter
+             nil ; commented
+             here-I-am 
+             ""     ; xr-prefix
+             t      ; a toc buffer
+             ))
+       
       (run-hooks 'reftex-display-copied-context-hook)
       (message "Building *toc* buffer...done.")
       (setq buffer-read-only t))
      (t
       ;; Only compute the offset
       (setq offset
-	    (or (reftex-get-offset this-buf here-I-am
-				   (if reftex-toc-include-labels " " nil)
-				   t
-				   reftex-toc-include-index-entries
-				   reftex-toc-include-file-boundaries)
-		(reftex-last-assoc-before-elt
-		 'toc here-I-am
-		 (symbol-value reftex-docstruct-symbol))))
+            (or (reftex-get-offset this-buf here-I-am
+                                   (if reftex-toc-include-labels " " nil)
+                                   t
+                                   reftex-toc-include-index-entries
+                                   reftex-toc-include-file-boundaries)
+                (reftex-last-assoc-before-elt 
+                 'toc here-I-am
+                 (symbol-value reftex-docstruct-symbol))))
       (put 'reftex-toc :reftex-line 3)
       (goto-line 3)
       (beginning-of-line)))
@@ -221,27 +239,27 @@
 (defun reftex-toc-recenter (&optional arg)
   "Display the TOC window and highlight line corresponding to current position."
   (interactive "P")
-  (let ((buf (current-buffer)))
-    (reftex-toc arg)
+  (let ((buf (current-buffer))
+        (frame (selected-frame)))
+    (reftex-toc arg t)
     (if (= (count-lines 1 (point)) 2)
-	(let ((current-prefix-arg nil))
-	  (select-window (get-buffer-window buf))
-	  (reftex-toc nil)))
+        (let ((current-prefix-arg nil))
+          (select-window (get-buffer-window buf frame))
+          (reftex-toc nil t)))
     (and (> (point) 1)
-	 (not (get-text-property (point) 'intangible))
-	 (memq reftex-highlight-selection '(cursor both))
-	 (reftex-highlight 2
-	   (or (previous-single-property-change
-		(min (point-max) (1+ (point))) :data)
-	       (point-min))
-	   (or (next-single-property-change (point) :data)
-	       (point-max))))
-    (select-window (get-buffer-window buf))))
+         (not (get-text-property (point) 'intangible))
+         (memq reftex-highlight-selection '(cursor both))
+         (reftex-highlight 2
+                           (or (previous-single-property-change 
+                                (min (point-max) (1+ (point))) :data)
+                               (point-min))
+                           (or (next-single-property-change (point) :data)
+                               (point-max))))
+    (select-window (get-buffer-window buf frame))))
 
 (defun reftex-toc-pre-command-hook ()
   ;; used as pre command hook in *toc* buffer
   (reftex-unhighlight 0)
-;;  (reftex-unhighlight 1)  ;; remove highlight on leaving buffer.
   )
 
 (defun reftex-toc-post-command-hook ()
@@ -249,37 +267,52 @@
   (when (get-text-property (point) :data)
     (put 'reftex-toc :reftex-data (get-text-property (point) :data))
     (and (> (point) 1)
-	 (not (get-text-property (point) 'intangible))
-	 (memq reftex-highlight-selection '(cursor both))
-	 (reftex-highlight 2
-	   (or (previous-single-property-change (1+ (point)) :data)
-	       (point-min))
-	   (or (next-single-property-change (point) :data)
-	       (point-max)))))
+         (not (get-text-property (point) 'intangible))
+         (memq reftex-highlight-selection '(cursor both))
+         (reftex-highlight 2
+           (or (previous-single-property-change (1+ (point)) :data)
+               (point-min))
+           (or (next-single-property-change (point) :data)
+               (point-max)))))
   (if (integerp reftex-toc-follow-mode)
       ;; remove delayed action
       (setq reftex-toc-follow-mode t)
-    (and reftex-toc-follow-mode
-	 (not (equal reftex-last-follow-point (point)))
-	 ;; show context in other window
-	 (setq reftex-last-follow-point (point))
-	 (condition-case nil
-	     (reftex-toc-visit-location nil (not reftex-revisit-to-follow))
-	   (error t)))))
+    (and (not (reftex-toc-dframe-p))
+         reftex-toc-follow-mode
+         (not (equal reftex-last-follow-point (point)))
+         ;; show context in other window
+         (setq reftex-last-follow-point (point))
+         (condition-case nil
+             (reftex-toc-visit-location nil (not reftex-revisit-to-follow))
+           (error t)))))
 
 (defun reftex-re-enlarge ()
   ;; Enlarge window to a remembered size.
   (if reftex-toc-split-windows-horizontally
       (enlarge-window-horizontally
        (max 0 (- (or reftex-last-window-width (window-width))
-		 (window-width))))
+                 (window-width))))
     (enlarge-window
      (max 0 (- (or reftex-last-window-height (window-height))
-	       (window-height))))))
+               (window-height))))))
+
+(defun reftex-toc-dframe-p (&optional frame error)
+  ;; Check if FRAME is the dedicated TOC frame.  
+  ;; If yes, and ERROR is non-nil, throw an error.
+  (setq frame (or frame (selected-frame)))
+  (let ((res (equal 
+              (if (fboundp 'frame-property)
+                  (frame-property frame 'name)
+                (frame-parameter  frame 'name))
+              "RefTeX TOC Frame")))
+    (if (and res error)
+        (error "This frame is view-only.  Use `C-c =' to create toc window for commands."))
+    res))
 
 (defun reftex-toc-show-help ()
   "Show a summary of special key bindings."
   (interactive)
+  (reftex-toc-dframe-p nil 'error)
   (with-output-to-temp-buffer "*RefTeX Help*"
     (princ reftex-toc-help))
   (reftex-enlarge-to-fit "*RefTeX Help*" t)
@@ -290,25 +323,29 @@
 (defun reftex-toc-next (&optional arg)
   "Move to next selectable item."
   (interactive "p")
+  (if (boundp 'zmacs-region-stays) (setq zmacs-region-stays t))
   (setq reftex-callback-fwd t)
   (or (eobp) (forward-char 1))
-  (goto-char (or (next-single-property-change (point) :data)
-		 (point))))
+  (goto-char (or (next-single-property-change (point) :data) 
+                 (point))))
 (defun reftex-toc-previous (&optional arg)
   "Move to previous selectable item."
   (interactive "p")
+  (if (boundp 'zmacs-region-stays) (setq zmacs-region-stays t))
   (setq reftex-callback-fwd nil)
   (goto-char (or (previous-single-property-change (point) :data)
-		 (point))))
+                 (point))))
 (defun reftex-toc-next-heading (&optional arg)
   "Move to next table of contentes line."
   (interactive "p")
+  (if (boundp 'zmacs-region-stays) (setq zmacs-region-stays t))
   (end-of-line)
   (re-search-forward "^ " nil t arg)
   (beginning-of-line))
 (defun reftex-toc-previous-heading (&optional arg)
   "Move to previous table of contentes line."
   (interactive "p")
+  (if (boundp 'zmacs-region-stays) (setq zmacs-region-stays t))
   (re-search-backward "^ " nil t arg))
 (defun reftex-toc-toggle-follow ()
   "Toggle follow (other window follows with context)."
@@ -319,16 +356,16 @@
   "Toggle inclusion of file boundaries in *toc* buffer."
   (interactive)
   (setq reftex-toc-include-file-boundaries
-	(not reftex-toc-include-file-boundaries))
+        (not reftex-toc-include-file-boundaries))
   (reftex-toc-revert))
 (defun reftex-toc-toggle-labels (arg)
   "Toggle inclusion of labels in *toc* buffer.
 With prefix ARG, prompt for a label type and include only labels of
 that specific type."
   (interactive "P")
-  (setq reftex-toc-include-labels
-	(if arg (reftex-query-label-type)
-	  (not reftex-toc-include-labels)))
+  (setq reftex-toc-include-labels 
+        (if arg (reftex-query-label-type)
+          (not reftex-toc-include-labels)))
   (reftex-toc-revert))
 (defun reftex-toc-toggle-index (arg)
   "Toggle inclusion of index in *toc* buffer.
@@ -336,8 +373,8 @@
 specific index."
   (interactive "P")
   (setq reftex-toc-include-index-entries
-	(if arg (reftex-index-select-tag)
-	  (not reftex-toc-include-index-entries)))
+        (if arg (reftex-index-select-tag)
+          (not reftex-toc-include-index-entries)))
   (reftex-toc-revert))
 (defun reftex-toc-toggle-context ()
   "Toggle inclusion of label context in *toc* buffer.
@@ -351,46 +388,57 @@
 levels are shown.  For eaxample, to set the level to 3, type `3 m'."
   (interactive "P")
   (setq reftex-toc-max-level (if arg
-				 (prefix-numeric-value arg)
-			       100))
+                                 (prefix-numeric-value arg)
+                               100))
   (setq reftex-toc-max-level-indicator
-	(if arg (int-to-string reftex-toc-max-level) "ALL"))
+        (if arg (int-to-string reftex-toc-max-level) "ALL"))
   (reftex-toc-revert))
 (defun reftex-toc-view-line ()
   "View document location in other window."
   (interactive)
+  (reftex-toc-dframe-p nil 'error)
   (reftex-toc-visit-location))
 (defun reftex-toc-goto-line-and-hide ()
   "Go to document location in other window.  Hide the *toc* window."
   (interactive)
+  (reftex-toc-dframe-p nil 'error)
   (reftex-toc-visit-location 'hide))
 (defun reftex-toc-goto-line ()
   "Go to document location in other window. *toc* window stays."
   (interactive)
+  (reftex-toc-dframe-p nil 'error)
   (reftex-toc-visit-location t))
 (defun reftex-toc-mouse-goto-line-and-hide (ev)
   "Go to document location in other window.  Hide the *toc* window."
   (interactive "e")
   (mouse-set-point ev)
+  (reftex-toc-dframe-p nil 'error)
   (reftex-toc-visit-location 'hide))
 (defun reftex-toc-show-calling-point ()
   "Show point where reftex-toc was called from."
   (interactive)
+  (reftex-toc-dframe-p nil 'error)
   (let ((this-window (selected-window)))
     (unwind-protect
-	(progn
-	  (switch-to-buffer-other-window
-	   (marker-buffer reftex-toc-return-marker))
-	  (goto-char (marker-position reftex-toc-return-marker))
-	  (recenter '(4)))
+        (progn
+          (switch-to-buffer-other-window
+           (marker-buffer reftex-toc-return-marker))
+          (goto-char (marker-position reftex-toc-return-marker))
+          (recenter '(4)))
       (select-window this-window))))
 (defun reftex-toc-quit ()
-  "Hide the *toc* window and do not move point."
+  "Hide the *toc* window and do not move point.
+If the toc window is the only window on the dedicated TOC frame, the frame
+is destroyed."
   (interactive)
-  (or (one-window-p) (delete-window))
-  (switch-to-buffer (marker-buffer reftex-toc-return-marker))
-  (reftex-re-enlarge)
-  (goto-char (or (marker-position reftex-toc-return-marker) (point))))
+  (if (and (one-window-p)
+           (reftex-toc-dframe-p)
+           (> (length (frame-list)) 1))
+      (delete-frame)
+    (or (one-window-p) (delete-window))
+    (switch-to-buffer (marker-buffer reftex-toc-return-marker))
+    (reftex-re-enlarge)
+    (goto-char (or (marker-position reftex-toc-return-marker) (point)))))
 (defun reftex-toc-quit-and-kill ()
   "Kill the *toc* buffer."
   (interactive)
@@ -404,37 +452,41 @@
 This works just like `reftex-display-index' from a LaTeX buffer.
 With prefix arg 1, restrict index to the section at point."
   (interactive "P")
+  (reftex-toc-dframe-p nil 'error)
   (let ((data (get-text-property (point) :data))
-	(docstruct (symbol-value reftex-docstruct-symbol))
-	bor eor restr)
+        (docstruct (symbol-value reftex-docstruct-symbol))
+        bor eor restr)
     (when (equal arg 2)
       (setq bor (reftex-last-assoc-before-elt 'toc data docstruct)
-	    eor (assoc 'toc (cdr (memq bor docstruct)))
-	    restr (list (nth 6 bor) bor eor)))
+            eor (assoc 'toc (cdr (memq bor docstruct)))
+            restr (list (nth 6 bor) bor eor)))
     (reftex-toc-goto-line)
     (reftex-display-index (if restr nil arg) restr)))
+
+;; Rescanning the document and rebuilding the TOC buffer.
 (defun reftex-toc-rescan (&rest ignore)
   "Regenerate the *toc* buffer by reparsing file of section at point."
   (interactive)
-  (if (and reftex-enable-partial-scans
-	   (null current-prefix-arg))
+  (if (and reftex-enable-partial-scans 
+           (null current-prefix-arg))
       (let* ((data (get-text-property (point) :data))
-	     (what (car data))
-	     (file (cond ((eq what 'toc) (nth 3 data))
-			 ((memq what '(eof bof file-error)) (nth 1 data))
-			 ((stringp what) (nth 3 data))
-			 ((eq what 'index) (nth 3 data))))
-	     (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
+             (what (car data))
+             (file (cond ((eq what 'toc) (nth 3 data))
+                         ((memq what '(eof bof file-error)) (nth 1 data))
+                         ((stringp what) (nth 3 data))
+                         ((eq what 'index) (nth 3 data))))
+             (line (+ (count-lines (point-min) (point)) (if (bolp) 1 0))))
         (if (not file)
             (error "Don't know which file to rescan.  Try `C-u r'")
-	  (put 'reftex-toc :reftex-line line)
+          (put 'reftex-toc :reftex-line line)
           (switch-to-buffer-other-window
            (reftex-get-file-buffer-force file))
-	  (setq current-prefix-arg '(4))
-	  (let ((reftex-rebuilding-toc t))
-	    (reftex-toc))))
+          (setq current-prefix-arg '(4))
+          (let ((reftex-rebuilding-toc t))
+            (reftex-toc))))
     (reftex-toc-Rescan))
   (reftex-kill-temporary-buffers))
+
 (defun reftex-toc-Rescan (&rest ignore)
   "Regenerate the *toc* buffer by reparsing the entire document."
   (interactive)
@@ -445,28 +497,38 @@
   (setq current-prefix-arg '(16))
   (let ((reftex-rebuilding-toc t))
     (reftex-toc)))
+
 (defun reftex-toc-revert (&rest ignore)
   "Regenerate the *toc* from the internal lists."
   (interactive)
-  (switch-to-buffer-other-window
-   (reftex-get-file-buffer-force reftex-last-toc-file))
+  (let ((unsplittable 
+         (if (fboundp 'frame-property)
+             (frame-property (selected-frame) 'unsplittable)
+           (frame-parameter (selected-frame) 'unsplittable)))
+        (reftex-rebuilding-toc t))
+    (if unsplittable
+        (switch-to-buffer
+         (reftex-get-file-buffer-force reftex-last-toc-file))
+      (switch-to-buffer-other-window
+       (reftex-get-file-buffer-force reftex-last-toc-file))))
   (reftex-erase-buffer "*toc*")
   (setq current-prefix-arg nil)
-  (let ((reftex-rebuilding-toc t))
-    (reftex-toc t)))
+  (reftex-toc t))
+
 (defun reftex-toc-external (&rest ignore)
   "Switch to table of contents of an external document."
   (interactive)
+  (reftex-toc-dframe-p nil 'error)
   (let* ((old-buf (current-buffer))
-	 (xr-alist (get-text-property 1 'xr-alist))
-	 (xr-index (reftex-select-external-document
-		   xr-alist 0)))
+         (xr-alist (get-text-property 1 'xr-alist))
+         (xr-index (reftex-select-external-document
+                   xr-alist 0)))
     (switch-to-buffer-other-window (or (reftex-get-file-buffer-force
-					(cdr (nth xr-index xr-alist)))
-				       (error "Cannot switch document")))
+                                        (cdr (nth xr-index xr-alist)))
+                                       (error "Cannot switch document")))
     (reftex-toc)
     (if (equal old-buf (current-buffer))
-	(message "")
+        (message "")
       (message "Switched document"))))
 
 (defun reftex-toc-jump (arg)
@@ -479,6 +541,254 @@
    nil t)
   (beginning-of-line))
 
+;; Promotion/Demotion stuff
+
+(defun reftex-toc-demote (&optional arg)
+  "Demote section at point.  If region is active, apply to all in region."
+  (interactive "p")
+  (reftex-toc-do-promote 1))
+(defun reftex-toc-promote (&optional arg)
+  "Promote section at point.  If region is active, apply to all in region."
+  (interactive "p")
+  (reftex-toc-do-promote -1))
+(defun reftex-toc-do-promote (delta)
+  "Workhorse for reftex-toc-promote and reftex-to-demote.
+Changes the level of sections in the current region, or just the section at
+point."
+  ;; We should not do anything unless we are sure this is going to work for
+  ;; each section in the region.  Therefore we first collect information and
+  ;; test.
+  (let* ((start-line (+ (count-lines (point-min) (point))
+			(if (bolp) 1 0)))
+	 (mark-line  (if (reftex-region-active-p)
+			 (save-excursion (goto-char (mark))
+					 (+ (count-lines (point-min) (point))
+					    (if (bolp) 1 0)))))
+         (start-pos (point))
+         (pro-or-de (if (> delta 0) "de" "pro"))
+         beg end entries data sections nsec mpos msg)
+    (setq msg
+          (catch 'exit
+            (if (reftex-region-active-p)
+                ;; A region is dangerous, check if we have a brandnew scan,
+                ;; to make sure we are not missing any section statements.
+                (if (not (reftex-toc-check-docstruct))
+                    (reftex-toc-load-all-files-for-promotion)   ;; exits
+                  (setq beg (min (point) (mark))
+                        end (max (point) (mark))))
+              (setq beg (point) end (point)))
+            (goto-char beg)
+            (while (and (setq data (get-text-property (point) :data))
+                        (<= (point) end))
+              (if (eq (car data) 'toc) (push (cons data (point)) entries))
+              (goto-char (or (next-single-property-change (point) :data)
+                             (point-max))))
+            (setq entries (nreverse entries))
+            ;; Get the relevant section numbers, for an informative message
+            (goto-char start-pos)
+            (setq sections (reftex-toc-extract-section-number (car entries)))
+            (if (> (setq nsec (length entries)) 1)
+                (setq sections 
+                      (concat sections "-"
+                              (reftex-toc-extract-section-number
+                               (nth (1- nsec) entries)))))
+            ;; Run through the list and prepare the changes.
+            (setq entries (mapcar 'reftex-toc-promote-prepare entries))
+            ;; Ask for permission
+            (if (or (not reftex-toc-confirm-promotion)           ; never confirm
+                    (and (integerp reftex-toc-confirm-promotion) ; confirm if many
+                         (< nsec reftex-toc-confirm-promotion))
+                    (yes-or-no-p                                 ; ask
+                     (format "%s %d toc-entr%s (section%s %s)? "
+                             (if (< delta 0) "Promote" "Demote")
+                             nsec
+                             (if (= 1 nsec) "y" "ies")
+                             (if (= 1 nsec) "" "s")
+                             sections)))
+                nil              ; we have permission, do nothing
+              (error "Abort"))   ; abort, we don't have permission
+            ;; Do the changes
+            (mapcar 'reftex-toc-promote-action entries)
+            ;; Rescan the document and rebuilt the toc buffer
+            (save-window-excursion
+              (reftex-toc-Rescan))
+            (reftex-toc-restore-region start-line mark-line)
+            (message "%d section%s %smoted" 
+                     nsec (if (= 1 nsec) "" "s") pro-or-de)
+            nil))
+    (if msg (progn (ding) (message msg)))))
+
+(defvar delta)
+(defvar mpos)
+(defvar pro-or-de)
+(defvar start-pos)
+(defvar start-line)
+(defvar mark-line)
+
+(defun reftex-toc-restore-region (point-line &optional mark-line)
+  (if mark-line
+      (progn (goto-line mark-line)
+             (setq mpos (point))))
+  (if point-line (goto-line point-line))
+  (if mark-line
+      (progn
+        (set-mark mpos)
+        (if (fboundp 'zmacs-activate-region)
+            (zmacs-activate-region)
+          (setq mark-active t
+                deactivate-mark nil)))))
+
+(defun reftex-toc-promote-prepare (x)
+  "Look at a toc entry and see if we could pro/demote it.
+Expects the level change DELTA to be dynamically scoped into this function.
+This function prepares everything for the changes, but does not do it.
+The return value is a list with information needed when doing the
+promotion/demotion later."
+  (let* ((data (car x))
+         (toc-point (cdr x))
+         (marker (nth 4 data))
+         (literal (nth 7 data))
+         (load nil)
+         (name nil)
+         ;; Here follows some paranoid code to make very sure we are not
+         ;; going to break anything
+         (name1         ; dummy
+          (if (and (markerp marker) (marker-buffer marker))
+              ;; Buffer is still live and we have the marker.
+              (progn
+                (save-excursion
+                  ;; Goto the buffer and check of section is unchanged
+                  (set-buffer (marker-buffer marker))
+                  (goto-char (marker-position marker))
+                  (if (looking-at (regexp-quote literal))
+                      ;; OK, get the makro name
+                      (progn
+                        (beginning-of-line 1)
+                        (if (looking-at reftex-section-regexp)
+                            (setq name (reftex-match-string 2))
+                          (error "Something is wrong! Contact maintainer!")))
+                    ;; Section has changed, request scan and loading
+                    ;; We use a variable to delay until after the safe-exc.
+                    ;; because otherwise we loose the region.
+                    (setq load t)))
+                ;; Scan document and load all files, this exits command
+                (if load (reftex-toc-load-all-files-for-promotion))) ; exits
+            ;; We don't have a live marker: scan and load files.
+            (reftex-toc-load-all-files-for-promotion)))
+         (level (cdr (assoc name reftex-section-levels-all)))
+         (dummy (if (not (integerp level))
+                    (progn
+                      (goto-char toc-point)
+                      (error "Cannot %smote special sections" pro-or-de))))
+         ;; Delta is dynamically scoped into here...
+         (newlevel (if (>= level 0) (+ delta level) (- level delta)))
+         (dummy2 (if (or (and (>= level 0) (= newlevel -1))
+                         (and (< level 0)  (= newlevel 0)))
+                     (error "Cannot %smote \\%s" pro-or-de name)))
+         (newname (reftex-toc-newhead-from-alist newlevel name
+                                                 reftex-section-levels-all)))
+    (if (and name newname)
+        (list data name newname toc-point)
+      (goto-char toc-point)
+      (error "Cannot %smote \\%s" pro-or-de name))))
+
+(defun reftex-toc-promote-action (x)
+  "Change the level of a toc entry.
+DELTA and PRO-OR-DE are assumed to be dynamically scoped into this function."
+  (let* ((data (car x))
+         (name (nth 1 x))
+         (newname (nth 2 x))
+         (marker (nth 4 data)))
+    (save-excursion
+      (set-buffer (marker-buffer marker))
+      (goto-char (marker-position marker))
+      (if (looking-at (concat "\\([ \t]*\\\\\\)" (regexp-quote name)))
+          (replace-match (concat "\\1" newname))
+        (error "Fatal error during %smotion" pro-or-de)))))
+
+(defun reftex-toc-extract-section-number (entry)
+  "Get the numbering of a toc entry, for message purposes."
+  (if (string-match "\\s-*\\(\\S-+\\)" (nth 2 (car entry)))
+      (match-string 1 (nth 2 (car entry)))
+    "?"))
+
+(defun reftex-toc-newhead-from-alist (nlevel head alist)
+  "Get new heading with level NLEVEL from ALIST.
+If there are no such entries, return nil.
+If there are several different entries with same new level, choose
+the one with the smallest distance to the assocation of HEAD in the alist.
+This makes it possible for promotion to work several sets of headings,
+if these sets are sorted blocks in the alist."
+  (let* ((al alist)
+         (ass (assoc head al))
+         (pos (length (memq ass al)))
+         dist (mindist 1000) newhead)
+    (while al
+      (if (equal (cdar al) nlevel)
+          (progn
+            (setq dist (abs (- (length al) pos)))
+            (if (< dist mindist)
+                (setq newhead (car (car al))
+                      mindist dist))))
+      (setq al (cdr al)))
+    newhead))
+
+(defun reftex-toc-check-docstruct ()
+  "Check if the current docstruct is fully up to date and all files visited."
+  ;; We do this by checking if all sections are on the right position
+  (let ((docstruct (symbol-value reftex-docstruct-symbol))
+        entry marker empoint)
+    (catch 'exit
+      (while (setq entry (pop docstruct))
+        (if (eq (car entry) 'toc)
+            (progn
+              (setq marker (nth 4 entry)
+                    empoint (nth 8 entry))
+              (if (not (and (markerp marker)
+                            (marker-buffer marker)
+                            (= (marker-position marker) empoint)))
+                  (throw 'exit nil)))))
+      t)))
+
+(defun reftex-toc-load-all-files-for-promotion ()
+  "Make sure all files of the document are being visited by buffers,
+and that the scanning info is absolutely up to date.
+We do this by rescanning with reftex-keep-temporary-buffers bound to t.
+The variable PRO-OR-DE is assumed to be dynamically scoped into thes function.
+When finished, we exit with an error message."
+  (let ((reftex-keep-temporary-buffers t))
+    (reftex-toc-Rescan)
+    (reftex-toc-restore-region start-line mark-line)
+    (throw 'exit
+           (format "TOC had to be updated first.  Please check selection and repeat the command." pro-or-de))))
+
+(defun reftex-toc-rename-label ()
+  "Rename the currently selected label in the *TOC* buffer.
+This launches a global search and replace in order to rename a label.
+Renaming a label is hardly ever necessary - the only exeption is after
+promotion/demotion in connection with a package like fancyref, where the
+label prefix determines the wording of a reference."
+  (interactive)
+  (let* ((toc (get-text-property (point) :data))
+         (label (car toc)) newlabel)
+    (if (not (stringp label))
+        (error "This is not a label entry."))
+    (setq newlabel (read-string (format "Rename label \"%s\" to:" label)))
+    (if (assoc newlabel (symbol-value reftex-docstruct-symbol))
+        (if (not (y-or-n-p 
+                  (format "Label '%s' exists. Use anyway? " label)))
+            (error "Abort")))
+    (save-excursion
+      (save-window-excursion
+        (reftex-toc-visit-location t)
+        (condition-case nil
+            (reftex-query-replace-document
+             (concat "{" (regexp-quote label) "}")
+             (format "{%s}" newlabel))
+          (error t))))        
+    (reftex-toc-rescan)))
+
+
 (defun reftex-toc-visit-location (&optional final no-revisit)
   ;; Visit the tex file corresponding to the toc entry on the current line.
   ;; If FINAL is t, stay there
@@ -494,9 +804,9 @@
          show-window show-buffer match)
 
     (unless toc (error "Don't know which toc line to visit"))
-
+    
     (cond
-
+  
      ((eq (car toc) 'toc)
       ;; a toc entry
       (setq match (reftex-toc-find-section toc no-revisit)))
@@ -508,19 +818,19 @@
      ((memq (car toc) '(bof eof))
       ;; A file entry
       (setq match
-	    (let ((where (car toc))
-		  (file (nth 1 toc)))
-	      (if (or (not no-revisit) (reftex-get-buffer-visiting file))
-		  (progn
-		    (switch-to-buffer-other-window
-		     (reftex-get-file-buffer-force file nil))
-		    (goto-char (if (eq where 'bof) (point-min) (point-max))))
-		(message reftex-no-follow-message) nil))))
+            (let ((where (car toc))
+                  (file (nth 1 toc)))
+              (if (or (not no-revisit) (reftex-get-buffer-visiting file))
+                  (progn
+                    (switch-to-buffer-other-window 
+                     (reftex-get-file-buffer-force file nil))
+                    (goto-char (if (eq where 'bof) (point-min) (point-max))))
+                (message reftex-no-follow-message) nil))))
 
      ((stringp (car toc))
       ;; a label
       (setq match (reftex-show-label-location toc reftex-callback-fwd
-						no-revisit t))))
+                                                no-revisit t))))
 
     (setq show-window (selected-window)
           show-buffer (current-buffer))
@@ -542,46 +852,46 @@
       ;; If `show-window' is still live, show-buffer is already visible
       ;; so let's not make it visible in yet-another-window.
       (if (window-live-p show-window)
-	  (select-window show-window)
+	  (set-buffer show-buffer)
 	(switch-to-buffer show-buffer))
       (reftex-re-enlarge))
      (t nil))))
 
 (defun reftex-toc-find-section (toc &optional no-revisit)
   (let* ((file (nth 3 toc))
-	 (marker (nth 4 toc))
-	 (level (nth 5 toc))
-	 (literal (nth 7 toc))
-	 (emergency-point (nth 8 toc))
-	 (match
-	  (cond
-	   ((and (markerp marker) (marker-buffer marker))
-	    ;; Buffer is still live and we have the marker.  Should be easy.
-	    (switch-to-buffer-other-window (marker-buffer marker))
-	    (goto-char (marker-position marker))
-	    (or (looking-at (regexp-quote literal))
-		(looking-at (reftex-make-regexp-allow-for-ctrl-m literal))
-		(looking-at (reftex-make-desperate-section-regexp literal))
-		(looking-at (concat "\\\\"
-				    (regexp-quote
-				     (car
-				      (rassq level
-					     reftex-section-levels-all)))
-				    "[[{]?"))))
-	   ((or (not no-revisit)
-		(reftex-get-buffer-visiting file))
-	    ;; Marker is lost.  Use the backup method.
-	    (switch-to-buffer-other-window
-	     (reftex-get-file-buffer-force file nil))
-	    (goto-char (or emergency-point (point-min)))
-	    (or (looking-at (regexp-quote literal))
-		(let ((len (length literal)))
-		  (or (reftex-nearest-match (regexp-quote literal) len)
-		      (reftex-nearest-match
-		       (reftex-make-regexp-allow-for-ctrl-m literal) len)
-		      (reftex-nearest-match
-		       (reftex-make-desperate-section-regexp literal) len)))))
-	   (t (message reftex-no-follow-message) nil))))
+         (marker (nth 4 toc))
+         (level (nth 5 toc))
+         (literal (nth 7 toc))
+         (emergency-point (nth 8 toc))
+         (match
+          (cond
+           ((and (markerp marker) (marker-buffer marker))
+            ;; Buffer is still live and we have the marker.  Should be easy.
+            (switch-to-buffer-other-window (marker-buffer marker))
+            (goto-char (marker-position marker))
+            (or (looking-at (regexp-quote literal))
+                (looking-at (reftex-make-regexp-allow-for-ctrl-m literal))
+                (looking-at (reftex-make-desperate-section-regexp literal))
+                (looking-at (concat "\\\\"
+                                    (regexp-quote
+                                     (car 
+                                      (rassq level 
+                                             reftex-section-levels-all)))
+                                    "[[{]?"))))
+           ((or (not no-revisit)
+                (reftex-get-buffer-visiting file))
+            ;; Marker is lost.  Use the backup method.
+            (switch-to-buffer-other-window
+             (reftex-get-file-buffer-force file nil))
+            (goto-char (or emergency-point (point-min)))
+            (or (looking-at (regexp-quote literal))
+                (let ((len (length literal)))
+                  (or (reftex-nearest-match (regexp-quote literal) len)
+                      (reftex-nearest-match
+                       (reftex-make-regexp-allow-for-ctrl-m literal) len)
+                      (reftex-nearest-match
+                       (reftex-make-desperate-section-regexp literal) len)))))
+           (t (message reftex-no-follow-message) nil))))
     (when match
       (goto-char (match-beginning 0))
       (if (not (= (point) (point-max))) (recenter 1))
@@ -603,15 +913,17 @@
       (setq old (substring old (match-end 0))))
     new))
 
+;; Auto recentering of TOC window
 
 (defun reftex-recenter-toc-when-idle ()
   (and (> (buffer-size) 5)
        reftex-mode
        (not (active-minibuffer-window))
        (fboundp 'reftex-toc-mode)
-       (get-buffer-window "*toc*")
+       (get-buffer-window "*toc*" 'visible)
        (string= reftex-last-toc-master (reftex-TeX-master-file))
-       (reftex-toc-recenter)))
+       (let (current-prefix-arg)
+         (reftex-toc-recenter))))
 
 (defun reftex-toggle-auto-toc-recenter ()
   "Toggle the automatic recentering of the toc window.
@@ -620,20 +932,73 @@
   (interactive)
   (if reftex-toc-auto-recenter-timer
       (progn
-	(if (featurep 'xemacs)
-	    (delete-itimer reftex-toc-auto-recenter-timer)
-	  (cancel-timer reftex-toc-auto-recenter-timer))
-	(setq reftex-toc-auto-recenter-timer nil)
-	(message "Automatic recentering of toc buffer was turned off"))
+        (if (featurep 'xemacs)
+            (delete-itimer reftex-toc-auto-recenter-timer)
+          (cancel-timer reftex-toc-auto-recenter-timer))
+        (setq reftex-toc-auto-recenter-timer nil)
+        (message "Automatic recentering of toc windwo was turned off"))
     (setq reftex-toc-auto-recenter-timer
-	  (if (featurep 'xemacs)
-	      (start-itimer "RefTeX Idle Timer for recenter"
-			    'reftex-recenter-toc-when-idle
-			    reftex-idle-time reftex-idle-time t)
-	    (run-with-idle-timer
-	     reftex-idle-time t 'reftex-recenter-toc-when-idle)))
+          (if (featurep 'xemacs)
+              (start-itimer "RefTeX Idle Timer for recenter"
+                            'reftex-recenter-toc-when-idle
+                            reftex-idle-time reftex-idle-time t)
+            (run-with-idle-timer
+             reftex-idle-time t 'reftex-recenter-toc-when-idle)))
     (message "Automatic recentering of toc window was turned on")))
 
+(defun reftex-toc-toggle-dedicated-frame ()
+  "Toggle the display of a separate frame for the TOC.
+This frame is not used by the `reftex-toc' commands, but it is useful to
+always show the current section in connection with the option
+`reftex-auto-recenter-toc'."
+  (interactive)
+  (catch 'exit
+    (let* ((frames (frame-list)) frame
+           (get-frame-prop-func (if (fboundp 'frame-property)
+                                    'frame-property
+                                  'frame-parameter)))
+      (while (setq frame (pop frames))
+        (if (equal (funcall get-frame-prop-func frame 'name)
+                   "RefTeX TOC Frame")
+            (progn
+              (delete-frame frame)
+              (throw 'exit nil))))
+      (reftex-make-separate-toc-frame))))
+
+(defun reftex-make-separate-toc-frame ()
+  ;; Create a new fame showing only the toc buffer.
+  (let ((current-frame (selected-frame))
+        (current-window (selected-window))
+        (current-toc-window (get-buffer-window "*toc*" 'visible))
+        current-toc-frame)
+    (if (and current-toc-window
+             (not (equal (selected-frame) (window-frame current-toc-window))))
+        nil
+      (setq current-toc-frame
+            (make-frame
+             '((name . "RefTeX TOC Frame")
+               (height . 20) (width . 60)
+               (unsplittable . t)
+               (minibuffer . nil)
+               (default-toolbar-visible-p . nil)
+               (menubar-visible-p . nil)
+               (horizontal-scrollbar-visible-p . nil))))
+      (select-frame current-toc-frame)
+      (switch-to-buffer "*toc*")
+      (select-frame current-frame)
+      (if (fboundp 'focus-frame) (focus-frame current-frame)
+        (if (fboundp 'x-focus-frame) (x-focus-frame current-frame)))
+      (select-window current-window)
+      (when (eq reftex-auto-recenter-toc 'frame)
+        (unless reftex-toc-auto-recenter-timer
+          (reftex-toggle-auto-toc-recenter))
+        (add-hook 'delete-frame-hook 'reftex-toc-delete-frame-hook)))))
+
+(defun reftex-toc-delete-frame-hook (frame)
+  (if (and reftex-toc-auto-recenter-timer
+           (reftex-toc-dframe-p frame))
+      (progn
+      (reftex-toggle-auto-toc-recenter))))
 
 ;; Table of Contents map
 (define-key reftex-toc-map (if (featurep 'xemacs) [(button2)] [(mouse-2)])
@@ -645,47 +1010,57 @@
  'previous-line 'reftex-toc-previous reftex-toc-map global-map)
 
 (loop for x in
-      '(("n"    . reftex-toc-next)
-	("p"    . reftex-toc-previous)
-	("?"    . reftex-toc-show-help)
-	(" "    . reftex-toc-view-line)
-	("\C-m" . reftex-toc-goto-line-and-hide)
-	("\C-i" . reftex-toc-goto-line)
-	("\C-c>". reftex-toc-display-index)
-	("r"    . reftex-toc-rescan)
-	("R"    . reftex-toc-Rescan)
-	("g"    . revert-buffer)
-	("q"    . reftex-toc-quit)
-	("k"    . reftex-toc-quit-and-kill)
-	("f"    . reftex-toc-toggle-follow)
-	("a"    . reftex-toggle-auto-toc-recenter)
-	("F"    . reftex-toc-toggle-file-boundary)
-	("i"    . reftex-toc-toggle-index)
-	("l"    . reftex-toc-toggle-labels)
-	("t"    . reftex-toc-max-level)
-	("c"    . reftex-toc-toggle-context)
-	("%"    . reftex-toc-toggle-commented)
-	("x"    . reftex-toc-external)
-	("z"    . reftex-toc-jump)
-	("."    . reftex-toc-show-calling-point)
-	("\C-c\C-n" . reftex-toc-next-heading)
-	("\C-c\C-p" . reftex-toc-previous-heading))
+      '(("n"        . reftex-toc-next)
+        ("p"        . reftex-toc-previous)
+        ("?"        . reftex-toc-show-help)
+        (" "        . reftex-toc-view-line)
+        ("\C-m"     . reftex-toc-goto-line-and-hide)
+        ("\C-i"     . reftex-toc-goto-line)
+        ("\C-c>"    . reftex-toc-display-index)
+        ("r"        . reftex-toc-rescan)
+        ("R"        . reftex-toc-Rescan)
+        ("g"        . revert-buffer)
+        ("q"        . reftex-toc-quit);
+        ("k"        . reftex-toc-quit-and-kill)
+        ("f"        . reftex-toc-toggle-follow);
+        ("a"        . reftex-toggle-auto-toc-recenter)
+        ("d"        . reftex-toc-toggle-dedicated-frame)
+        ("F"        . reftex-toc-toggle-file-boundary)
+        ("i"        . reftex-toc-toggle-index)
+        ("l"        . reftex-toc-toggle-labels)
+        ("t"        . reftex-toc-max-level)
+        ("c"        . reftex-toc-toggle-context)
+;        ("%"        . reftex-toc-toggle-commented)
+        ("\M-%"     . reftex-toc-rename-label)
+        ("x"        . reftex-toc-external)
+        ("z"        . reftex-toc-jump)
+        ("."        . reftex-toc-show-calling-point)
+        ("\C-c\C-n" . reftex-toc-next-heading)
+        ("\C-c\C-p" . reftex-toc-previous-heading)
+        (">"        . reftex-toc-demote)
+        ("<"        . reftex-toc-promote))
       do (define-key reftex-toc-map (car x) (cdr x)))
 
 (loop for key across "0123456789" do
       (define-key reftex-toc-map (vector (list key)) 'digit-argument))
 (define-key reftex-toc-map "-" 'negative-argument)
 
-(easy-menu-define
+(easy-menu-define 
  reftex-toc-menu reftex-toc-map
  "Menu for Table of Contents buffer"
  '("TOC"
    ["Show Location" reftex-toc-view-line t]
    ["Go To Location" reftex-toc-goto-line t]
    ["Exit & Go To Location" reftex-toc-goto-line-and-hide t]
-   ["Index" reftex-toc-display-index t]
+   ["Show Calling Point" reftex-toc-show-calling-point t]
    ["Quit" reftex-toc-quit t]
    "--"
+   ("Edit"
+    ["Promote" reftex-toc-promote t]
+    ["Demote" reftex-toc-demote t]
+    ["Rename Label" reftex-toc-rename-label t])
+   "--"
+   ["Index" reftex-toc-display-index t]
    ["External Document TOC  " reftex-toc-external t]
    "--"
    ("Update"
@@ -703,10 +1078,13 @@
     ["Context" reftex-toc-toggle-context :style toggle
      :selected reftex-toc-include-context]
     "--"
-    ["Follow Mode" reftex-toc-toggle-follow :style toggle
-     :selected reftex-toc-follow-mode])
+    ["Follow Mode" reftex-toc-toggle-follow :style toggle 
+     :selected reftex-toc-follow-mode]
+    ["Auto Recenter" reftex-toggle-auto-toc-recenter :style toggle
+     :selected reftex-toc-auto-recenter-timer]
+    ["Dedicated Frame" reftex-toc-toggle-dedicated-frame t])
    "--"
    ["Help" reftex-toc-show-help t]))
 
 
-;;; reftex-toc.el ends here
+;;; reftex-toc.el ends here
\ No newline at end of file
--- a/lisp/textmodes/reftex-vars.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex-vars.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex-vars.el --- configuration variables for RefTeX
-;; Copyright (c) 1997, 1998, 1999, 2000 Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 
 ;; This file is part of GNU Emacs.
 
@@ -13,11 +13,11 @@
 
 ;; GNU Emacs is distributed in the hope that it will be useful,
 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
-;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE   See the
 ;; GNU General Public License for more details.
 
 ;; You should have received a copy of the GNU General Public License
-;; along with GNU Emacs; see the file COPYING.  If not, write to the
+;; along with GNU Emacs; see the file COPYING  If not, write to the
 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 ;; Boston, MA 02111-1307, USA.
 
@@ -93,28 +93,28 @@
     (LaTeX       "LaTeX default environments"
      (("section"   ?s "%S" "~\\ref{%s}" (nil . t)
        (regexp "parts?" "chapters?" "chap\\." "sections?" "sect?\\."
-	       "paragraphs?" "par\\."
-	       "\\\\S" "\247" "Teile?" "Kapitel" "Kap\\." "Abschnitte?"
-	       "appendi\\(x\\|ces\\)" "App\\."  "Anh\"?ange?" "Anh\\."))
+               "paragraphs?" "par\\."
+               "\\\\S" "\247" "Teile?" "Kapitel" "Kap\\." "Abschnitte?"
+               "appendi\\(x\\|ces\\)" "App\\."  "Anh\"?ange?" "Anh\\."))
 
       ("enumerate" ?i "item:" "~\\ref{%s}" item
        (regexp "items?" "Punkte?"))
-
+      
       ("equation"  ?e "eq:" "~(\\ref{%s})" t
        (regexp "equations?" "eqs?\\." "eqn\\." "Gleichung\\(en\\)?"  "Gl\\."))
       ("eqnarray"  ?e "eq:" nil eqnarray-like)
-
+      
       ("figure"    ?f "fig:" "~\\ref{%s}" caption
        (regexp "figure?[sn]?" "figs?\\." "Abbildung\\(en\\)?" "Abb\\."))
       ("figure*"   ?f nil nil caption)
-
+      
       ("table"     ?t "tab:" "~\\ref{%s}" caption
        (regexp "tables?" "tab\\." "Tabellen?"))
       ("table*"    ?t nil nil caption)
-
+      
       ("\\footnote[]{}" ?n "fn:" "~\\ref{%s}" 2
        (regexp "footnotes?" "Fussnoten?"))
-
+      
       ("any"       ?\  " "   "~\\ref{%s}" nil)
 
       ;; The label macro is hard coded, but it *could* be defined like this:
@@ -141,6 +141,19 @@
       (?A    . "\\citeauthor*{%l}")
       (?y    . "\\citeyear{%l}")
       (?n    . "\\nocite{%l}")))
+    (amsrefs "The AMSRefs package"
+     ((?\C-m . "\\cite{%l}")
+      (?p    . "\\cite{%l}")
+      (?P    . "\\cites{%l}")
+      (?t    . "\\ocite{%l}")
+      (?T    . "\\ocites{%l}")
+      (?y    . "\\ycite{%l}")
+      (?Y    . "\\ycites{%l}")
+      (?a    . "\\citeauthor{%l}")
+      (?A    . "\\citeauthory{%l}")
+      (?f    . "\\fullcite{%l}")
+      (?F    . "\\fullocite{%l}")
+      (?n    . "\\nocite{%l}")))
     (bibentry "The Bibentry package"
       "\\bibentry{%l}")
     (harvard "The Harvard package"
@@ -178,20 +191,20 @@
 `?t'    should point to a textual citation (citation as a noun).
 `?p'    should point to a parenthetical citation.")
 
-(defconst reftex-index-macros-builtin
+(defconst reftex-index-macros-builtin 
   '((default "Default \\index and \\glossary macros"
       (("\\index{*}" "idx" ?i "" nil t)
        ("\\glossary{*}" "glo" ?g "" nil t)))
     (multind "The multind.sty package"
        (("\\index{}{*}" 1 ?i "" nil t)))
     (index "The index.sty package"
-	   (("\\index[]{*}" 1 ?i "" nil t)
-	    ("\\index*[]{*}" 1 ?I "" nil nil)))
+           (("\\index[]{*}" 1 ?i "" nil t)
+            ("\\index*[]{*}" 1 ?I "" nil nil)))
     (Index-Shortcut "index.sty with \\shortindexingon"
        (("\\index[]{*}" 1 ?i "" nil t)
-	("\\index*[]{*}" 1 ?I "" nil nil)
-	("^[]{*}" 1 ?^ "" texmathp t)
-	("_[]{*}" 1 ?_ "" texmathp nil))))
+        ("\\index*[]{*}" 1 ?I "" nil nil)
+        ("^[]{*}" 1 ?^ "" texmathp t)   
+        ("_[]{*}" 1 ?_ "" texmathp nil))))
   "Builtin stuff for reftex-index-macros.
 Lower-case symbols correspond to a style file of the same name in the LaTeX
 distribution.  Mixed-case symbols are convenience aliases.")
@@ -202,8 +215,8 @@
 (defgroup reftex nil
   "LaTeX label and citation support."
   :tag "RefTeX"
-  :link '(url-link :tag "Home Page"
-		   "http://strw.leidenuniv.nl/~dominik/Tools/")
+  :link '(url-link :tag "Home Page" 
+                   "http://zon.astro.uva.nl/~dominik/Tools/")
   :link '(emacs-commentary-link :tag "Commentary in reftex.el" "reftex.el")
   :link '(custom-manual "(reftex)Top")
   :prefix "reftex-"
@@ -240,7 +253,6 @@
     ("subsubsection"   .  4)
     ("paragraph"       .  5)
     ("subparagraph"    .  6)
-    ("subsubparagraph" .  7)
     ("addchap"         . -1) ; KOMA-Script
     ("addsec"          . -2) ; KOMA-Script
 ;;; ("minisec"         . -7) ; KOMA-Script
@@ -251,14 +263,19 @@
 the backslash).  The cdr is a number indicating its level.  A negative
 level means the same level as the positive value, but the section will
 never get a number.  The cdr may also be a function which will be called
-to after the section-re matched to determine the level."
+to after the section-re matched to determine the level.
+This list is also used for promotion and demption of sectioning commands.
+If you are using a document class which has several sets of sectioning
+commands, promotion only works correctly if this list is sorted first
+by set, then within each set by level.  The promotion commands always
+select the nearest entry with the correct new level."
   :group 'reftex-table-of-contents-browser
   :set 'reftex-set-dirty
   :type '(repeat
           (cons (string :tag "sectioning macro" "")
-		(choice
-		 (number :tag "level           " 0)
-		 (symbol :tag "function        " my-level-func)))))
+                (choice
+                 (number :tag "level           " 0)
+                 (symbol :tag "function        " my-level-func)))))
 
 (defcustom reftex-toc-max-level 100
   "*The maximum level of toc entries which will be included in the TOC.
@@ -278,27 +295,43 @@
   :type 'boolean)
 
 
-(defcustom reftex-auto-recenter-toc nil
-  "*Non-nil means, initially turn automatic recentering of toc on.
-When active, the *TOC* buffer will always show the section you
+(defcustom reftex-auto-recenter-toc 'frame
+  "*Non-nil means, turn automatic recentering of *TOC* window on.
+When active, the *TOC* window will always show the section you
 are currently working in.  Recentering happens whenever Emacs is idle for
 more than `reftex-idle-time' seconds.
-This feature can be turned on and off from the menu
-(Ref->Options)."
+
+Value t means, turn on immediately when RefTeX gets started.  Then,
+recentering will work for any toc window created during the session.
+
+Value 'frame (the default) means, turn automatic recentering on only while the
+dedicated TOC frame does exist, and do the recentering only in that frame.  So
+when creating that frame (with \"d\" key in an ordinary TOC window), the
+automatic recentering is turned on.  When the frame gets destroyed, automatic
+recentering is turned off again.
+
+This feature can be turned on and off from the menu 
+\(Ref->Options)."
   :group 'reftex-table-of-contents-browser
-  :type 'boolean)
-
+  :type '(choice
+          (const :tag "never" nil)
+          (const :tag "always" t)
+          (const :tag "in dedicated frame only" 'frame)))
+ 
 (defcustom reftex-toc-split-windows-horizontally nil
   "*Non-nil means, create TOC window by splitting window horizontally."
   :group 'reftex-table-of-contents-browser
   :type 'boolean)
 
-(defcustom reftex-toc-split-windows-horizontally-fraction .5
-  "*Fraction of the horizontal width of the frame to be used for TOC window.
-Only relevant when `reftex-toc-split-windows-horizontally' is non-nil."
+(defcustom reftex-toc-split-windows-fraction .3
+  "*Fraction of the width or height of the frame to be used for TOC window.
+See also `reftex-toc-split-windows-horizontally'."
   :group 'reftex-table-of-contents-browser
   :type 'number)
 
+(defvar reftex-toc-split-windows-horizontally-fraction 0.5
+  "This variable is obsolete, use `reftex-toc-split-windows-fraction' instead.")
+
 (defcustom reftex-toc-keep-other-windows t
   "*Non-nil means, split the selected window to display the *toc* buffer.
 This helps to keep the window configuration, but makes the *toc* small.
@@ -325,6 +358,17 @@
   :group 'reftex-table-of-contents-browser
   :type 'boolean)
 
+(defcustom reftex-toc-confirm-promotion 2
+  "*Non-nil means, promotion/demotion commands first prompt for confirmation.
+When nil, the command is executed immediately.  When this is an integer
+N, ask for confirmation only if N or more section commands are going to be
+changed."
+  :group 'reftex-table-of-contents-browser
+  :type '(choice
+          (const  :tag "Never" nil)
+          (const  :tag "Always" t)
+          (number :tag "When more than N sections" :value 2)))
+
 (defcustom reftex-toc-include-context nil
   "*Non-nil means, include context with labels in the *toc* buffer.
 Context will only be shown when labels are visible as well.
@@ -363,22 +407,22 @@
 
 (defcustom reftex-default-label-alist-entries
   '(amsmath endnotes fancybox floatfig longtable picinpar
-	    rotating sidecap subfigure supertab wrapfig LaTeX)
+            rotating sidecap subfigure supertab wrapfig LaTeX)
   "Default label alist specifications.  LaTeX should always be the last entry.
-The value of this variable is a list of symbols with associations in the
+The value of this variable is a list of symbols with associations in the 
 constant `reftex-label-alist-builtin'.  Check that constant for a full list
 of options."
   :group 'reftex-defining-label-environments
   :set   'reftex-set-dirty
   :type `(set
-	  :indent 4
+          :indent 4
           :inline t
           :greedy t
           ,@(mapcar
-	     (lambda (x)
-	       (list 'const :tag (concat (symbol-name (nth 0 x))
-					 ": " (nth 1 x))
-		     (nth 0 x)))
+             (lambda (x)
+               (list 'const :tag (concat (symbol-name (nth 0 x))
+                                         ": " (nth 1 x))
+                     (nth 0 x)))
              reftex-label-alist-builtin)))
 
 (defcustom reftex-label-alist nil
@@ -526,10 +570,10 @@
            (choice    :tag "Environment or \\macro "
                       (const  :tag "Ignore, just use typekey" nil)
                       (string "")
-		      (symbol :tag "Special parser" my-parser))
-	   (choice    :tag "Type specification    "
-		      (const :tag "unspecified, like in \\label" nil)
-		      (character :tag "Char  " ?a))
+                      (symbol :tag "Special parser" my-parser))
+           (choice    :tag "Type specification    "
+                      (const :tag "unspecified, like in \\label" nil)
+                      (character :tag "Char  " ?a))
            (choice    :tag "Label prefix string   "
                       (const  :tag "Default" nil)
                       (string :tag "String" "lab:"))
@@ -537,44 +581,44 @@
                       (const  :tag "Default" nil)
                       (string :tag "String" "~\\ref{%s}"))
            (choice    :tag "Context method        "
-		      (const  :tag "Default position" t)
-		      (const  :tag "After label"      nil)
-		      (number :tag "Macro arg nr" 1)
-		      (regexp :tag "Regexp" "")
-		      (const  :tag "Caption in float" caption)
-		      (const  :tag "Item in list" item)
-		      (const  :tag "Eqnarray-like" eqnarray-like)
-		      (const  :tag "Alignat-like" alignat-like)
-		      (symbol :tag "Function" my-func))
-	   (repeat :tag "Magic words" :extra-offset 2 (string))
-	   (option (choice :tag "Make TOC entry     "
-			   (const :tag "No entry" nil)
-			   (integer :tag "Level" :value -3))))
+                      (const  :tag "Default position" t)
+                      (const  :tag "After label"      nil)
+                      (number :tag "Macro arg nr" 1)
+                      (regexp :tag "Regexp" "")
+                      (const  :tag "Caption in float" caption)
+                      (const  :tag "Item in list" item)
+                      (const  :tag "Eqnarray-like" eqnarray-like)
+                      (const  :tag "Alignat-like" alignat-like)
+                      (symbol :tag "Function" my-func))
+           (repeat :tag "Magic words" :extra-offset 2 (string))
+           (option (choice :tag "Make TOC entry     "
+                           (const :tag "No entry" nil)
+                           (integer :tag "Level" :value -3))))
      (choice
       :tag "Package"
       :value AMSTeX
       ,@(mapcar
-	 (lambda (x)
-	   (list 'const :tag (concat (symbol-name (nth 0 x)))
-		 (nth 0 x)))
-	 reftex-label-alist-builtin)))))
+         (lambda (x)
+           (list 'const :tag (concat (symbol-name (nth 0 x)))
+                 (nth 0 x)))
+         reftex-label-alist-builtin)))))
 
 (defcustom reftex-section-prefixes '((0 . "part:") (1 . "cha:") (t . "sec:"))
   "Prefixes for section labels.
 When the label prefix given in an entry in `reftex-label-alist' contains `%S',
-this list is used to determine the correct prefix string depending on the
+this list is used to determine the correct prefix string depending on the 
 current section level.
 The list is an alist, with each entry of the form (KEY . PREFIX)
 Possible keys are sectioning macro names like `chapter', section levels
-(as given in `reftex-section-levels'), and t for the default."
+\(as given in `reftex-section-levels'), and t for the default."
   :group 'reftex-defining-label-environments
   :type '(repeat
-	  (cons :value (0 . "")
-		(choice
-		 (string :tag  "macro name")
-		 (integer :tag "section level")
-		 (const :tag "default" t))
-		(string :tag "Prefix"))))
+          (cons :value (0 . "")
+                (choice
+                 (string :tag  "macro name")
+                 (integer :tag "section level")
+                 (const :tag "default" t))
+                (string :tag "Prefix"))))
 
 (defcustom reftex-default-context-regexps
   '((caption       . "\\\\\\(rot\\)?caption\\*?[[{]")
@@ -587,7 +631,7 @@
 or macro."
   :group 'reftex-defining-label-environments
   :type '(repeat (cons (symbol) (regexp))))
-
+  
 (defcustom reftex-special-environment-functions nil
   "List of functions to be called when trying to figure out current environment.
 These are special functions to detect \"environments\" which do not
@@ -633,7 +677,7 @@
      (let ((pos (point)) p1)
        (save-excursion
          ;; Search for any of the linguex item macros at the beginning of a line
-         (if (re-search-backward
+         (if (re-search-backward 
               \"^[ \\t]*\\\\(\\\\\\\\\\\\(ex\\\\|a\\\\|b\\\\|c\\\\|d\\\\|e\\\\|f\\\\)g?\\\\.\\\\)\" bound t)
              (progn
                (setq p1 (match-beginning 1))
@@ -643,7 +687,7 @@
                    nil
                  ;; OK, we got it
                  (cons \"linguex\" p1)))
-           ;; Return nil for not found
+           ;; Return nil for not found 
            nil))))
 
 3. Tell RefTeX to use this function
@@ -690,7 +734,7 @@
 like character classes.
 Thus, the combination may be set differently for each label type.  The
 default settings \"s\" and \"sft\" mean: Derive section labels from headings
-(with confirmation).  Prompt for figure and table labels.  Use simple labels
+\(with confirmation).  Prompt for figure and table labels.  Use simple labels
 without confirmation for everything else.
 The available label types are: s (section), f (figure), t (table), i (item),
 e (equation), n (footnote), N (endnote), plus any definitions in
@@ -751,7 +795,7 @@
                 (repeat  :tag "Ignore words"
                          :entry-format "           %i %d %v"
                          (string :tag ""))
-		(option (boolean :tag "Downcase words          "))))
+                (option (boolean :tag "Downcase words          "))))
 
 (defcustom reftex-label-illegal-re "[^-a-zA-Z0-9_+=:;,.]"
   "Regexp matching characters not legal in labels."
@@ -827,7 +871,7 @@
     (choice :tag "Hide short context              " ,@reftex-tmp)
     (choice :tag "Follow context in other window  " ,@reftex-tmp)
     (choice :tag "Show commented labels           " ,@reftex-tmp)
-    (choice :tag "Obsolete flag.  Don't use.      " ,@reftex-tmp)
+    (choice :tag "Obsolete flag,  Don't use.      " ,@reftex-tmp)
     (choice :tag "Show begin/end of included files" ,@reftex-tmp)))
 
 (defcustom reftex-multiref-punctuation '((?, . ", ") (?- . "--") (?+ . " and "))
@@ -842,7 +886,7 @@
 
 (defcustom reftex-vref-is-default nil
   "*Non-nil means, the varioref macro \\vref is used as default.
-In the selection buffer, the `v' key toggles the reference macro between
+In the selection buffer, the `v' key toggles the reference macro between 
 `\\ref' and `\\vref'.  The value of this variable determines the default
 which is active when entering the selection process.
 Instead of nil or t, this may also be a string of type letters indicating
@@ -852,7 +896,7 @@
 
 (defcustom reftex-fref-is-default nil
   "*Non-nil means, the fancyref macro \\fref is used as default.
-In the selection buffer, the `V' key toggles the reference macro between
+In the selection buffer, the `V' key toggles the reference macro between 
 `\\ref', `\\fref' and `\\Fref'.  The value of this variable determines
 the default which is active when entering the selection process.
 Instead of nil or t, this may also be a string of type letters indicating
@@ -876,7 +920,7 @@
 
 (defcustom reftex-format-ref-function nil
   "Function which produces the string to insert as a reference.
-Normally should be nil, because the format to insert a reference can
+Normally should be nil, because the format to insert a reference can 
 already be specified in `reftex-label-alist'.
 This hook also is used by the special commands to insert `\\vref' and `\\fref'
 references, so even if you set this, your setting will be ignored by
@@ -957,13 +1001,13 @@
 %i institution   %j journal        %k key        %m month
 %n number        %o organization   %p pages      %P first page
 %r address       %s school         %u publisher  %t title
-%v volume        %y year
+%v volume        %y year          
 %B booktitle, abbreviated          %T title, abbreviated
 
 Usually, only %l is needed.  The other stuff is mainly for the echo area
 display, and for (setq reftex-comment-citations t).
 
-%< as a special operator kills punctuation and space around it after the
+%< as a special operator kills punctuation and space around it after the 
 string has been formatted.
 
 Beware that all this only works with BibTeX database files.  When
@@ -975,7 +1019,7 @@
 strings.
   In order to configure this variable, you can either set
 `reftex-cite-format' directly yourself or set it to the SYMBOL of one of
-the predefined styles.  The predefined symbols are those which have an
+the predefined styles.  The predefined symbols are those which have an 
 association in the constant `reftex-cite-format-builtin'.
 E.g.: (setq reftex-cite-format 'natbib)"
   :group 'reftex-citation-support
@@ -1033,7 +1077,7 @@
 
 (defcustom reftex-format-cite-function nil
   "Function which produces the string to insert as a citation.
-Normally should be nil, because the format to insert a reference can
+Normally should be nil, because the format to insert a reference can 
 already be specified in `reftex-cite-format'.
 The function will be called with two arguments, the CITATION KEY and the
 DEFAULT FORMAT, which is taken from `reftex-cite-format'.  The function
@@ -1066,16 +1110,16 @@
 These correspond to the makeindex keywords LEVEL ENCAP ACTUAL QUOTE ESCAPE."
   :group 'reftex-index-support
   :type '(list
-	  (string :tag "LEVEL  separator")
-	  (string :tag "ENCAP  char     ")
-	  (string :tag "ACTUAL char     ")
-	  (string :tag "QUOTE  char     ")
-	  (string :tag "ESCAPE char     ")))
+          (string :tag "LEVEL  separator")
+          (string :tag "ENCAP  char     ")
+          (string :tag "ACTUAL char     ")
+          (string :tag "QUOTE  char     ")
+          (string :tag "ESCAPE char     ")))
 
 (defcustom reftex-index-macros nil
   "Macros which define index entries.  The structure is
 
-(MACRO INDEX-TAG KEY PREFIX EXCLUDE REPEAT)
+\(MACRO INDEX-TAG KEY PREFIX EXCLUDE REPEAT)
 
 MACRO is the macro.  Arguments should be denoted by empty braces like
 \\index[]{*}.  Use square brackets to denote optional arguments.  The star
@@ -1116,43 +1160,43 @@
   :group 'reftex-index-support
   :set 'reftex-set-dirty
   :type `(list
-	  (repeat
-	   :inline t
-	   (list :value ("" "idx" ?a "" nil)
-		 (string  :tag "Macro with args")
-		 (choice  :tag "Index Tag      "
-			 (string)
-			 (integer :tag "Macro arg Nr" :value 1))
-		 (character :tag "Access Key     ")
-		 (string  :tag "Key Prefix     ")
-		 (symbol  :tag "Exclusion hook ")
+          (repeat 
+           :inline t
+           (list :value ("" "idx" ?a "" nil)
+                 (string  :tag "Macro with args")
+                 (choice  :tag "Index Tag      "
+                         (string)
+                         (integer :tag "Macro arg Nr" :value 1))
+                 (character :tag "Access Key     ")
+                 (string  :tag "Key Prefix     ")
+                 (symbol  :tag "Exclusion hook ")
                  (boolean :tag "Repeat Outside ")))
-	  (option
-	   :tag "Package:"
-	   (choice :tag "Package"
-		   :value index
-		   ,@(mapcar
-		      (lambda (x)
-			(list 'const :tag (concat (symbol-name (nth 0 x))
-						  ": " (nth 1 x))
-			      (nth 0 x)))
-		      reftex-index-macros-builtin)))))
+          (option
+           :tag "Package:"
+           (choice :tag "Package"
+                   :value index
+                   ,@(mapcar
+                      (lambda (x)
+                        (list 'const :tag (concat (symbol-name (nth 0 x))
+                                                  ": " (nth 1 x))
+                              (nth 0 x)))
+                      reftex-index-macros-builtin)))))
 
 (defcustom reftex-index-default-macro '(?i "idx")
   "The default index macro for \\[reftex-index-selection-or-word].
 This is a list with (MACRO-KEY DEFAULT-TAG).
 
 MACRO-KEY:   Character identifying an index macro - see `reftex-index-macros'.
-DEFAULT-TAG: This is the tag to be used if the macro requires a TAG argument.
+DEFAULT-TAG: This is the tag to be used if the macro requires a TAG argument.  
              When this is nil and a TAG is needed, RefTeX will ask for it.
              When this is the empty string and the TAG argument of the index
              macro is optional, the TAG argument will be omitted."
   :group 'reftex-index-support
   :type '(list
-	  (character :tag "Character identifying default macro")
-	  (choice    :tag "Default index tag                  "
-		  (const nil)
-		  (string))))
+          (character :tag "Character identifying default macro")
+          (choice    :tag "Default index tag                  "
+                  (const nil)
+                  (string))))
 
 (defcustom reftex-index-default-tag "idx"
   "Default index tag.
@@ -1166,16 +1210,16 @@
 last      The last used index tag will be offered as default."
   :group 'reftex-index-support
   :type '(choice
-	  (const :tag  "no default" nil)
-	  (const :tag  "last used " 'last)
-	  (string :tag "index tag " "idx")))
+          (const :tag  "no default" nil)
+          (const :tag  "last used " 'last)
+          (string :tag "index tag " "idx")))
 
 (defcustom reftex-index-math-format "$%s$"
   "Format of index entries when copied from inside math mode.
 When `reftex-index-selection-or-word' is executed inside TeX math mode,
 the index key copied from the buffer is processed with this format string
 through the `format' function.  This can be used to add the math delimiters
-(e.g. `$') to the string.
+\(e.g. `$') to the string.
 Requires the `texmathp.el' library which is part of AUCTeX."
   :group 'reftex-index-support
   :type 'string)
@@ -1229,8 +1273,8 @@
 If the function returns nil, the current match is skipped."
   :group 'reftex-index-support
   :type '(choice
-	  (const :tag "No verification" nil)
-	  (function)))
+          (const :tag "No verification" nil)
+          (function)))
 
 (defcustom reftex-index-phrases-skip-indexed-matches nil
   "*Non-nil means, skip matches which appear to be indexed already.
@@ -1238,7 +1282,7 @@
 phrases may match at places where that phrase was already indexed.  In
 particular when indexing an already processed document again, this
 will even be the norm.  When this variable is non-nil, RefTeX checks if
-the match is an index macro argument, or if an index macro is directly
+the match is inside an index macro argument, or if an index macro is directly
 before or after the phrase.  If that is the case, that match will
 be ignored."
   :group 'reftex-index-support
@@ -1282,7 +1326,7 @@
 
 (defcustom reftex-index-include-context nil
   "*Non-nil means, display the index definition context in the index buffer.
-This flag may also be toggled from the index buffer with the `c' key."
+This flag may also be toggled from the index buffer with the `c' key." 
   :group 'reftex-index-support
   :type 'boolean)
 
@@ -1305,9 +1349,9 @@
 argument of a macro.  Note that crossref viewing for citations,
 references (both ways) and index entries is hard-coded.  This variable
 is only to configure additional structures for which crossreference
-viewing can be useful.  Each entry has the structure
+viewing can be useful.  Each entry has the structure 
 
-(MACRO-RE SEARCH-RE HIGHLIGHT).
+\(MACRO-RE SEARCH-RE HIGHLIGHT).
 
 MACRO-RE is matched against the macro.  SEARCH-RE is the regexp used
 to search for cross references.  `%s' in this regexp is replaced with
@@ -1315,8 +1359,8 @@
 which subgroup of the match should be highlighted."
   :group 'reftex-viewing-cross-references
   :type '(repeat (group (regexp  :tag "Macro  Regexp  ")
-			(string  :tag "Search Regexp  ")
-			(integer :tag "Highlight Group"))))
+                        (string  :tag "Search Regexp  ")
+                        (integer :tag "Highlight Group"))))
 
 (defcustom reftex-auto-view-crossref t
   "*Non-nil means, initially turn automatic viewing of crossref info on.
@@ -1326,12 +1370,12 @@
 displayed, the echo area will display information about that cross
 reference.  You can also set the variable to the symbol `window'.  In
 this case a small temporary window is used for the display.
-This feature can be turned on and off from the menu
-(Ref->Options)."
+This feature can be turned on and off from the menu 
+\(Ref->Options)."
   :group 'reftex-viewing-cross-references
   :type '(choice (const :tag "off" nil)
-		 (const :tag "in Echo Area" t)
-		 (const :tag "in Other Window" window)))
+                 (const :tag "in Echo Area" t)
+                 (const :tag "in Other Window" window)))
 
 (defcustom reftex-idle-time 1.2
   "*Time (secs) Emacs has to be idle before automatic crossref display is done.
@@ -1372,7 +1416,7 @@
 - If an element is the name of an environment variable, its content is used.
 - If an element starts with an exclamation mark, it is used as a command
   to retrieve the path.  A typical command with the kpathsearch library would
-  be `!kpsewhich -show-path=.tex'.
+  be `!kpsewhich -show-path=.tex'. 
 - Otherwise the element itself is interpreted as a path.
 Multiple directories can be separated by the system dependent `path-separator'.
 Directories ending in `//' or `!!' will be expanded recursively.
@@ -1387,7 +1431,7 @@
 - If an element is the name of an environment variable, its content is used.
 - If an element starts with an exclamation mark, it is used as a command
   to retrieve the path.  A typical command with the kpathsearch library would
-  be `!kpsewhich -show-path=.bib'.
+  be `!kpsewhich -show-path=.bib'. 
 - Otherwise the element itself is interpreted as a path.
 Multiple directories can be separated by the system dependent `path-separator'.
 Directories ending in `//' or `!!' will be expanded recursively.
@@ -1398,7 +1442,7 @@
   :type '(repeat (string :tag "Specification")))
 
 (defcustom reftex-file-extensions '(("tex" . (".tex" ".ltx"))
-				    ("bib" . (".bib")))
+                                    ("bib" . (".bib")))
   "*Association list with file extensions for different file types.
 This is a list of items, each item is like: (TYPE . (DEF-EXT OTHER-EXT ...))
 
@@ -1413,7 +1457,7 @@
 TeX-file-extensions."
   :group 'reftex-finding-files
   :type '(repeat (cons (string :tag "File type")
-		       (repeat (string :tag "Extension")))))
+                       (repeat (string :tag "Extension")))))
 
 (defcustom reftex-search-unrecursed-path-first t
   "*Non-nil means, search all specified directories before trying recursion.
@@ -1432,13 +1476,13 @@
 TEXINPUTS and BIBINPUTS to find TeX files and BibTeX database files.
 With this option turned on, it calls an external program specified in the
 option `reftex-external-file-finders' instead.  As a side effect,
-the variables `reftex-texpath-environment-variables' and
+the variables `reftex-texpath-environment-variables' and 
 `reftex-bibpath-environment-variables' will be ignored."
   :group 'reftex-finding-files
   :type 'boolean)
 
 (defcustom reftex-external-file-finders '(("tex" . "kpsewhich -format=.tex %f")
-					  ("bib" . "kpsewhich -format=.bib %f"))
+                                          ("bib" . "kpsewhich -format=.bib %f"))
   "*Association list with external programs to call for finding files.
 Each entry is a cons cell (TYPE . PROGRAM).
 TYPE is either \"tex\" or \"bib\".  PROGRAM is the external program to use with
@@ -1447,7 +1491,7 @@
 Only relevant when `reftex-use-external-file-finders' is non-nil."
   :group 'reftex-finding-files
   :type '(repeat (cons (string :tag "File type")
-		       (string :tag "Program  "))))
+                       (string :tag "Program  "))))
 
 ;; Tuning the parser ----------------------------------------------------
 
@@ -1523,7 +1567,7 @@
 (defcustom reftex-save-parse-info nil
   "*Non-nil means, save information gathered with parsing in a file.
 The file MASTER.rel in the same directory as MASTER.tex is used to save the
-information.  When this variable is t,
+information.  When this variable is t, 
 - accessing the parsing information for the first time in an editing session
   will read that file (if available) instead of parsing the document.
 - exiting Emacs or killing a buffer in reftex-mode will cause a new version
@@ -1607,10 +1651,10 @@
 to become effective (keys `g' or `r')."
   :group 'reftex-fontification-configurations
   :type '(choice
-	  (const :tag "Never" nil)
-	  (const :tag "Cursor driven" cursor)
-	  (const :tag "Mouse driven" mouse)
-	  (const :tag "Mouse and Cursor driven." both)))
+          (const :tag "Never" nil)
+          (const :tag "Cursor driven" cursor)
+          (const :tag "Mouse driven" mouse)
+          (const :tag "Mouse and Cursor driven." both)))
 
 (defcustom reftex-cursor-selected-face 'highlight
   "Face name to highlight cursor selected item in toc and selection buffers.
@@ -1716,18 +1760,18 @@
 may require a restart of Emacs in order to become effective."
   :group 'reftex-miscellaneous-configurations
   :group 'LaTeX
-  :type '(choice
-	  (const :tag "No plug-ins" nil)
-	  (const :tag "All possible plug-ins" t)
-	  (list
-	   :tag "Individual choice"
-	   :value (t t t t t)
-	   (boolean :tag "supply label in new sections and environments")
-	   (boolean :tag "supply argument for macros like `\\label'     ")
-	   (boolean :tag "supply argument for macros like `\\ref'       ")
-	   (boolean :tag "supply argument for macros like `\\cite'      ")
-	   (boolean :tag "supply argument for macros like `\\index'     ")
-	   )))
+  :type '(choice 
+          (const :tag "No plug-ins" nil)
+          (const :tag "All possible plug-ins" t)
+          (list
+           :tag "Individual choice"
+           :value (t t t t t)
+           (boolean :tag "supply label in new sections and environments")
+           (boolean :tag "supply argument for macros like `\\label'     ")
+           (boolean :tag "supply argument for macros like `\\ref'       ")
+           (boolean :tag "supply argument for macros like `\\cite'      ")
+           (boolean :tag "supply argument for macros like `\\index'     ")
+           )))
 
 (defcustom reftex-allow-detached-macro-args nil
   "*Non-nil means, allow arguments of macros to be detached by whitespace.
@@ -1747,6 +1791,7 @@
   :group 'reftex-miscellaneous-configurations
   :type 'hook)
 
+
 (provide 'reftex-vars)
 
 ;;; reftex-vars.el ends here
--- a/lisp/textmodes/reftex.el	Mon Aug 11 12:25:27 2003 +0000
+++ b/lisp/textmodes/reftex.el	Mon Aug 11 12:27:02 2003 +0000
@@ -1,8 +1,8 @@
 ;;; reftex.el --- minor mode for doing \label, \ref, \cite, \index in LaTeX
-;; Copyright (c) 1997, 1998, 1999, 2000, 2003  Free Software Foundation, Inc.
+;; Copyright (c) 1997, 1998, 1999, 2000, 2003 Free Software Foundation, Inc.
 
 ;; Author: Carsten Dominik <dominik@science.uva.nl>
-;; Version: 4.18
+;; Version: 4.21
 ;; Keywords: tex
 
 ;; This file is part of GNU Emacs.
@@ -25,7 +25,7 @@
 ;;---------------------------------------------------------------------------
 ;;
 ;;; Commentary:
-;;
+;; 
 ;; RefTeX is a minor mode with distinct support for \ref, \label, \cite,
 ;; and \index commands in (multi-file) LaTeX documents.
 ;; - A table of contents provides easy access to any part of a document.
@@ -64,13 +64,13 @@
 ;;
 ;; The documentation in various formats is also available at
 ;;
-;;     http://www.strw.leidenuniv.nl/~dominik/Tools/
+;;     http://zon.astro.uva.nl/~dominik/Tools/
 ;;
 ;;---------------------------------------------------------------------------
 ;;
 ;; Introduction
 ;; ************
-;;
+;; 
 ;; RefTeX is a specialized package for support of labels, references,
 ;; citations, and the index in LaTeX.  RefTeX wraps itself round 4 LaTeX
 ;; macros: `\label', `\ref', `\cite', and `\index'.  Using these macros
@@ -79,13 +79,13 @@
 ;; time-consuming tasks almost entirely.  It also provides functions to
 ;; display the structure of a document and to move around in this
 ;; structure quickly.
-;;
+;; 
 ;;    *Note Imprint::, for information about who to contact for help, bug
 ;; reports or suggestions.
-;;
+;; 
 ;; Environment
 ;; ===========
-;;
+;; 
 ;; RefTeX needs to access all files which are part of a multifile
 ;; document, and the BibTeX database files requested by the
 ;; `\bibliography' command.  To find these files, RefTeX will require a
@@ -94,26 +94,26 @@
 ;; which are also used by RefTeX.  However, on some systems these
 ;; variables do not contain the full search path.  If RefTeX does not work
 ;; for you because it cannot find some files, read *Note Finding Files::.
-;;
+;; 
 ;; Entering RefTeX Mode
 ;; ====================
-;;
+;; 
 ;; To turn RefTeX Mode on and off in a particular buffer, use `M-x
 ;; reftex-mode'.  To turn on RefTeX Mode for all LaTeX files, add the
 ;; following lines to your `.emacs' file:
-;;
+;; 
 ;;      (add-hook 'LaTeX-mode-hook 'turn-on-reftex)   ; with AUCTeX LaTeX mode
 ;;      (add-hook 'latex-mode-hook 'turn-on-reftex)   ; with Emacs latex mode
-;;
+;; 
 ;; RefTeX in a Nutshell
 ;; ====================
-;;
+;; 
 ;;   1. Table of Contents
 ;;      Typing `C-c =' (`reftex-toc') will show a table of contents of the
 ;;      document.  This buffer can display sections, labels and index
 ;;      entries defined in the document.  From the buffer, you can jump
 ;;      quickly to every part of your document.  Press `?' to get help.
-;;
+;; 
 ;;   2. Labels and References
 ;;      RefTeX helps to create unique labels and to find the correct key
 ;;      for references quickly.  It distinguishes labels for different
@@ -121,7 +121,7 @@
 ;;      others), and can be configured to recognize any additional labeled
 ;;      environments you have defined yourself (variable
 ;;      `reftex-label-alist').
-;;
+;; 
 ;;         * Creating Labels
 ;;           Type `C-c (' (`reftex-label') to insert a label at point.
 ;;           RefTeX will either
@@ -130,17 +130,17 @@
 ;;                tables) or
 ;;              - insert a simple label made of a prefix and a number (all
 ;;                other environments)
-;;
+;; 
 ;;           Which labels are created how is configurable with the variable
 ;;           `reftex-insert-label-flags'.
-;;
+;; 
 ;;         * Referencing Labels
 ;;           To make a reference, type `C-c )' (`reftex-reference').  This
 ;;           shows an outline of the document with all labels of a certain
 ;;           type (figure, equation,...) and some label context.
 ;;           Selecting a label inserts a `\ref{LABEL}' macro into the
 ;;           original buffer.
-;;
+;; 
 ;;   3. Citations
 ;;      Typing `C-c [' (`reftex-citation') will let you specify a regular
 ;;      expression to search in current BibTeX database files (as
@@ -149,7 +149,7 @@
 ;;      sorted.  The selected article is referenced as `\cite{KEY}' (see
 ;;      the variable `reftex-cite-format' if you want to insert different
 ;;      macros).
-;;
+;; 
 ;;   4. Index Support
 ;;      RefTeX helps to enter index entries.  It also compiles all entries
 ;;      into an alphabetically sorted `*Index*' buffer which you can use
@@ -157,25 +157,25 @@
 ;;      index macros and can be configured to recognize any additional
 ;;      macros you have defined (`reftex-index-macros').  Multiple indices
 ;;      are supported.
-;;
+;; 
 ;;         * Creating Index Entries
 ;;           To index the current selection or the word at point, type
 ;;           `C-c /' (`reftex-index-selection-or-word').  The default macro
 ;;           `reftex-index-default-macro' will be used.  For a more
 ;;           complex entry type `C-c <' (`reftex-index'), select any of
 ;;           the index macros and enter the arguments with completion.
-;;
+;; 
 ;;         * The Index Phrases File (Delayed Indexing)
 ;;           Type `C-c \' (`reftex-index-phrase-selection-or-word') to add
 ;;           the current word or selection to a special _index phrase
 ;;           file_.  RefTeX can later search the document for occurrences
 ;;           of these phrases and let you interactively index the matches.
-;;
+;; 
 ;;         * Displaying and Editing the Index
 ;;           To display the compiled index in a special buffer, type `C-c
 ;;           >' (`reftex-display-index').  From that buffer you can check
 ;;           and edit all entries.
-;;
+;; 
 ;;   5. Viewing Cross-References
 ;;      When point is on the KEY argument of a cross-referencing macro
 ;;      (`\label', `\ref', `\cite', `\bibitem', `\index', and variations)
@@ -185,14 +185,14 @@
 ;;      When the enclosing macro is `\cite' or `\ref' and no other message
 ;;      occupies the echo area, information about the citation or label
 ;;      will automatically be displayed in the echo area.
-;;
+;; 
 ;;   6. Multifile Documents
 ;;      Multifile Documents are fully supported.  The included files must
 ;;      have a file variable `TeX-master' or `tex-main-file' pointing to
 ;;      the master file.  RefTeX provides cross-referencing information
 ;;      from all parts of the document, and across document borders
 ;;      (`xr.sty').
-;;
+;; 
 ;;   7. Document Parsing
 ;;      RefTeX needs to parse the document in order to find labels and
 ;;      other information.  It does it automatically once and updates its
@@ -201,23 +201,23 @@
 ;;      with a raw `C-u' prefix, or press the `r' key in the label
 ;;      selection buffer, the table of contents buffer, or the index
 ;;      buffer.
-;;
+;; 
 ;;   8. AUCTeX
 ;;      If your major LaTeX mode is AUCTeX, RefTeX can cooperate with it
 ;;      (see variable `reftex-plug-into-AUCTeX').  AUCTeX contains style
 ;;      files which trigger appropriate settings in RefTeX, so that for
 ;;      many of the popular LaTeX packages no additional customizations
 ;;      will be necessary.
-;;
+;; 
 ;;   9. Useful Settings
 ;;      To make RefTeX faster for large documents, try these:
 ;;           (setq reftex-enable-partial-scans t)
 ;;           (setq reftex-save-parse-info t)
 ;;           (setq reftex-use-multiple-selection-buffers t)
-;;
+;; 
 ;;      To integrate with AUCTeX, use
 ;;           (setq reftex-plug-into-AUCTeX t)
-;;
+;; 
 ;;      To make your own LaTeX macro definitions known to RefTeX,
 ;;      customize the variables
 ;;           `reftex-label-alist'          (for label macros/environments)
@@ -227,7 +227,7 @@
 ;;           `reftex-index-default-macro'  (to set the default macro)
 ;;      If you have a large number of macros defined, you may want to write
 ;;      an AUCTeX style file to support them with both AUCTeX and RefTeX.
-;;
+;; 
 ;;  10. Where Next?
 ;;      Go ahead and use RefTeX.  Use its menus until you have picked up
 ;;      the key bindings.  For an overview of what you can do in each of
@@ -236,13 +236,13 @@
 ;;      The first part of the manual explains in a tutorial way how to use
 ;;      and customize RefTeX.  The second part is a command and variable
 ;;      reference.
-;;
+;; 
 ;;---------------------------------------------------------------------------
 ;;
 ;; AUTHOR
 ;; ======
 ;;
-;; Carsten Dominik <dominik@strw.LeidenUniv.nl>
+;; Carsten Dominik <dominik@science.uva.nl>
 ;;
 ;;         with contributions from Stephen Eglen
 ;;
@@ -250,7 +250,7 @@
 ;; XEmacs 21.x.  If you need to install it yourself, you can find a
 ;; distribution at
 ;;
-;;    http://www.strw.leidenuniv.nl/~dominik/Tools/
+;;    http://zon.astro.uva.nl/~dominik/Tools/
 ;;
 ;; THANKS TO:
 ;; ---------
@@ -282,6 +282,12 @@
 (defvar reftex-tables-dirty t
   "Flag showing if tables need to be re-computed.")
 
+(eval-and-compile
+  (defun reftex-set-dirty (symbol value)
+    (setq reftex-tables-dirty t)
+    (set symbol value)))
+
+
 ;;; =========================================================================
 ;;;
 ;;; Configuration variables
@@ -294,7 +300,7 @@
 ;;; Define the formal stuff for a minor mode named RefTeX.
 ;;;
 
-(defconst reftex-version "RefTeX version 4.18"
+(defconst reftex-version "RefTeX version 4.21"
   "Version string for RefTeX.")
 
 (defvar reftex-mode nil
@@ -312,10 +318,10 @@
   (setq reftex-syntax-table (copy-syntax-table))
   (modify-syntax-entry ?\( "." reftex-syntax-table)
   (modify-syntax-entry ?\) "." reftex-syntax-table))
-
+        
 (unless reftex-syntax-table-for-bib
   (setq reftex-syntax-table-for-bib
-	(copy-syntax-table reftex-syntax-table))
+        (copy-syntax-table reftex-syntax-table))
   (modify-syntax-entry ?\' "." reftex-syntax-table-for-bib)
   (modify-syntax-entry ?\" "." reftex-syntax-table-for-bib)
   (modify-syntax-entry ?\[ "." reftex-syntax-table-for-bib)
@@ -371,30 +377,30 @@
 
   (if reftex-mode
       (progn
-	;; Mode was turned on
+        ;; Mode was turned on
         (easy-menu-add reftex-mode-menu)
-	(and reftex-plug-into-AUCTeX
-	     (reftex-plug-into-AUCTeX))
-	(unless (get 'reftex-auto-view-crossref 'initialized)
-	  (and reftex-auto-view-crossref
-	       (reftex-toggle-auto-view-crossref))
-	  (put 'reftex-auto-view-crossref 'initialized t))
-	(unless (get 'reftex-auto-recenter-toc 'initialized)
-	  (and reftex-auto-recenter-toc
-	       (reftex-toggle-auto-toc-recenter))
-	  (put 'reftex-auto-recenter-toc 'initialized t))
+        (and reftex-plug-into-AUCTeX
+             (reftex-plug-into-AUCTeX))
+        (unless (get 'reftex-auto-view-crossref 'initialized)
+          (and reftex-auto-view-crossref
+               (reftex-toggle-auto-view-crossref))
+          (put 'reftex-auto-view-crossref 'initialized t))
+        (unless (get 'reftex-auto-recenter-toc 'initialized)
+          (and (eq reftex-auto-recenter-toc t)
+               (reftex-toggle-auto-toc-recenter))
+          (put 'reftex-auto-recenter-toc 'initialized t))
 
-	;; Prepare the special syntax tables.
-	(setq reftex-syntax-table (copy-syntax-table (syntax-table)))
-	(modify-syntax-entry ?\( "." reftex-syntax-table)
-	(modify-syntax-entry ?\) "." reftex-syntax-table)
-
-	(setq reftex-syntax-table-for-bib
-	      (copy-syntax-table reftex-syntax-table))
-	(modify-syntax-entry ?\' "." reftex-syntax-table-for-bib)
-	(modify-syntax-entry ?\" "." reftex-syntax-table-for-bib)
-	(modify-syntax-entry ?\[ "." reftex-syntax-table-for-bib)
-	(modify-syntax-entry ?\] "." reftex-syntax-table-for-bib)
+        ;; Prepare the special syntax tables.
+        (setq reftex-syntax-table (copy-syntax-table (syntax-table)))
+        (modify-syntax-entry ?\( "." reftex-syntax-table)
+        (modify-syntax-entry ?\) "." reftex-syntax-table)
+        
+        (setq reftex-syntax-table-for-bib
+              (copy-syntax-table reftex-syntax-table))
+        (modify-syntax-entry ?\' "." reftex-syntax-table-for-bib)
+        (modify-syntax-entry ?\" "." reftex-syntax-table-for-bib)
+        (modify-syntax-entry ?\[ "." reftex-syntax-table-for-bib)
+        (modify-syntax-entry ?\] "." reftex-syntax-table-for-bib)
 
         (run-hooks 'reftex-mode-hook))
     ;; Mode was turned off
@@ -419,13 +425,13 @@
   ;; This function should be installed in `kill-buffer-hook'.
   ;; We are careful to make sure nothing goes wring in this function.
   (when (and (boundp 'reftex-mode)  reftex-mode
-	     (boundp 'reftex-save-parse-info)  reftex-save-parse-info
-	     (boundp 'reftex-docstruct-symbol)  reftex-docstruct-symbol
-	     (symbol-value reftex-docstruct-symbol)
-	     (get reftex-docstruct-symbol 'modified))
+             (boundp 'reftex-save-parse-info)  reftex-save-parse-info
+             (boundp 'reftex-docstruct-symbol)  reftex-docstruct-symbol
+             (symbol-value reftex-docstruct-symbol)
+             (get reftex-docstruct-symbol 'modified))
     ;; Write the file.
     (condition-case nil
-	(reftex-access-parse-file 'write)
+        (reftex-access-parse-file 'write)
       (error nil))))
 
 (defun reftex-kill-emacs-hook ()
@@ -433,9 +439,9 @@
   ;; This function should be installed in `kill-emacs-hook'.
   (save-excursion
     (mapcar (lambda (buf)
-	      (set-buffer buf)
-	      (reftex-kill-buffer-hook))
-	    (buffer-list))))
+              (set-buffer buf)
+              (reftex-kill-buffer-hook))
+            (buffer-list))))
 
 ;;; =========================================================================
 ;;;
@@ -505,8 +511,8 @@
       (put (symbol-value symbol) :master-index index)
       ;; Initialize if new symbols.
       (when newflag
-	(set (symbol-value symbol) nil)
-	(put (symbol-value symbol) 'reftex-index-macros-style '(default))))
+        (set (symbol-value symbol) nil)
+        (put (symbol-value symbol) 'reftex-index-macros-style '(default))))
 
     ;; Return t if the symbols did already exist, nil when we've made them.
     (not newflag)))
@@ -529,10 +535,10 @@
       ((master
         (cond
          ((fboundp 'TeX-master-file) ; AUCTeX is loaded.  Use its mechanism.
-	  (condition-case nil
-	      (TeX-master-file t)
-	    (error (buffer-file-name))))
-	 ((fboundp 'tex-main-file) (tex-main-file)) ; Emacs LaTeX mode
+          (condition-case nil 
+              (TeX-master-file t)
+            (error (buffer-file-name))))
+         ((fboundp 'tex-main-file) (tex-main-file)) ; Emacs LaTeX mode
          ((boundp 'TeX-master)       ; The variable is defined - lets use it.
           (cond
            ((eq TeX-master t)
@@ -558,7 +564,7 @@
           (buffer-file-name)))))
     (cond
      ((null master)
-      (error "Need a filename for this buffer, please save it first"))
+      (error "Need a filename for this buffer,  please save it first"))
      ((or (file-exists-p (concat master ".tex"))
           (reftex-get-buffer-visiting (concat master ".tex")))
       ;; Ahh, an extra .tex was missing...
@@ -569,7 +575,7 @@
       )
      (t
       ;; Use buffer file name.
-      (setq master (buffer-file-name))))
+      (buffer-file-name)))
     (expand-file-name master)))
 
 (defun reftex-is-multi ()
@@ -587,15 +593,15 @@
   (unless reftex-docstruct-symbol
     (reftex-tie-multifile-symbols))
   (when (and reftex-docstruct-symbol
-	     (symbolp reftex-docstruct-symbol))
+             (symbolp reftex-docstruct-symbol))
     (put reftex-docstruct-symbol 'reftex-cite-format value)))
 
 (defun reftex-get-cite-format ()
   ;; Return the current citation format.  Either the document-local value in
   ;; reftex-cite-format-symbol, or the global value in reftex-cite-format.
   (if (and reftex-docstruct-symbol
-	   (symbolp reftex-docstruct-symbol)
-	   (get reftex-docstruct-symbol 'reftex-cite-format))
+           (symbolp reftex-docstruct-symbol)
+           (get reftex-docstruct-symbol 'reftex-cite-format))
       (get reftex-docstruct-symbol 'reftex-cite-format)
     reftex-cite-format))
 
@@ -611,22 +617,22 @@
   (unless reftex-docstruct-symbol
     (reftex-tie-multifile-symbols))
   (when (and reftex-docstruct-symbol
-	     (symbolp reftex-docstruct-symbol))
+             (symbolp reftex-docstruct-symbol))
     (let ((list (get reftex-docstruct-symbol 'reftex-index-macros-style))
-	  entry changed)
+          entry changed)
       (while entry-list
-	(setq entry (pop entry-list))
-	;; When it is a symbol, remove all other symbols
-	(and (symbolp entry)
-	     (not (memq entry list))
-	     (setq list (reftex-remove-symbols-from-list list)))
-	;; Add to list unless already member
-	(unless (member entry list)
-	  (setq reftex-tables-dirty t
-		changed t)
-	  (push entry list)))
+        (setq entry (pop entry-list))
+        ;; When it is a symbol, remove all other symbols
+        (and (symbolp entry)
+             (not (memq entry list))
+             (setq list (reftex-remove-symbols-from-list list)))
+        ;; Add to list unless already member
+        (unless (member entry list)
+          (setq reftex-tables-dirty t
+                changed t)
+          (push entry list)))
       (when changed
-	(put reftex-docstruct-symbol 'reftex-index-macros-style list)))))
+        (put reftex-docstruct-symbol 'reftex-index-macros-style list)))))
 
 ;;; =========================================================================
 ;;;
@@ -728,14 +734,14 @@
 
 ;; A list of all variables in the cache.
 ;; The cache is used to save the compiled versions of some variables.
-(defconst reftex-cache-variables
+(defconst reftex-cache-variables 
   '(reftex-memory ;; This MUST ALWAYS be the first!
-
+    
     ;; Outline
     reftex-section-levels-all
 
     ;; Labels
-    reftex-env-or-mac-alist
+    reftex-env-or-mac-alist 
     reftex-special-env-parsers
     reftex-macros-with-labels
     reftex-label-mac-list
@@ -751,7 +757,7 @@
     reftex-index-macro-alist
     reftex-macros-with-index
     reftex-query-index-macro-prompt
-    reftex-query-index-macro-help
+    reftex-query-index-macro-help 
     reftex-key-to-index-macro-alist
 
     ;; Regular expressions
@@ -768,35 +774,35 @@
 (defun reftex-ensure-compiled-variables ()
   ;; Recompile the label alist when necessary
   (let* ((mem reftex-memory)
-	 (cache (get reftex-docstruct-symbol 'reftex-cache))
-	 (cmem  (car cache))
-	 (alist reftex-label-alist)
-	 (levels (get reftex-docstruct-symbol 'reftex-section-levels))
-	 (style (get reftex-docstruct-symbol 'reftex-label-alist-style))
-	 (default reftex-default-label-alist-entries)
-	 (index reftex-index-macros)
-	 (istyle (get reftex-docstruct-symbol 'reftex-index-macros-style)))
+         (cache (get reftex-docstruct-symbol 'reftex-cache))
+         (cmem  (car cache))
+         (alist reftex-label-alist)
+         (levels (get reftex-docstruct-symbol 'reftex-section-levels))
+         (style (get reftex-docstruct-symbol 'reftex-label-alist-style))
+         (default reftex-default-label-alist-entries)
+         (index reftex-index-macros)
+         (istyle (get reftex-docstruct-symbol 'reftex-index-macros-style)))
     (cond
      (reftex-tables-dirty (reftex-compile-variables))
      ((and (eq alist   (nth 0 mem))
-	   (eq levels  (nth 1 mem))
-	   (eq style   (nth 2 mem))
-	   (eq default (nth 3 mem))
-	   (eq index   (nth 4 mem))
-	   (eq istyle  (nth 5 mem))))  ;; everything is OK
+           (eq levels  (nth 1 mem))
+           (eq style   (nth 2 mem))
+           (eq default (nth 3 mem))
+           (eq index   (nth 4 mem))
+           (eq istyle  (nth 5 mem))))  ;; everything is OK
      ((and (eq alist   (nth 0 cmem))
-	   (eq levels  (nth 1 cmem))
-	   (eq style   (nth 2 cmem))
-	   (eq default (nth 2 cmem))
-	   (eq index   (nth 4 cmem))
-	   (eq istyle  (nth 5 cmem)))
+           (eq levels  (nth 1 cmem))
+           (eq style   (nth 2 cmem))
+           (eq default (nth 2 cmem))
+           (eq index   (nth 4 cmem))
+           (eq istyle  (nth 5 cmem)))
       ;; restore the cache
       (message "Restoring cache")
       (mapcar (lambda (sym) (set sym (pop cache))) reftex-cache-variables))
      (t (reftex-compile-variables)))))
 
 (defun reftex-reset-mode ()
-  "Reset RefTeX Mode.
+  "Reset RefTeX Mode.  
 This will re-compile the configuration information and remove all
 current scanning information and the parse file to enforce a rescan
 on next use."
@@ -804,18 +810,18 @@
 
   ;; Reset the file search path variables
   (loop for prop in '(status master-dir recursive-path rec-type) do
-	(put 'reftex-tex-path prop nil)
-	(put 'reftex-bib-path prop nil))
+        (put 'reftex-tex-path prop nil)
+        (put 'reftex-bib-path prop nil))
 
   ;; Kill temporary buffers associated with RefTeX - just in case they
   ;; were not cleaned up properly
   (save-excursion
     (let ((buffer-list '("*RefTeX Help*" "*RefTeX Select*"
-			 "*Duplicate Labels*" "*toc*" " *RefTeX-scratch*"))
-	  buf)
+                         "*Duplicate Labels*" "*toc*" " *RefTeX-scratch*"))
+          buf)
       (while (setq buf (pop buffer-list))
-	(if (get-buffer buf)
-	    (kill-buffer buf))))
+        (if (get-buffer buf)
+            (kill-buffer buf))))
     (reftex-erase-all-selection-and-index-buffers))
 
   ;; Make sure the current document will be rescanned soon.
@@ -830,6 +836,7 @@
 
   (reftex-compile-variables))
 
+;;;###autoload
 (defun reftex-reset-scanning-information ()
   "Reset the symbols containing information from buffer scanning.
 This enforces rescanning the buffer on next use."
@@ -846,12 +853,12 @@
 
 (defun reftex-erase-all-selection-and-index-buffers ()
   ;; Remove all selection buffers associated with current document.
-  (mapcar
+  (mapcar 
    (lambda (type)
      (reftex-erase-buffer (reftex-make-selection-buffer-name type)))
    reftex-typekey-list)
   ;; Kill all index buffers
-  (mapcar
+  (mapcar 
    (lambda (tag)
      (reftex-kill-buffer (reftex-make-index-buffer-name tag)))
    (cdr (assoc 'index-tags (symbol-value reftex-docstruct-symbol)))))
@@ -867,34 +874,34 @@
 
   ;; Record that we have done this, and what we have used.
   (setq reftex-tables-dirty nil)
-  (setq reftex-memory
-	(list reftex-label-alist
-	      (get reftex-docstruct-symbol 'reftex-section-levels)
-	      (get reftex-docstruct-symbol 'reftex-label-alist-style)
-	      reftex-default-label-alist-entries
-	      reftex-index-macros
-	      (get reftex-docstruct-symbol 'reftex-index-macros-style)))
+  (setq reftex-memory 
+        (list reftex-label-alist
+              (get reftex-docstruct-symbol 'reftex-section-levels)
+              (get reftex-docstruct-symbol 'reftex-label-alist-style)
+              reftex-default-label-alist-entries
+              reftex-index-macros
+              (get reftex-docstruct-symbol 'reftex-index-macros-style)))
 
   ;; Compile information in reftex-label-alist
   (let ((all (reftex-uniquify-by-car
-	      (reftex-splice-symbols-into-list
-	       (append reftex-label-alist
-		       (get reftex-docstruct-symbol
-			    'reftex-label-alist-style)
-		       reftex-default-label-alist-entries)
-	       reftex-label-alist-builtin)
-	      '(nil)))
-	(all-index (reftex-uniquify-by-car
-		    (reftex-splice-symbols-into-list
-		     (append reftex-index-macros
-			     (get reftex-docstruct-symbol
-				  'reftex-index-macros-style)
-			     '(default))
-		     reftex-index-macros-builtin)))
+              (reftex-splice-symbols-into-list
+               (append reftex-label-alist
+                       (get reftex-docstruct-symbol
+                            'reftex-label-alist-style)
+                       reftex-default-label-alist-entries)
+               reftex-label-alist-builtin)
+              '(nil)))
+        (all-index (reftex-uniquify-by-car
+                    (reftex-splice-symbols-into-list
+                     (append reftex-index-macros 
+                             (get reftex-docstruct-symbol
+                                  'reftex-index-macros-style)
+                             '(default))
+                     reftex-index-macros-builtin)))
         entry env-or-mac typekeychar typekey prefix context word
         fmt reffmt labelfmt wordlist qh-list macros-with-labels
         nargs nlabel opt-args cell sum i
-	macro verify repeat nindex tag key toc-level toc-levels)
+        macro verify repeat nindex tag key toc-level toc-levels)
 
     (setq reftex-words-to-typekey-alist nil
           reftex-typekey-list nil
@@ -923,7 +930,7 @@
               fmt (nth 2 entry)
               context (nth 3 entry)
               wordlist (nth 4 entry)
-	      toc-level (nth 5 entry))
+              toc-level (nth 5 entry))
         (if (stringp wordlist)
             ;; This is before version 2.04 - convert to new format
             (setq wordlist (nthcdr 4 entry)))
@@ -935,66 +942,66 @@
           (setq fmt (list "\\label{%s}" fmt)))
         (setq labelfmt (car fmt)
               reffmt (nth 1 fmt))
-	;; Note a new typekey
+        ;; Note a new typekey
         (if typekey
             (add-to-list 'reftex-typekey-list typekey))
         (if (and typekey prefix
                  (not (assoc typekey reftex-typekey-to-prefix-alist)))
             (add-to-list 'reftex-typekey-to-prefix-alist
                          (cons typekey prefix)))
-	;; Check if this is a macro or environment
+        ;; Check if this is a macro or environment
         (cond
-	 ((symbolp env-or-mac)
-	  ;; A special parser function
-	  (unless (fboundp env-or-mac)
-	    (message "Warning: %s does not seem to be a valid function"
-		     env-or-mac))
+         ((symbolp env-or-mac)
+          ;; A special parser function
+          (unless (fboundp env-or-mac)
+            (message "Warning: %s does not seem to be a valid function" 
+                     env-or-mac))
           (setq nargs nil nlabel nil opt-args nil)
-	  (add-to-list 'reftex-special-env-parsers env-or-mac)
-	  (setq env-or-mac (symbol-name env-or-mac)))
+          (add-to-list 'reftex-special-env-parsers env-or-mac)
+          (setq env-or-mac (symbol-name env-or-mac)))
          ((string-match "\\`\\\\" env-or-mac)
           ;; It's a macro
           (let ((result (reftex-parse-args env-or-mac)))
             (setq env-or-mac (or (first result) env-or-mac)
-		  nargs (second result)
+                  nargs (second result)
                   nlabel (third result)
                   opt-args (fourth result))
             (if nlabel (add-to-list 'macros-with-labels env-or-mac)))
-	  (if typekey (add-to-list 'reftex-label-mac-list env-or-mac)))
+          (if typekey (add-to-list 'reftex-label-mac-list env-or-mac)))
          (t
-	  ;; It's an environment
+          ;; It's an environment
           (setq nargs nil nlabel nil opt-args nil)
           (cond ((string= env-or-mac "any"))
                 ((string= env-or-mac ""))
                 ((string= env-or-mac "section"))
                 (t
                  (add-to-list 'reftex-label-env-list env-or-mac)
-		 (if toc-level
-		     (let ((string (format "begin{%s}" env-or-mac)))
-		       (or (assoc string toc-levels)
-			   (push (cons string toc-level) toc-levels))))))))
-	;; Translate some special context cases
-	(when (assq context reftex-default-context-regexps)
-	  (setq context
-		(format
-		 (cdr (assq context reftex-default-context-regexps))
-		 (regexp-quote env-or-mac))))
-	;; See if this is the first format for this typekey
+                 (if toc-level
+                     (let ((string (format "begin{%s}" env-or-mac)))
+                       (or (assoc string toc-levels)
+                           (push (cons string toc-level) toc-levels))))))))
+        ;; Translate some special context cases
+        (when (assq context reftex-default-context-regexps)
+          (setq context 
+                (format 
+                 (cdr (assq context reftex-default-context-regexps))
+                 (regexp-quote env-or-mac))))
+        ;; See if this is the first format for this typekey
         (and reffmt
              (not (assoc typekey reftex-typekey-to-format-alist))
              (push (cons typekey reffmt) reftex-typekey-to-format-alist))
-	;; See if this is the first definition for this env-or-mac
+        ;; See if this is the first definition for this env-or-mac
         (and (not (string= env-or-mac "any"))
              (not (string= env-or-mac ""))
              (not (assoc env-or-mac reftex-env-or-mac-alist))
              (push (list env-or-mac typekey context labelfmt
-			 nargs nlabel opt-args)
+                         nargs nlabel opt-args)
                    reftex-env-or-mac-alist))
-	;; Are the magic words regular expressions?  Quote normal words.
-	(if (eq (car wordlist) 'regexp)
-	    (setq wordlist (cdr wordlist))
-	  (setq wordlist (mapcar 'regexp-quote wordlist)))
-	;; Remember the first association of each word.
+        ;; Are the magic words regular expressions?  Quote normal words.
+        (if (eq (car wordlist) 'regexp)
+            (setq wordlist (cdr wordlist))
+          (setq wordlist (mapcar 'regexp-quote wordlist)))
+        ;; Remember the first association of each word.
         (while (stringp (setq word (pop wordlist)))
           (or (assoc word reftex-words-to-typekey-alist)
               (push (cons word typekey) reftex-words-to-typekey-alist)))
@@ -1009,10 +1016,10 @@
           (nreverse reftex-typekey-to-prefix-alist))
 
     ;; Prepare the typekey query prompt and help string.
-    (setq qh-list
-	  (sort qh-list
-		(lambda (x1 x2)
-		  (string< (downcase (car x1)) (downcase (car x2))))))
+    (setq qh-list 
+          (sort qh-list
+                (lambda (x1 x2)
+                  (string< (downcase (car x1)) (downcase (car x2))))))
     (setq reftex-type-query-prompt
           (concat "Label type: ["
                   (mapconcat (lambda(x) (format "%s" (car x)))
@@ -1020,164 +1027,164 @@
                   "]"))
     ;; In the help string, we need to wrap lines...
     (setq reftex-type-query-help
-          (concat
-	   "SELECT A LABEL TYPE:\n--------------------\n"
-	   (mapconcat
-	    (lambda(x)
-	      (setq sum 0)
-	      (format " [%s]   %s"
-		      (car x)
-		      (mapconcat (lambda(env)
-				   (setq sum (+ sum (length env)))
-				   (if (< sum 60)
-				       env
-				     (setq sum 0)
-				     (concat "\n       " env)))
-				 (cdr x) " ")))
-	    qh-list "\n")))
+          (concat 
+           "SELECT A LABEL TYPE:\n--------------------\n"
+           (mapconcat
+            (lambda(x)
+              (setq sum 0)
+              (format " [%s]   %s"
+                      (car x)
+                      (mapconcat (lambda(env)
+                                   (setq sum (+ sum (length env)))
+                                   (if (< sum 60)
+                                       env
+                                     (setq sum 0)
+                                     (concat "\n       " env)))
+                                 (cdr x) " ")))
+            qh-list "\n")))
 
     ;; Convert magic words to regular expressions.  We make regular expressions
     ;; which allow for some chars from the ref format to be in the buffer.
     ;; These characters will be seen and removed.
     (setq reftex-words-to-typekey-alist
-	  (mapcar
-	   (lambda (x)
-	     (setq word (car x)
-		   typekey (cdr x)
-		   fmt (cdr (assoc typekey reftex-typekey-to-format-alist)))
-	     (setq word (concat "\\W\\(" word "[ \t\n\r]*\\)\\("))
-	     (setq i 0)
-	     (while (and (< i 10)   ; maximum number of format chars allowed
- 			 (< i (length fmt))
-			 (not (member (aref fmt i) '(?%))))
-	       (setq word (concat word "\\|" (regexp-quote
-					      (substring fmt 0 (1+ i)))))
-	       (incf i))
-	     (cons (concat word "\\)\\=") typekey))
-	   (nreverse reftex-words-to-typekey-alist)))
+          (mapcar 
+           (lambda (x)
+             (setq word (car x)
+                   typekey (cdr x)
+                   fmt (cdr (assoc typekey reftex-typekey-to-format-alist)))
+             (setq word (concat "\\W\\(" word "[ \t\n\r]*\\)\\("))
+             (setq i 0)
+             (while (and (< i 10)   ; maximum number of format chars allowed
+                         (< i (length fmt))
+                         (not (member (aref fmt i) '(?%))))
+               (setq word (concat word "\\|" (regexp-quote
+                                              (substring fmt 0 (1+ i)))))
+               (incf i))
+             (cons (concat word "\\)\\=") typekey))
+           (nreverse reftex-words-to-typekey-alist)))
 
     ;; Parse the index macros
     (setq reftex-index-macro-alist nil
-	  reftex-key-to-index-macro-alist nil
-	  reftex-macros-with-index nil)
+          reftex-key-to-index-macro-alist nil
+          reftex-macros-with-index nil)
     (while all-index
       (setq entry (car all-index)
-	    macro (car entry)
-	    tag (nth 1 entry)
-	    key (nth 2 entry)
-	    prefix (or (nth 3 entry) "")
-	    verify (nth 4 entry)
-	    ;; For repeat, we need to be compatible with older code
-	    ;; This information used to be given only for the default macro,
-	    ;; but later we required to have it for *every* index macro
-	    repeat (cond ((> (length entry) 5) (nth 5 entry))
-			 ((and (eq key (car reftex-index-default-macro))
-			       (> (length reftex-index-default-macro) 2))
-			  ;; User has old setting - respect it
-			  (nth 2 reftex-index-default-macro))
-			 (t t))
-	    all-index (cdr all-index))
+            macro (car entry)
+            tag (nth 1 entry)
+            key (nth 2 entry)
+            prefix (or (nth 3 entry) "")
+            verify (nth 4 entry)
+            ;; For repeat, we need to be compatible with older code
+            ;; This information used to be given only for the default macro,
+            ;; but later we required to have it for *every* index macro
+            repeat (cond ((> (length entry) 5) (nth 5 entry))
+                         ((and (eq key (car reftex-index-default-macro))
+                               (> (length reftex-index-default-macro) 2))
+                          ;; User has old setting - respect it
+                          (nth 2 reftex-index-default-macro))
+                         (t t))
+            all-index (cdr all-index))
       (let ((result (reftex-parse-args macro)))
-	(setq macro (or (first result) macro)
-	      nargs (second result)
-	      nindex (third result)
-	      opt-args (fourth result))
-	(unless (member macro reftex-macros-with-index)
-	  ;;           0     1    2      3     4     5       6        7
-	  (push (list macro tag prefix verify nargs nindex opt-args repeat)
-		reftex-index-macro-alist)
-	  (or (assoc key reftex-key-to-index-macro-alist)
-	      (push (list key macro) reftex-key-to-index-macro-alist))
-	  (push macro reftex-macros-with-index))))
+        (setq macro (or (first result) macro)
+              nargs (second result)
+              nindex (third result)
+              opt-args (fourth result))
+        (unless (member macro reftex-macros-with-index)
+          ;;           0     1    2      3     4     5       6        7
+          (push (list macro tag prefix verify nargs nindex opt-args repeat)
+                reftex-index-macro-alist)
+          (or (assoc key reftex-key-to-index-macro-alist)
+              (push (list key macro) reftex-key-to-index-macro-alist))
+          (push macro reftex-macros-with-index))))
     ;; Make the prompt and help string for index macros query
     (setq reftex-key-to-index-macro-alist
-	  (sort reftex-key-to-index-macro-alist
-		(lambda (a b) (< (downcase (car a)) (downcase (car b))))))
-    (setq reftex-query-index-macro-prompt
-	  (concat "Index macro: ["
-		  (mapconcat (lambda (x) (char-to-string (car x)))
-			     reftex-key-to-index-macro-alist "")
-		  "]"))
+          (sort reftex-key-to-index-macro-alist
+                (lambda (a b) (< (downcase (car a)) (downcase (car b))))))
+    (setq reftex-query-index-macro-prompt 
+          (concat "Index macro: ["
+                  (mapconcat (lambda (x) (char-to-string (car x)))
+                             reftex-key-to-index-macro-alist "")
+                  "]"))
     (setq i 0
-	  reftex-query-index-macro-help
-	  (concat
-	   "SELECT A MACRO:\n---------------\n"
-	   (mapconcat
-	    (lambda(x)
-	      (format "[%c] %-20.20s%s" (car x) (nth 1 x)
-		      (if (= 0 (mod (incf i) 3)) "\n" "")))
-	    reftex-key-to-index-macro-alist "")))
+          reftex-query-index-macro-help
+          (concat 
+           "SELECT A MACRO:\n---------------\n"
+           (mapconcat
+            (lambda(x)
+              (format "[%c] %-20.20s%s" (car x) (nth 1 x) 
+                      (if (= 0 (mod (incf i) 3)) "\n" "")))
+            reftex-key-to-index-macro-alist "")))
 
     ;; Make the full list of section levels
     (setq reftex-section-levels-all
-	  (append toc-levels
-		  (get reftex-docstruct-symbol 'reftex-section-levels)
-		  reftex-section-levels))
+          (append toc-levels
+                  (get reftex-docstruct-symbol 'reftex-section-levels)
+                  reftex-section-levels))
 
     ;; Calculate the regular expressions
     (let* (
-;	   (wbol "\\(\\`\\|[\n\r]\\)[ \t]*")
-	   (wbol "\\(^\\)[ \t]*")  ; Need to keep the empty group because
-	                          ;;; because match number are hard coded
-	   (label-re "\\\\label{\\([^}]*\\)}")
-	   (include-re (concat wbol
-			       "\\\\\\("
-			       (mapconcat 'identity
-					  reftex-include-file-commands "\\|")
-			       "\\)[{ \t]+\\([^} \t\n\r]+\\)"))
-	   (section-re
-	    (concat wbol "\\\\\\("
-		    (mapconcat (lambda (x) (regexp-quote (car x)))
-			       reftex-section-levels-all "\\|")
-		    "\\)\\*?\\(\\[[^]]*\\]\\)?[[{ \t\r\n]"))
-	   (appendix-re (concat wbol "\\(\\\\appendix\\)"))
-	   (macro-re
-	    (if macros-with-labels
-		(concat "\\("
-			(mapconcat 'regexp-quote macros-with-labels "\\|")
-			"\\)[[{]")
-	      ""))
-	   (index-re
-	    (concat "\\("
-		    (mapconcat 'regexp-quote reftex-macros-with-index "\\|")
-		    "\\)[[{]"))
-	   (find-index-re-format
-	    (concat "\\("
-		    (mapconcat 'regexp-quote reftex-macros-with-index "\\|")
-		    "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]"))
-	   (find-label-re-format
-	    (concat "\\("
-		    (mapconcat 'regexp-quote (append '("\\label")
-						     macros-with-labels) "\\|")
-		    "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]"))
-	   (index-level-re
-	    (regexp-quote (nth 0 reftex-index-special-chars)))
-	   (index-key-end-re ;; ^]- not allowed
-	    (concat "[^" (nth 3 reftex-index-special-chars) "]"
-		    "[" (nth 1 reftex-index-special-chars)
-		    (nth 2 reftex-index-special-chars) "]"))
-	   )
+;          (wbol "\\(\\`\\|[\n\r]\\)[ \t]*")
+           (wbol "\\(^\\)[ \t]*")  ; Need to keep the empty group because
+                                  ;;; because match number are hard coded  
+           (label-re "\\\\label{\\([^}]*\\)}")
+           (include-re (concat wbol 
+                               "\\\\\\("
+                               (mapconcat 'identity 
+                                          reftex-include-file-commands "\\|")
+                               "\\)[{ \t]+\\([^} \t\n\r]+\\)"))
+           (section-re
+            (concat wbol "\\\\\\("
+                    (mapconcat (lambda (x) (regexp-quote (car x)))
+                               reftex-section-levels-all "\\|")
+                    "\\)\\*?\\(\\[[^]]*\\]\\)?[[{ \t\r\n]"))
+           (appendix-re (concat wbol "\\(\\\\appendix\\)"))
+           (macro-re
+            (if macros-with-labels
+                (concat "\\("
+                        (mapconcat 'regexp-quote macros-with-labels "\\|")
+                        "\\)[[{]")
+              ""))
+           (index-re
+            (concat "\\("
+                    (mapconcat 'regexp-quote reftex-macros-with-index "\\|")
+                    "\\)[[{]"))
+           (find-index-re-format
+            (concat "\\("
+                    (mapconcat 'regexp-quote reftex-macros-with-index "\\|")
+                    "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]"))
+           (find-label-re-format
+            (concat "\\("
+                    (mapconcat 'regexp-quote (append '("\\label")
+                                                     macros-with-labels) "\\|")
+                    "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]"))
+           (index-level-re
+            (regexp-quote (nth 0 reftex-index-special-chars)))
+           (index-key-end-re ;; ^]- not allowed
+            (concat "[^" (nth 3 reftex-index-special-chars) "]"
+                    "[" (nth 1 reftex-index-special-chars)
+                    (nth 2 reftex-index-special-chars) "]"))
+           )
       (setq reftex-section-regexp section-re
             reftex-section-or-include-regexp
             (concat section-re "\\|" include-re)
             reftex-everything-regexp
             (concat label-re "\\|" section-re "\\|" include-re
-		    "\\|" appendix-re
-		    "\\|" index-re
+                    "\\|" appendix-re
+                    "\\|" index-re
                     (if macros-with-labels "\\|" "") macro-re)
             reftex-everything-regexp-no-index
             (concat label-re "\\|" section-re "\\|" include-re
-		    "\\|" appendix-re
-		    "\\|" "\\(\\\\6\\\\3\\\\1\\)" ; This is unlikely to match
+                    "\\|" appendix-re
+                    "\\|" "\\(\\\\6\\\\3\\\\1\\)" ; This is unlikely to match
                     (if macros-with-labels "\\|" "") macro-re)
-	    reftex-index-re index-re
-	    reftex-index-level-re index-level-re
-	    reftex-index-key-end-re index-key-end-re
-	    reftex-macros-with-labels macros-with-labels
-	    reftex-find-index-entry-regexp-format find-index-re-format
+            reftex-index-re index-re
+            reftex-index-level-re index-level-re
+            reftex-index-key-end-re index-key-end-re
+            reftex-macros-with-labels macros-with-labels
+            reftex-find-index-entry-regexp-format find-index-re-format
             reftex-find-label-regexp-format find-label-re-format
-	    reftex-find-label-regexp-format2
-	    "\\([]} \t\n\r]\\)\\([[{]\\)\\(%s\\)[]}]")
+            reftex-find-label-regexp-format2 
+            "\\([]} \t\n\r]\\)\\([[{]\\)\\(%s\\)[]}]")
       (message "Compiling label environment definitions...done")))
   (put reftex-docstruct-symbol 'reftex-cache
        (mapcar 'symbol-value reftex-cache-variables)))
@@ -1195,8 +1202,8 @@
             (when (eq ?\[ (string-to-char args))
               (push cnt opt-list))
             (when (and (match-end 1)
-		       (not nlabel))
-	      (setq nlabel cnt))
+                       (not nlabel))
+              (setq nlabel cnt))
             (setq args (substring args (match-end 0))))
           (list must-match cnt nlabel opt-list)))
     nil))
@@ -1220,14 +1227,14 @@
   (reftex-ensure-compiled-variables)
 
   (when (or (null (symbol-value reftex-docstruct-symbol))
-	    (member rescan '(t 1 (4) (16))))
+            (member rescan '(t 1 (4) (16))))
     ;; The docstruct will change: Remove selection buffers.
     (save-excursion
       (reftex-erase-buffer "*toc*")
       (reftex-erase-all-selection-and-index-buffers)))
 
   (if (and (null (symbol-value reftex-docstruct-symbol))
-	   (not (member rescan '(t 1 (4) (16))))
+           (not (member rescan '(t 1 (4) (16))))
            reftex-save-parse-info)
       ;; Try to read the stuff from a file
       (reftex-access-parse-file 'read))
@@ -1241,7 +1248,6 @@
     ;; Scan whatever was required by the caller.
     (reftex-do-parse rescan file))))
 
-;;;###autoload
 (defun reftex-scanning-info-available-p ()
   "Is the scanning info about the current document available?"
   (unless reftex-docstruct-symbol
@@ -1249,7 +1255,7 @@
   (and (symbolp reftex-docstruct-symbol)
        (symbol-value reftex-docstruct-symbol)
        t))
-
+  
 (defun reftex-silence-toc-markers (list n)
   ;; Set all toc markers in the first N entries in list to nil
   (while (and list (> (decf n) -1))
@@ -1262,12 +1268,12 @@
   "Perform ACTION on the parse file (the .rel file).
 Valid actions are: readable, restore, read, kill, write."
   (let* ((list (symbol-value reftex-docstruct-symbol))
-	 (docstruct-symbol reftex-docstruct-symbol)
+         (docstruct-symbol reftex-docstruct-symbol)
          (master (reftex-TeX-master-file))
-	 (enable-local-variables nil)
+         (enable-local-variables nil)
          (file (if (string-match "\\.[a-zA-Z]+\\'" master)
-                   (concat (substring master 0 (match-beginning 0))
-			   reftex-parse-file-extension)
+                   (concat (substring master 0 (match-beginning 0)) 
+                           reftex-parse-file-extension)
                  (concat master reftex-parse-file-extension))))
     (cond
      ((eq action 'readable)
@@ -1279,31 +1285,31 @@
           (reftex-tie-multifile-symbols))
       (if (file-exists-p file)
           ;; load the file and return t for success
-	  (condition-case nil
-	      (progn (load-file file) t)
-	    (error (set reftex-docstruct-symbol nil)
-		   (error "Error while loading file %s" file)))
+          (condition-case nil
+              (progn (load-file file) t)
+            (error (set reftex-docstruct-symbol nil)
+                   (error "Error while loading file %s" file)))
         ;; Throw an exception if the file does not exist
         (error "No restore file %s" file)))
      ((eq action 'read)
       (put reftex-docstruct-symbol 'modified nil)
       (if (file-exists-p file)
           ;; load the file and return t for success
-	  (condition-case nil
-	      (progn
-		(load-file file)
-		(reftex-check-parse-consistency)
-		t)
-	    (error (message "Error while restoring file %s" file)
-		   (set reftex-docstruct-symbol nil)
-		   nil))
+          (condition-case nil
+              (progn
+                (load-file file)
+                (reftex-check-parse-consistency)
+                t)
+            (error (message "Error while restoring file %s" file)
+                   (set reftex-docstruct-symbol nil)
+                   nil))
         ;; return nil for failure, but no exception
         nil))
      ((eq action 'kill)
       ;; Remove the file
       (when (and (file-exists-p file) (file-writable-p file))
-	(message "Unlinking file %s" file)
-	(delete-file file)))
+        (message "Unlinking file %s" file)
+        (delete-file file)))
      (t
       (put docstruct-symbol 'modified nil)
       (save-excursion
@@ -1319,20 +1325,20 @@
               (insert "(set reftex-docstruct-symbol '(\n\n")
               (let ((standard-output (current-buffer)))
                 (mapcar
-		 (lambda (x)
-		   (cond ((eq (car x) 'toc)
-			  ;; A toc entry. Do not save the marker.
-			  ;; Save the markers  position at position 8
-			  (print (list 'toc "toc" (nth 2 x) (nth 3 x)
-				       nil (nth 5 x) (nth 6 x) (nth 7 x)
-				       (or (and (markerp (nth 4 x))
-						(marker-position (nth 4 x)))
-					   (nth 8 x)))))
-			 ((and (not (eq t reftex-support-index))
-			       (eq (car x) 'index))
-			  ;; Don't save index entries
-			  )
-			 (t (print x))))
+                 (lambda (x)
+                   (cond ((eq (car x) 'toc)
+                          ;; A toc entry. Do not save the marker.
+                          ;; Save the markers  position at position 8
+                          (print (list 'toc "toc" (nth 2 x) (nth 3 x)
+                                       nil (nth 5 x) (nth 6 x) (nth 7 x)
+                                       (or (and (markerp (nth 4 x))
+                                                (marker-position (nth 4 x)))
+                                           (nth 8 x)))))
+                         ((and (not (eq t reftex-support-index))
+                               (eq (car x) 'index))
+                          ;; Don't save index entries
+                          )
+                         (t (print x))))
                  list))
               (insert "))\n\n")
               (save-buffer 0)
@@ -1345,29 +1351,29 @@
 
   ;; Check if the master is the same: when moving a document, this will see it.
   (let* ((real-master (reftex-TeX-master-file))
-	 (parsed-master
-	  (nth 1 (assq 'bof (symbol-value reftex-docstruct-symbol)))))
+         (parsed-master 
+          (nth 1 (assq 'bof (symbol-value reftex-docstruct-symbol)))))
     (unless (string= (file-truename real-master) (file-truename parsed-master))
       (message "Master file name in load file is different: %s versus %s"
-	       parsed-master real-master)
+               parsed-master real-master)
       (error "Master file name error")))
 
   ;; Check for the existence of all document files
 ;;;  (let* ((all (symbol-value reftex-docstruct-symbol)))
 ;;;    (while all
 ;;;      (when (and (eq (car (car all)) 'bof)
-;;;		 (not (file-regular-p (nth 1 (car all)))))
-;;;	(message "File %s in saved parse info not avalable" (cdr (car all)))
-;;;	(error "File not found"))
+;;;              (not (file-regular-p (nth 1 (car all)))))
+;;;     (message "File %s in saved parse info not avalable" (cdr (car all)))
+;;;     (error "File not found"))
 ;;;      (setq all (cdr all))))
   )
 
 (defun reftex-select-external-document (xr-alist xr-index)
   ;; Return index of an external document.
   (let* ((len (length xr-alist)) (highest (1- (+ ?0 len)))
-	 (prompt (format "[%c-%c] Select    TAB: Read prefix with completion"
-			 ?0 highest))
-	 key prefix)
+         (prompt (format "[%c-%c] Select    TAB: Read prefix with completion" 
+                         ?0 highest))
+         key prefix)
     (cond
      ((= len 1)
       (message "No external documents available")
@@ -1376,27 +1382,27 @@
       (- 1 xr-index))
      (t
       (save-excursion
-	(let* ((length (apply 'max (mapcar
-				    (lambda(x) (length (car x))) xr-alist)))
-	       (fmt (format " [%%c]  %%-%ds  %%s\n" length))
-	       (n (1- ?0)))
-	  (setq key
-		(reftex-select-with-char
-		 prompt
-		 (concat
-		  "SELECT EXTERNAL DOCUMENT\n------------------------\n"
-		  (mapconcat
-		   (lambda (x)
-		     (format fmt (incf n) (or (car x) "")
-			     (abbreviate-file-name (cdr x))))
-		   xr-alist ""))
-		 nil t))
-	  (cond
-	   ((and (>= key ?0) (<= key highest)) (- key ?0))
-	   ((= key ?\C-i)
-	    (setq prefix (completing-read "Prefix: " xr-alist nil t))
-	    (- len (length (memq (assoc prefix xr-alist) xr-alist))))
-	   (t (error "Illegal document selection [%c]" key)))))))))
+        (let* ((length (apply 'max (mapcar 
+                                    (lambda(x) (length (car x))) xr-alist)))
+               (fmt (format " [%%c]  %%-%ds  %%s\n" length))
+               (n (1- ?0)))
+          (setq key
+                (reftex-select-with-char
+                 prompt
+                 (concat
+                  "SELECT EXTERNAL DOCUMENT\n------------------------\n"
+                  (mapconcat
+                   (lambda (x) 
+                     (format fmt (incf n) (or (car x) "")
+                             (abbreviate-file-name (cdr x))))
+                   xr-alist ""))
+                 nil t))
+          (cond
+           ((and (>= key ?0) (<= key highest)) (- key ?0))
+           ((= key ?\C-i)
+            (setq prefix (completing-read "Prefix: " xr-alist nil t))
+            (- len (length (memq (assoc prefix xr-alist) xr-alist))))
+           (t (error "Illegal document selection [%c]" key)))))))))
 
 ;;; =========================================================================
 ;;;
@@ -1408,65 +1414,65 @@
 try first the default extension and only then the naked file name.
 When DIE is non-nil, throw an error if file not found."
   (let* ((rec-values (if reftex-search-unrecursed-path-first '(nil t) '(t)))
-	 (extensions (cdr (assoc type reftex-file-extensions)))
-	 (def-ext (car extensions))
-	 (ext-re (concat "\\("
-			 (mapconcat 'regexp-quote extensions "\\|")
-			 "\\)\\'"))
-	 (files (if (string-match ext-re file)
-		    (cons file nil)
-		  (cons (concat file def-ext) file)))
-	 path old-path file1)
+         (extensions (cdr (assoc type reftex-file-extensions)))
+         (def-ext (car extensions))
+         (ext-re (concat "\\(" 
+                         (mapconcat 'regexp-quote extensions "\\|")
+                         "\\)\\'"))
+         (files (if (string-match ext-re file)
+                    (cons file nil)
+                  (cons (concat file def-ext) file)))
+         path old-path file1)
     (cond
      ((file-name-absolute-p file)
-      (setq file1
-	    (or
-	     (and (car files) (file-regular-p (car files)) (car files))
-	     (and (cdr files) (file-regular-p (cdr files)) (cdr files)))))
+      (setq file1 
+            (or 
+             (and (car files) (file-regular-p (car files)) (car files))
+             (and (cdr files) (file-regular-p (cdr files)) (cdr files)))))
      ((and reftex-use-external-file-finders
-	   (assoc type reftex-external-file-finders))
+           (assoc type reftex-external-file-finders))
       (setq file1 (reftex-find-file-externally file type master-dir)))
      (t
       (while (and (null file1) rec-values)
-	(setq path (reftex-access-search-path
-		    type (pop rec-values) master-dir file))
-	(if (or (null old-path)
-		(not (eq old-path path)))
-	    (setq old-path path
-		  path (cons master-dir path)
-		  file1 (or (and (car files)
-				 (reftex-find-file-on-path
-				  (car files) path master-dir))
-			    (and (cdr files)
-				 (reftex-find-file-on-path
-				  (cdr files) path master-dir))))))))
+        (setq path (reftex-access-search-path
+                    type (pop rec-values) master-dir file))
+        (if (or (null old-path)
+                (not (eq old-path path)))
+            (setq old-path path
+                  path (cons master-dir path)
+                  file1 (or (and (car files)
+                                 (reftex-find-file-on-path 
+                                  (car files) path master-dir))
+                            (and (cdr files)
+                                 (reftex-find-file-on-path 
+                                  (cdr files) path master-dir))))))))
     (cond (file1 file1)
-	  (die (error "No such file: %s" file) nil)
-	  (t (message "No such file: %s (ignored)" file) nil))))
+          (die (error "No such file: %s" file) nil)
+          (t (message "No such file: %s (ignored)" file) nil))))
 
 (defun reftex-find-file-externally (file type &optional master-dir)
   ;; Use external program to find FILE.
   ;; The program is taken from `reftex-external-file-finders'.
   ;; Interprete relative path definitions starting from MASTER-DIR.
   (let ((default-directory (or master-dir default-directory))
-	(prg (cdr (assoc type reftex-external-file-finders)))
-	out)
+        (prg (cdr (assoc type reftex-external-file-finders)))
+        out)
     (if (string-match "%f" prg)
-	(setq prg (replace-match file t t prg)))
+        (setq prg (replace-match file t t prg)))
     (setq out (apply 'reftex-process-string (split-string prg)))
     (if (string-match "[ \t\n]+\\'" out)     ; chomp
-	(setq out (replace-match "" nil nil out)))
+        (setq out (replace-match "" nil nil out)))
     (cond ((equal out "") nil)
-	  ((file-regular-p out) (expand-file-name out master-dir))
-	  (t nil))))
+          ((file-regular-p out) (expand-file-name out master-dir))
+          (t nil))))
 
 (defun reftex-process-string (program &rest args)
   "Execute PROGRAM with arguments ARGS and return its STDOUT as a string."
   (let ((calling-dir default-directory))  ; remember default directory
     (with-output-to-string
       (with-current-buffer standard-output
-	(let ((default-directory calling-dir)) ; set default directory
-	  (apply 'call-process program nil '(t nil) nil args))))))
+        (let ((default-directory calling-dir)) ; set default directory
+          (apply 'call-process program nil '(t nil) nil args))))))
 
 (defun reftex-access-search-path (type &optional recurse master-dir file)
   ;; Access path from environment variables.  TYPE is either "tex" or "bib".
@@ -1480,51 +1486,51 @@
     (when (null (get pathvar 'status))
       ;; Get basic path
       (set pathvar
-	   (reftex-uniq
-	    (reftex-parse-colon-path
-	     (mapconcat
-	      (lambda(x)
-		(if (string-match "^!" x)
-		    (apply 'reftex-process-string
-			   (split-string (substring x 1)))
-		  (or (getenv x) x)))
-	      ;; For consistency, the next line should look like this:
-	      ;;  (cdr (assoc type reftex-path-environment))
-	      ;; However, historically we have separate options for the
-	      ;; environment variables, so we have to do this:
-	      (symbol-value (intern (concat "reftex-" type
-					    "path-environment-variables")))
-	      path-separator))))
+           (reftex-uniq
+            (reftex-parse-colon-path
+             (mapconcat
+              (lambda(x) 
+                (if (string-match "^!" x)
+                    (apply 'reftex-process-string
+                           (split-string (substring x 1)))
+                  (or (getenv x) x)))
+              ;; For consistency, the next line should look like this:
+              ;;  (cdr (assoc type reftex-path-environment))
+              ;; However, historically we have separate options for the
+              ;; environment variables, so we have to do this:
+              (symbol-value (intern (concat "reftex-" type 
+                                            "path-environment-variables")))
+              path-separator))))
       (put pathvar 'status 'split)
       ;; Check if we have recursive elements
       (let ((path (symbol-value pathvar)) dir rec)
-	(while (setq dir (pop path))
-	  (when (string= (substring dir -2) "//")
-	    (if (file-name-absolute-p dir)
-		(setq rec (or rec 'absolute))
-	      (setq rec 'relative))))
-	(put pathvar 'rec-type rec)))
+        (while (setq dir (pop path))
+          (when (string= (substring dir -2) "//")
+            (if (file-name-absolute-p dir)
+                (setq rec (or rec 'absolute))
+              (setq rec 'relative))))
+        (put pathvar 'rec-type rec)))
 
     (if recurse
-	;; Return the recursive expansion of the path
-	(cond
-	 ((not (get pathvar 'rec-type))
-	  ;; Path does not contain recursive elements - use simple path
-	  (symbol-value pathvar))
-	 ((or (not (get pathvar 'recursive-path))
-	      (and (eq (get pathvar 'rec-type) 'relative)
-		   (not (equal master-dir (get pathvar 'master-dir)))))
-	  ;; Either: We don't have a recursive expansion yet.
-	  ;; or:     Relative recursive path elements need to be expanded
-	  ;;         relative to new default directory
-	  (message "Expanding search path to find %s file: %s ..." type file)
-	  (put pathvar 'recursive-path
-	       (reftex-expand-path (symbol-value pathvar) master-dir))
-	  (put pathvar 'master-dir master-dir)
-	  (get pathvar 'recursive-path))
-	 (t
-	  ;; Recursive path computed earlier is still OK.
-	  (get pathvar 'recursive-path)))
+        ;; Return the recursive expansion of the path
+        (cond
+         ((not (get pathvar 'rec-type))
+          ;; Path does not contain recursive elements - use simple path
+          (symbol-value pathvar))
+         ((or (not (get pathvar 'recursive-path))
+              (and (eq (get pathvar 'rec-type) 'relative)
+                   (not (equal master-dir (get pathvar 'master-dir)))))
+          ;; Either: We don't have a recursive expansion yet.
+          ;; or:     Relative recursive path elements need to be expanded
+          ;;         relative to new default directory
+          (message "Expanding search path to find %s file: %s ..." type file)
+          (put pathvar 'recursive-path 
+               (reftex-expand-path (symbol-value pathvar) master-dir))
+          (put pathvar 'master-dir master-dir)
+          (get pathvar 'recursive-path))
+         (t 
+          ;; Recursive path computed earlier is still OK.
+          (get pathvar 'recursive-path)))
       ;; The simple path was requested
       (symbol-value pathvar))))
 
@@ -1534,15 +1540,15 @@
   (catch 'exit
     (when (file-name-absolute-p file)
       (if (file-regular-p file)
-	  (throw 'exit file)
-	(throw 'exit nil)))
+          (throw 'exit file)
+        (throw 'exit nil)))
     (let* ((thepath path) file1 dir)
       (while (setq dir (pop thepath))
-	(when (string= (substring dir -2) "//")
-	  (setq dir (substring dir 0 -1)))
-	(setq file1 (expand-file-name file (expand-file-name dir def-dir)))
-	(if (file-regular-p file1)
-	    (throw 'exit file1)))
+        (when (string= (substring dir -2) "//")
+          (setq dir (substring dir 0 -1)))
+        (setq file1 (expand-file-name file (expand-file-name dir def-dir)))
+        (if (file-regular-p file1)
+            (throw 'exit file1)))
       ;; No such file
       nil)))
 
@@ -1551,8 +1557,8 @@
   ;; Trailing ! or !! will be converted into `//' (emTeX convention)
   (mapcar
    (lambda (dir)
-     (if (string-match "\\(//+\\|/*!+\\)\\'" dir)
-	 (setq dir (replace-match "//" t t dir)))
+     (if (string-match "\\(//+\\|/*!+\\)\\'" dir) 
+         (setq dir (replace-match "//" t t dir)))
      (file-name-as-directory dir))
    (delete "" (split-string path (concat path-separator "+")))))
 
@@ -1562,15 +1568,15 @@
   (let (path1 dir recursive)
     (while (setq dir (pop path))
       (if (setq recursive (string= (substring dir -2) "//"))
-	  (setq dir (substring dir 0 -1)))
+          (setq dir (substring dir 0 -1)))
       (if (and recursive
-	       (not (file-name-absolute-p dir)))
-	  (setq dir (expand-file-name dir default-dir)))
+               (not (file-name-absolute-p dir)))
+          (setq dir (expand-file-name dir default-dir)))
       (if recursive
-	  ;; Expand recursively
-	  (setq path1 (append (reftex-recursive-directory-list dir) path1))
-	;; Keep unchanged
-	(push dir path1)))
+          ;; Expand recursively
+          (setq path1 (append (reftex-recursive-directory-list dir) path1))
+        ;; Keep unchanged
+        (push dir path1)))
     (nreverse path1)))
 
 (defun reftex-recursive-directory-list (dir)
@@ -1578,18 +1584,18 @@
   (let ((path (list dir)) path1 file files)
     (while (setq dir (pop path))
       (when (file-directory-p dir)
-	(setq files (nreverse (directory-files dir t "[^.]")))
-	(while (setq file (pop files))
-	  (if (file-directory-p file)
-	      (push (file-name-as-directory file) path)))
-	(push dir path1)))
+        (setq files (nreverse (directory-files dir t "[^.]")))
+        (while (setq file (pop files))
+          (if (file-directory-p file) 
+              (push (file-name-as-directory file) path)))
+        (push dir path1)))
     path1))
 
 (defun reftex-uniq (list)
   (let (new)
     (while list
       (or (member (car list) new)
-	  (push (car list) new))
+          (push (car list) new))
       (pop list))
     (nreverse new)))
 
@@ -1652,8 +1658,8 @@
   "Show the table of contents for the current document." t)
 (autoload 'reftex-toc-recenter "reftex-toc"
   "Display the TOC window and highlight line corresponding to current position." t)
-(autoload 'reftex-toggle-auto-toc-recenter "reftex-toc" t)
-
+(autoload 'reftex-toggle-auto-toc-recenter "reftex-toc" 
+  "Toggle automatic recentering of TOC window." t)
 
 ;;; =========================================================================
 ;;;
@@ -1791,6 +1797,13 @@
   (when (match-beginning n)
     (buffer-substring-no-properties (match-beginning n) (match-end n))))
 
+(defun reftex-region-active-p ()
+  "Is transient-mark-mode on and the region active?
+Works on both Emacs and XEmacs."
+  (if (featurep 'xemacs)
+      (and zmacs-regions (region-active-p))
+    (and transient-mark-mode mark-active)))
+
 (defun reftex-kill-buffer (buffer)
   ;; Kill buffer if it exists.
   (and (setq buffer (get-buffer buffer))
@@ -1848,7 +1861,7 @@
   (let* ((elt (car (member elt list))) (ex (not exclusive)) ass last-ass)
     (while (and (setq ass (assoc key list))
                 (setq list (memq ass list))
-		(or ex (not (eq elt (car list))))
+                (or ex (not (eq elt (car list))))
                 (memq elt list))
       (setq last-ass ass
             list (cdr list)))
@@ -1862,22 +1875,22 @@
   (let (rtn)
     (while list
       (if (funcall predicate (car list))
-	  (push (if completion
-		    (list (nth nth (car list)))
-		  (nth nth (car list)))
-		rtn))
+          (push (if completion
+                    (list (nth nth (car list))) 
+                  (nth nth (car list)))
+                rtn))
       (setq list (cdr list)))
     (nreverse rtn)))
 
 (defun reftex-make-selection-buffer-name (type &optional index)
   ;; Make unique name for a selection buffer.
   (format " *RefTeX[%s][%d]*"
-	  type (or index (get reftex-docstruct-symbol :master-index) 0)))
+          type (or index (get reftex-docstruct-symbol :master-index) 0)))
 
 (defun reftex-make-index-buffer-name (tag &optional cnt)
   ;; Make unique name for an index buffer.
   (format "*Index[%s][%d]*"
-	  tag (or cnt (get reftex-docstruct-symbol :master-index) 0)))
+          tag (or cnt (get reftex-docstruct-symbol :master-index) 0)))
 
 (defun reftex-truncate (string ncols &optional ellipses padding)
   ;; Truncate STRING to NCOLS characters.
@@ -1885,11 +1898,11 @@
   ;; white space to NCOLS characters.  When ELLIPSES is non-nil and the
   ;; string needs to be truncated, replace last 3 characters by dots.
   (setq string
-	(if (<= (length string) ncols)
-	    string
-	  (if ellipses
-	      (concat (substring string 0 (- ncols 3)) "...")
-	    (substring string 0 ncols))))
+        (if (<= (length string) ncols)
+            string
+          (if ellipses
+              (concat (substring string 0 (- ncols 3)) "...")
+            (substring string 0 ncols))))
   (if padding
       (format (format "%%-%ds" ncols) string)
     string))
@@ -1899,8 +1912,8 @@
   ;; If POS is given, calculate distances relative to it.
   ;; Return nil if there is no match.
   (let ((pos (point))
-	(dist (or max-length (length regexp)))
-	match1 match2 match)
+        (dist (or max-length (length regexp)))  
+        match1 match2 match)
     (goto-char (min (+ pos dist) (point-max)))
     (when (re-search-backward regexp nil t)
       (setq match1 (match-data)))
@@ -1936,14 +1949,14 @@
   ;; Enlarge other window displaying buffer to show whole buffer if possible.
   ;; If KEEP-CURRENT in non-nil, current buffer must remain visible.
   (let* ((win1 (selected-window))
-	 (buf1 (current-buffer))
-	 (win2 (get-buffer-window buf2))) ;; Only on current frame.
+         (buf1 (current-buffer))
+         (win2 (get-buffer-window buf2))) ;; Only on current frame.
     (when win2
       (select-window win2)
-      (unless (and (pos-visible-in-window-p 1)
-		   (pos-visible-in-window-p (point-max)))
-	(enlarge-window (1+ (- (count-lines 1 (point-max))
-			       (reftex-window-height))))))
+      (unless (and (pos-visible-in-window-p (point-min))
+                   (pos-visible-in-window-p (point-max)))
+        (enlarge-window (1+ (- (count-lines (point-min) (point-max))
+                               (reftex-window-height))))))
     (cond
      ((window-live-p win1) (select-window win1))
      (keep-current
@@ -1958,37 +1971,37 @@
   (let ((char ?\?))
     (save-window-excursion
       (catch 'exit
-	(message (concat prompt "   (?=Help)"))
-	(when (or (sit-for (or delay-time 0))
-		  (= ?\? (setq char (read-char-exclusive))))
-	  (reftex-kill-buffer "*RefTeX Select*")
-	  (switch-to-buffer-other-window "*RefTeX Select*")
-	  (insert help-string)
-	  (goto-char 1)
-	  (unless (and (pos-visible-in-window-p (point-min))
-		       (pos-visible-in-window-p (point-max)))
-	    (enlarge-window (1+ (- (count-lines (point-min) (point-max))
-				   (reftex-window-height)))))
-	  (setq truncate-lines t))
-	(if (and (pos-visible-in-window-p (point-min))
-		 (pos-visible-in-window-p (point-max)))
-	    nil
-	  (setq prompt (concat prompt (if scroll "   (SPC/DEL=Scroll)" ""))))
-	(message prompt)
-	(and (equal char ?\?) (setq char (read-char-exclusive)))
-	(while t
-	  (cond ((equal char ?\C-g) (keyboard-quit))
-		((equal char ?\?))
-		((and scroll (equal char ?\ ))
-		 (condition-case nil (scroll-up) (error nil))
-		 (message prompt))
-		((and scroll (equal char ?\C-? ))
-		 (condition-case nil (scroll-down) (error nil))
-		 (message prompt))
-		(t (message "")
-		   (throw 'exit char)))
-	  (setq char (read-char-exclusive)))))))
-
+        (message (concat prompt "   (?=Help)"))
+        (when (or (sit-for (or delay-time 0))
+                  (= ?\? (setq char (read-char-exclusive))))
+          (reftex-kill-buffer "*RefTeX Select*")
+          (switch-to-buffer-other-window "*RefTeX Select*")
+          (insert help-string)
+          (goto-char 1)
+          (unless (and (pos-visible-in-window-p (point-min))
+                       (pos-visible-in-window-p (point-max)))
+            (enlarge-window (1+ (- (count-lines (point-min) (point-max))
+                                   (reftex-window-height)))))
+          (setq truncate-lines t))
+        (if (and (pos-visible-in-window-p (point-min))
+                 (pos-visible-in-window-p (point-max)))
+            nil
+          (setq prompt (concat prompt (if scroll "   (SPC/DEL=Scroll)" ""))))
+        (message prompt)
+        (and (equal char ?\?) (setq char (read-char-exclusive)))
+        (while t
+          (cond ((equal char ?\C-g) (keyboard-quit))
+                ((equal char ?\?))
+                ((and scroll (equal char ?\ ))
+                 (condition-case nil (scroll-up) (error nil))
+                 (message prompt))
+                ((and scroll (equal char ?\C-? ))
+                 (condition-case nil (scroll-down) (error nil))
+                 (message prompt))
+                (t (message "") 
+                   (throw 'exit char)))
+          (setq char (read-char-exclusive)))))))
+      
 
 (defun reftex-make-regexp-allow-for-ctrl-m (string)
   ;; convert STRING into a regexp, allowing ^M for \n and vice versa
@@ -2011,14 +2024,14 @@
 ;; Define `current-message' for compatibility with XEmacs prior to 20.4
 (defvar message-stack)
 (if (and (featurep 'xemacs)
-	 (not (fboundp 'current-message)))
+         (not (fboundp 'current-message)))
     (defun current-message (&optional frame)
       (cdr (car message-stack))))
 
 (defun reftex-visited-files (list)
   ;; Takes a list of filenames and returns the buffers of those already visited
   (delq nil (mapcar (lambda (x) (if (reftex-get-buffer-visiting x) x nil))
-		    list)))
+                    list)))
 
 (defun reftex-get-file-buffer-force (file &optional mark-to-kill)
   ;; Return a buffer visiting file.  Make one, if necessary.
@@ -2049,7 +2062,7 @@
              (let ((format-alist nil)
                    (auto-mode-alist (reftex-auto-mode-alist))
                    (default-major-mode 'fundamental-mode)
-		   (enable-local-variables nil)
+                   (enable-local-variables nil)
                    (after-insert-file-functions nil))
                (setq buf (find-file-noselect file)))
 
@@ -2059,9 +2072,9 @@
                  (set-buffer buf)
                  (run-hooks 'reftex-initialize-temporary-buffers))))
 
-	   ;; Lets see if we got a license to kill :-|
-	   (and mark-to-kill
-		(add-to-list 'reftex-buffers-to-kill buf))
+           ;; Lets see if we got a license to kill :-|
+           (and mark-to-kill
+                (add-to-list 'reftex-buffers-to-kill buf))
 
            ;; Return the new buffer
            buf)
@@ -2111,7 +2124,7 @@
   (let (rtn)
     (while list
       (unless (symbolp (car list))
-	(push (car list) rtn))
+        (push (car list) rtn))
       (setq list (cdr list)))
     (nreverse rtn)))
 
@@ -2121,7 +2134,7 @@
     (while list
       (setq elm (pop list))
       (unless (member elm new)
-	(push elm new)))
+        (push elm new)))
     (nreverse new)))
 
 (defun reftex-uniquify-by-car (alist &optional keep-list)
@@ -2137,11 +2150,11 @@
 
 (defun reftex-abbreviate-title (string)
   (reftex-convert-string string "[-~ \t\n\r,;]" nil t t
-			 5 40 nil 1 " " (nth 5 reftex-derive-label-parameters)))
+                         5 40 nil 1 " " (nth 5 reftex-derive-label-parameters)))
 
 (defun reftex-convert-string (string split-re illegal-re dot keep-fp
-				     nwords maxchar illegal abbrev sep
-				     ignore-words &optional downcase)
+                                     nwords maxchar illegal abbrev sep
+                                     ignore-words &optional downcase)
   "Convert a string (a sentence) to something shorter.
 SPLIT-RE     is the regular expression used to split the string into words.
 ILLEGAL-RE   matches characters which are illegal in the final string.
@@ -2159,14 +2172,14 @@
 IGNORE-WORDS List of words which should be removed from the string."
 
   (let* ((words0 (split-string string (or split-re "[ \t\n\r]")))
-	 (reftex-label-illegal-re (or illegal-re "\000"))
-	 (abbrev-re (concat
-		     "\\`\\("
-		     (make-string (nth 0 reftex-abbrev-parameters) ?.)
-		     "[" (nth 2 reftex-abbrev-parameters) "]*"
-		     "\\)"
-		     "[" (nth 3 reftex-abbrev-parameters) "]"
-		     (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
+         (reftex-label-illegal-re (or illegal-re "\000"))
+         (abbrev-re (concat
+                     "\\`\\("
+                     (make-string (nth 0 reftex-abbrev-parameters) ?.)
+                     "[" (nth 2 reftex-abbrev-parameters) "]*"
+                     "\\)"
+                     "[" (nth 3 reftex-abbrev-parameters) "]"
+                     (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
          words word)
 
     ;; Remove words from the ignore list or with funny characters
@@ -2186,21 +2199,21 @@
     ;; Restrict number of words
     (if (> (length words) nwords)
         (setcdr (nthcdr (1- nwords) words) nil))
-
+    
     ;; First, try to use all words
     (setq string (mapconcat 'identity words sep))
-
+  
     ;; Abbreviate words if enforced by user settings or string length
     (if (or (eq t abbrev)
             (and abbrev
                  (> (length string) maxchar)))
         (setq words
               (mapcar
-	       (lambda (w) (if (string-match abbrev-re w)
-			       (if dot
-				   (concat (match-string 1 w) ".")
-				 (match-string 1 w))
-			     w))
+               (lambda (w) (if (string-match abbrev-re w)
+                               (if dot
+                                   (concat (match-string 1 w) ".")
+                                 (match-string 1 w))
+                             w))
                words)
               string (mapconcat 'identity words sep)))
 
@@ -2250,47 +2263,47 @@
   (and (reftex-use-fonts)
        (or (eq t reftex-refontify-context)
            (and (eq 1 reftex-refontify-context)
-		;; Test of we use the font-lock version of x-symbol
-		(and (featurep 'x-symbol-tex) (not (boundp 'x-symbol-mode)))))))
+                ;; Test of we use the font-lock version of x-symbol
+                (and (featurep 'x-symbol-tex) (not (boundp 'x-symbol-mode)))))))
 
 (defvar font-lock-defaults-computed)
 (defun reftex-fontify-select-label-buffer (parent-buffer)
   ;; Fontify the `*RefTeX Select*' buffer.  Buffer is temporarily renamed to
   ;; start with none-SPC char, beacuse Font-Lock otherwise refuses operation.
   (run-hook-with-args 'reftex-pre-refontification-functions
-		      parent-buffer 'reftex-ref)
+                      parent-buffer 'reftex-ref)
   (let* ((oldname (buffer-name))
-	 (newname (concat "Fontify-me-" oldname)))
+         (newname (concat "Fontify-me-" oldname)))
     (unwind-protect
-	(progn
-	  ;; Rename buffer temporarily to start w/o space (because of font-lock)
-	  (rename-buffer newname t)
-	  (cond
-	   ((fboundp 'font-lock-default-fontify-region)
-	    ;; Good: we have the indirection functions
-	    (set (make-local-variable 'font-lock-fontify-region-function)
-		 'reftex-select-font-lock-fontify-region)
-	    (let ((major-mode 'latex-mode))
-	      (font-lock-mode 1)))
-	   ((fboundp 'font-lock-set-defaults-1)
-	    ;; Looks like the XEmacs font-lock stuff.
-	    ;; FIXME: this is still kind of a hack, but it works.
-	    (set (make-local-variable 'font-lock-keywords) nil)
-	    (let ((major-mode 'latex-mode)
-		  (font-lock-defaults-computed nil))
-	      (font-lock-set-defaults-1)
-	      (reftex-select-font-lock-fontify-region (point-min) (point-max))))
-	   (t
-	    ;; Oops?
-	    (message "Sorry: cannot refontify RefTeX Select buffer."))))
+        (progn
+          ;; Rename buffer temporarily to start w/o space (because of font-lock)
+          (rename-buffer newname t)
+          (cond
+           ((fboundp 'font-lock-default-fontify-region)
+            ;; Good: we have the indirection functions
+            (set (make-local-variable 'font-lock-fontify-region-function)
+                 'reftex-select-font-lock-fontify-region)
+            (let ((major-mode 'latex-mode))
+              (font-lock-mode 1)))
+           ((fboundp 'font-lock-set-defaults-1)
+            ;; Looks like the XEmacs font-lock stuff.
+            ;; FIXME: this is still kind of a hack, but it works.
+            (set (make-local-variable 'font-lock-keywords) nil)
+            (let ((major-mode 'latex-mode)
+                  (font-lock-defaults-computed nil))
+              (font-lock-set-defaults-1)
+              (reftex-select-font-lock-fontify-region (point-min) (point-max))))
+           (t
+            ;; Oops? 
+            (message "Sorry: cannot refontify RefTeX Select buffer."))))
       (rename-buffer oldname))))
 
 (defun reftex-select-font-lock-fontify-region (beg end &optional loudly)
   ;; Fontify a region, but only lines starting with a dot.
   (let ((func (if (fboundp 'font-lock-default-fontify-region)
-		  'font-lock-default-fontify-region
-		'font-lock-fontify-region))
-	beg1 end1)
+                  'font-lock-default-fontify-region
+                'font-lock-fontify-region))
+        beg1 end1)
     (goto-char beg)
     (while (re-search-forward "^\\." end t)
       (setq beg1 (point) end1 (progn (skip-chars-forward "^\n") (point)))
@@ -2309,9 +2322,9 @@
   (let (face)
     (catch 'exit
       (while (setq face (pop faces))
-	(if (featurep 'xemacs)
-	    (if (find-face face) (throw 'exit face))
-	  (if (facep face) (throw 'exit face)))))))
+        (if (featurep 'xemacs)
+            (if (find-face face) (throw 'exit face))
+          (if (facep face) (throw 'exit face)))))))
 
 ;; Highlighting uses overlays.  For XEmacs, we need the emulation.
 (if (featurep 'xemacs) (require 'overlay))
@@ -2321,14 +2334,14 @@
 
 ;; Initialize the overlays
 (aset reftex-highlight-overlays 0 (make-overlay 1 1))
-(overlay-put (aref reftex-highlight-overlays 0)
-	     'face 'highlight)
+(overlay-put (aref reftex-highlight-overlays 0) 
+             'face 'highlight)
 (aset reftex-highlight-overlays 1 (make-overlay 1 1))
 (overlay-put (aref reftex-highlight-overlays 1)
-	     'face reftex-cursor-selected-face)
+             'face reftex-cursor-selected-face)
 (aset reftex-highlight-overlays 2 (make-overlay 1 1))
 (overlay-put (aref reftex-highlight-overlays 2)
-	     'face reftex-cursor-selected-face)
+             'face reftex-cursor-selected-face)
 
 ;; Two functions for activating and deactivation highlight overlays
 (defun reftex-highlight (index begin end &optional buffer)
@@ -2346,30 +2359,30 @@
 
 ;;; =========================================================================
 ;;;
-;;; Keybindings
+;;; Keybindings 
 
 ;; The default bindings in the mode map.
 (loop for x in
       '(("\C-c="  . reftex-toc)
-	("\C-c-"  . reftex-toc-recenter)
-	("\C-c("  . reftex-label)
-	("\C-c)"  . reftex-reference)
-	("\C-c["  . reftex-citation)
-	("\C-c<"  . reftex-index)
-	("\C-c>"  . reftex-display-index)
-	("\C-c/"  . reftex-index-selection-or-word)
-	("\C-c\\" . reftex-index-phrase-selection-or-word)
-	("\C-c|"  . reftex-index-visit-phrases-buffer)
-	("\C-c&"  . reftex-view-crossref))
+        ("\C-c-"  . reftex-toc-recenter)
+        ("\C-c("  . reftex-label)
+        ("\C-c)"  . reftex-reference)
+        ("\C-c["  . reftex-citation)
+        ("\C-c<"  . reftex-index)
+        ("\C-c>"  . reftex-display-index)
+        ("\C-c/"  . reftex-index-selection-or-word)
+        ("\C-c\\" . reftex-index-phrase-selection-or-word)
+        ("\C-c|"  . reftex-index-visit-phrases-buffer)
+        ("\C-c&"  . reftex-view-crossref))
       do (define-key reftex-mode-map (car x) (cdr x)))
 
 ;; Bind `reftex-mouse-view-crossref' only when the key is still free
 (if (featurep 'xemacs)
     (unless (key-binding [(shift button2)])
-      (define-key reftex-mode-map [(shift button2)]
-	'reftex-mouse-view-crossref))
+      (define-key reftex-mode-map [(shift button2)] 
+        'reftex-mouse-view-crossref))
   (unless (key-binding [(shift mouse-2)])
-    (define-key reftex-mode-map [(shift mouse-2)]
+    (define-key reftex-mode-map [(shift mouse-2)] 
       'reftex-mouse-view-crossref)))
 
 ;; Bind `reftex-view-crossref-from-bibtex' in BibTeX mode map
@@ -2380,14 +2393,14 @@
 ;; If the user requests so, she can have a few more bindings:
 (when reftex-extra-bindings
   (loop for x in
-	'(("\C-ct" . reftex-toc)
-	  ("\C-cl" . reftex-label)
-	  ("\C-cr" . reftex-reference)
-	  ("\C-cc" . reftex-citation)
-	  ("\C-cv" . reftex-view-crossref)
-	  ("\C-cg" . reftex-grep-document)
-	  ("\C-cs" . reftex-search-document))
-	do (define-key reftex-mode-map (car x) (cdr x))))
+        '(("\C-ct" . reftex-toc)
+          ("\C-cl" . reftex-label)
+          ("\C-cr" . reftex-reference)
+          ("\C-cc" . reftex-citation)
+          ("\C-cv" . reftex-view-crossref)
+          ("\C-cg" . reftex-grep-document)
+          ("\C-cs" . reftex-search-document))
+        do (define-key reftex-mode-map (car x) (cdr x))))
 
 ;;; =========================================================================
 ;;;
@@ -2464,23 +2477,23 @@
      :style toggle :selected reftex-plug-into-AUCTeX])
    ("Reference Style"
     ["Default" (setq reftex-vref-is-default nil
-		     reftex-fref-is-default nil)
-     :style radio :selected (not (or reftex-vref-is-default
-				     reftex-fref-is-default))]
+                     reftex-fref-is-default nil)
+     :style radio :selected (not (or reftex-vref-is-default 
+                                     reftex-fref-is-default))]
     ["Varioref" (setq reftex-vref-is-default t
-		      reftex-fref-is-default nil)
+                      reftex-fref-is-default nil)
      :style radio :selected reftex-vref-is-default]
     ["Fancyref" (setq reftex-fref-is-default t
-		      reftex-vref-is-default nil)
+                      reftex-vref-is-default nil)
      :style radio :selected reftex-fref-is-default])
    ("Citation Style"
     ,@(mapcar
        (lambda (x)
-	 (vector
-	  (capitalize (symbol-name (car x)))
-	  (list 'reftex-set-cite-format (list 'quote (car x)))
-	  :style 'radio :selected
-	  (list 'eq (list 'reftex-get-cite-format) (list 'quote (car x)))))
+         (vector
+          (capitalize (symbol-name (car x)))
+          (list 'reftex-set-cite-format (list 'quote (car x)))
+          :style 'radio :selected
+          (list 'eq (list 'reftex-get-cite-format) (list 'quote (car x)))))
        reftex-cite-format-builtin)
     "--"
     "Sort Database Matches"
@@ -2495,13 +2508,13 @@
    ("Index Style"
     ,@(mapcar
        (lambda (x)
-	 (vector
-	  (capitalize (symbol-name (car x)))
-	  (list 'reftex-add-index-macros (list 'list (list 'quote (car x))))
-	  :style 'radio :selected
-	  (list 'memq (list 'quote (car x))
-		(list 'get 'reftex-docstruct-symbol
-		      (list 'quote 'reftex-index-macros-style)))))
+         (vector
+          (capitalize (symbol-name (car x)))
+          (list 'reftex-add-index-macros (list 'list (list 'quote (car x))))
+          :style 'radio :selected
+          (list 'memq (list 'quote (car x))
+                (list 'get 'reftex-docstruct-symbol 
+                      (list 'quote 'reftex-index-macros-style)))))
        reftex-index-macros-builtin))
    "--"
     ["Reset RefTeX Mode"       reftex-reset-mode t]
@@ -2509,7 +2522,7 @@
    ("Customize"
     ["Browse RefTeX Group" reftex-customize t]
     "--"
-    ["Build Full Customize Menu" reftex-create-customize-menu
+    ["Build Full Customize Menu" reftex-create-customize-menu 
      (fboundp 'customize-menu-create)])
    ("Documentation"
     ["Info" reftex-info t]
@@ -2525,17 +2538,17 @@
   (interactive)
   (if (fboundp 'customize-menu-create)
       (progn
-	(easy-menu-change
-	 '("Ref") "Customize"
-	 `(["Browse RefTeX group" reftex-customize t]
-	   "--"
-	   ,(customize-menu-create 'reftex)
-	   ["Set" Custom-set t]
-	   ["Save" Custom-save t]
-	   ["Reset to Current" Custom-reset-current t]
-	   ["Reset to Saved" Custom-reset-saved t]
-	   ["Reset to Standard Settings" Custom-reset-standard t]))
-	(message "\"Ref\"-menu now contains full customization menu"))
+        (easy-menu-change 
+         '("Ref") "Customize"
+         `(["Browse RefTeX group" reftex-customize t]
+           "--"
+           ,(customize-menu-create 'reftex)
+           ["Set" Custom-set t]
+           ["Save" Custom-save t]
+           ["Reset to Current" Custom-reset-current t]
+           ["Reset to Saved" Custom-reset-saved t]
+           ["Reset to Standard Settings" Custom-reset-standard t]))
+        (message "\"Ref\"-menu now contains full customization menu"))
     (error "Cannot expand menu (outdated version of cus-edit.el)")))
 
 (defun reftex-show-commentary ()
@@ -2563,7 +2576,7 @@
 ;;; That's it! ----------------------------------------------------------------
 
 (setq reftex-tables-dirty t)  ; in case this file is evaluated by hand
-(provide 'reftex)
+(provide 'reftex) 
 
 ;;;============================================================================