Anonymous committed 7d7c1b3

Baseline reftex package, version 1.0

Comments (0)

Files changed (5)

+1998-02-10  SL Baur  <>
+	* Created.
+# Makefile for Miscellaneous TeX utilities lisp code
+# This file is part of XEmacs.
+# XEmacs is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by the
+# Free Software Foundation; either version 2, or (at your option) any
+# later version.
+# XEmacs 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 GNU General Public License
+# for more details.
+# You should have received a copy of the GNU General Public License
+# along with XEmacs; see the file COPYING.  If not, write to
+# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+VERSION = 1.0
+MAINTAINER = Carsten Dominik <>
+PACKAGE = reftex
+PKG_TYPE = regular
+REQUIRES = xemacs-base
+ELCS = reftex.elc
+include ../../XEmacs.rules
+all:: $(ELCS) auto-autoloads.elc $(PACKAGE).info
+ reftex.texinfo
+srckit: srckit-std
+binkit: binkit-sourceinfo
+  (standards-version 1.0
+   version VERSION
+   author-version AUTHOR_VERSION
+   date DATE
+   build-date BUILD_DATE
+   maintainer MAINTAINER
+   distribution stable
+   priority medium
+   category CATEGORY
+   dump nil
+   description "Emacs support for LaTeX cross-references, citations.."
+   filename FILENAME
+   md5sum MD5SUM
+   size SIZE
+   provides (reftex)
+   requires (REQUIRES)
+   type regular
+;; reftex.el --- Minor mode for doing \label, \ref and \cite in LaTeX
+;; Copyright (c) 1997, 1998 Free Software Foundation, Inc.
+;; Version:    3.17 
+;; Author:     Carsten Dominik <>
+;; Keywords:   tex
+;; This file is part of GNU Emacs.
+;; GNU Emacs is free software; you can redistribute it and/or modify
+;; it under the terms of the GNU General Public License as published by
+;; the Free Software Foundation; either version 2, or (at your option)
+;; any later version.
+;; GNU Emacs is distributed in the hope that it will be useful,
+;; but WITHOUT ANY WARRANTY; without even the implied warranty of
+;; 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
+;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+;;; Commentary:
+;; RefTeX is a minor mode with distinct support for \ref, \label and
+;; \cite commands in (multi-file) LaTeX documents.
+;; Labels are created semi-automatically.  Definition context of labels is
+;; provided when creating a reference.  Citations are simplified with
+;; efficient database lookup.  A table of contents buffer provides easy
+;; access to any part of a document.
+;; To turn RefTeX Minor Mode on and off in a particular buffer, use
+;; `M-x reftex-mode'.
+;; To turn on RefTeX Minor Mode for all LaTeX files, add one of 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
+;; -------------
+;; There is an extensive texinfo document describing RefTeX in detail.
+;; When you are getting reftex.el with the Emacs distribution, the
+;; info files should already be installed.  To view this
+;; documentation, use `M-x reftex-info RET'.
+;; The documentation is also available at
+;; RefTeX in a Nutshell
+;; ====================
+;;   1. Labels and References
+;;      RefTeX distinguishes labels for different environments.  It always
+;;      knows if a certain label references a figure, table etc..  You can
+;;      configure RefTeX 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
+;;              - derive a label from context (default for section labels)
+;;              - insert a simple label consisting of a prefix and a number
+;;                (default for equations, enumerate items, and footnotes)
+;;                or
+;;              - prompt for a label string (figures and tables).
+;;           Which labels are created how is configurable (variable
+;;         - Referencing Labels
+;;           Referencing labels is a snap and I promise you'll love it.
+;;           In order 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
+;;           context of the label definition.  Selecting one of the labels
+;;           inserts a `\ref' macro into the original buffer.  Online help
+;;           during the selection is available with `?'.
+;;   2. Citations
+;;      After typing `C-c [' (`reftex-citation'), RefTeX will let you
+;;      specify a regular expression to search in current BibTeX database
+;;      files (as specified in the `\bibliography' command) and pull out a
+;;      formatted list of matches for you to choose from.  The list is
+;;      *formatted* and sorted, thus much easier to read than the raw
+;;      database entries.  The text inserted into the buffer is by default
+;;      just `\cite{KEY}', but can also contain author names and the year
+;;      in a configurable way (variable REFTEX-CITE-FORMAT).
+;;   3. Viewing Cross References
+;;      With point on or anywhere before a `\ref' or `\cite' macro, press
+;;      `C-c &' (`reftex-view-crossref').  This will display the
+;;      corresponding label definition or BibTeX database entry in another
+;;      window.
+;;   4. Table of Contents
+;;      Typing `C-c =' (`reftex-toc') will show a table of contents of the
+;;      document.  From that buffer, you can jump quickly to every part of
+;;      your document.
+;;   5. Multifile Documents
+;;      Multifile Domuments are fully supported. RefTeX will provide cross
+;;      referencing information from all files which are part of the
+;;      document. You may also use it to reference labels in external
+;;      documents (in cooperation with the LaTeX package `xr').
+;;   6. Document Parsing
+;;      RefTeX needs to parse the document in order to find labels and
+;;      other information.  It will do it automatically once, when you
+;;      start working with a document.  Re-parsing should not be necessary
+;;      too often since RefTeX updates its lists internally when you make
+;;      a new label with `reftex-label'.  To enforce reparsing, call any
+;;      of the commands described above with a raw `C-u' prefix, or press
+;;      the `r' key in the label selection buffer or the table of contents
+;;      buffer.
+;; ======
+;; Carsten Dominik <>
+;;         with contributions from Stephen Eglen
+;; The newest version of RefTeX can be found at
+;; The version at this site is compatible with Emacs 19 - the version
+;; distributed with Emacs 20 is not.
+;; ---------
+;; Thanks to the people on the Net who have used RefTeX and helped
+;; developing it with their reports.  In particular thanks to
+;;    F. Burstall, Alastair Burt, Soren Dayton, Stephen Eglen,
+;;    Karl Eichwalder, Peter Galbraith, Dieter Kraft, Adrian Lanz,
+;;    Rory Molinari, Laurent Mugnier, Sudeep Kumar Palat, Daniel Polani,
+;;    Robin Socha, Richard Stanton, Allan Strand, Jan Vroonhof,
+;;    Christoph Wedler.
+;; The view crossref feature was inspired by the similar function in
+;; Peter Galbraith's bib-cite.el.
+;; Finally thanks to Uwe Bolick who first got me (some years ago) into
+;; supporting LaTeX labels and references with an Editor (which was
+;; MicroEmacs at the time).
+;; =======
+;; Here are the more important changes made to RefTeX since initial release.
+;; Minor bug fixes are not mentioned.
+;; Version 1.00
+;;    - released on 7 Jan 1997.
+;; Version 1.04
+;;    - Macros as wrappers, AMSTeX support, delayed context parsing for
+;;      new labels.
+;; Version 1.05
+;;    - XEmacs port.
+;; Version 1.07
+;;    - RefTeX gets its own menu.
+;; Version 1.09
+;;    - Support for tex-main-file, an analogue for TeX-master.
+;;    - MS-DOS support.
+;; Version 2.00
+;;    - Labels can be derived from context (default for sections).
+;;    - Configuration of label insertion and label referencing revised.
+;;    - Crossref fields in BibTeX database entries.
+;;    - `reftex-toc' introduced (thanks to Stephen Eglen).
+;; Version 2.03
+;;    - Figure*, table*, Sidewaysfigure/table added to default environments.
+;;    - `reftex-bibfile-ignore-list' introduced (thanks to Rory Molinari).
+;;    - New functions `reftex-arg-label', `reftex-arg-ref', `reftex-arg-cite'.
+;;    - Emacs/XEmacs compatibility reworked.  XEmacs 19.15 now is required.
+;;    - `reftex-add-to-label-alist' (to be called from AUCTeX style files).
+;;    - Finding context with a hook function.
+;;    - Sorting BibTeX entries (new variable: `reftex-sort-bibtex-matches').
+;; Version 2.05
+;;    - Support for `custom.el'.
+;;    - New function `reftex-grep-document' (thanks to Stephen Eglen).
+;; Version 2.07
+;;    - New functions `reftex-search-document', `reftex-query-replace-document'
+;; Version 2.11
+;;    - Submitted for inclusion to Emacs and XEmacs.
+;; Version 2.14
+;;    - Variable `reftex-plug-into-AUCTeX' simplifies cooperation with AUCTeX.
+;; Version 2.17
+;;    - Label prefix expands % escapes with current file name and other stuff.
+;;    - Citation format now with % escapes.  This is not backward compatible!
+;;    - TEXINPUTS variable recognized when looking for input files.
+;;    - Context can be the nth argument of a macro.
+;;    - Searching in the select buffer is now possible (C-s and C-r).
+;;    - Display and derive-label can use two different context methods.
+;;    - AMSmath xalignat and xxalignat added.
+;; Version 3.00
+;;    - RefTeX should work better for very large projects:
+;;       - The new parser works without creating a master buffer.
+;;       - Rescanning can be limited to a part of a multifile document.
+;;       - Information from the parser can be stored in a file.
+;;    - RefTeX can deal with macros having a naked label as an argument.
+;;    - Macros may have white space and newlines between arguments.
+;;    - Multiple identical section headings no longer confuse `reftex-toc'.
+;;    - RefTeX should work correctly in combination with buffer-altering
+;;      packages like outline, folding, x-symbol, iso-cvt, isotex, etc.
+;;    - All labeled environments discussed in `The LaTeX Companion' by
+;;      Goossens, Mittelbach & Samarin, Addison-Wesley 1994) are part of
+;;      RefTeX's defaults.
+;; Version 3.03
+;;    - Support for the LaTeX package `xr', for inter-document references.
+;;    - A few (minor) Mule-related changes.
+;;    - Fixed bug which could cause HUGE .rel files.
+;;    - Search for input and .bib files with recursive path definitions.
+;; Version 3.04
+;;    - Fixed BUG in the `xr' support.
+;; Version 3.05
+;;    - Compatibility code now first checks for XEmacs feature.
+;; Version 3.07
+;;    - `Ref' menu improved.
+;; Version 3.10
+;;    - Fixed a bug which made reftex 3.07 fail on [X]Emacs version 19.
+;;    - Removed unimportant code which caused OS/2 Emacs to crash.
+;;    - All customization variables now accessible from menu.
+;; Version 3.11
+;;    - Fixed bug which led to naked label in (e.g.) footnotes.
+;;    - Added scroll-other-window functions to RefTeX-Select.
+;; Version 3.12
+;;    - There are 3 new keymaps for customization: `reftex-toc-map',
+;;      `reftex-select-label-map', `reftex-select-bib-map'.
+;;    - Refontification uses more standard font-lock stuff.
+;;    - When no BibTeX database files are specified, citations can also
+;;      use \bibitem entries from a `thebibliography' environment.
+;; Version 3.14
+;;    - Selection buffers can be kept between selections: this is faster.
+;;      See new variable `reftex-use-multiple-selection-buffers'.
+;;    - Prefix interpretation of reftex-view-crossref changed.
+;;    - Support for the `varioref' package (`v' key in selection buffer).
+;; Version 3.16
+;;    - New hooks `reftex-format-label-function', `reftex-format-ref-function',
+;;      `reftex-format-cite-function'.
+;;    - TeXInfo documentation completed.
+;;    - Some restrictions in Label inserting and referencing removed.
+;;    - New variable `reftex-default-bibliography'.
+;; Version 3.17
+;;    - Additional bindings in selection and *toc* buffers.  `g' redefined. 
+;;    - New command `reftex-save-all-document-buffers'.
+;;    - Magic word matching made more intelligent.
+;;    - Selection process can switch to completion (with TAB).
+;;    - \appendix is now recognized and influences section numbering.
+;;    - File commentary shortened considerably (use Info documentation).
+;;    - New option `reftex-no-include-regexps' to skip some include files.
+;;    - New option `reftex-revisit-to-follow'.
+;;; Code:
+(eval-when-compile (require 'cl))
+;; Stuff that needs to be there when we use defcustom
+;; --------------------------------------------------
+(require 'custom)
+(defvar reftex-tables-dirty t
+  "Flag showing if tables need to be re-computed.")
+  (defun reftex-set-dirty (symbol value)
+    (setq reftex-tables-dirty t)
+    (set symbol value)))
+  (defmacro reftex-fp (n)
+    (if (fboundp 'forward-point) 
+	(list 'forward-point n)
+      (list '+ '(point) n))))
+;;; Begin of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; Define the two constants which are needed during compilation
+(defconst reftex-label-alist-builtin
+  '(
+    ;; Some aliases, mostly for backward compatibility
+    (Sideways    "Alias for -->rotating" (rotating))
+    (AMSTeX      "amsmath with eqref macro"
+                 ((nil ?e nil "~\\eqref{%s}")
+                  amsmath))
+    ;; Individual package defaults
+    (amsmath "AMS-LaTeX math environments"
+     (("align"        ?e nil nil eqnarray-like)
+      ("gather"       ?e nil nil eqnarray-like)
+      ("multline"     ?e nil nil t)
+      ("flalign"      ?e nil nil eqnarray-like)
+      ("alignat"      ?e nil nil alignat-like)
+      ("xalignat"     ?e nil nil alignat-like)
+      ("xxalignat"    ?e nil nil alignat-like)
+      ("subequations" ?e nil nil t)))
+    (endnotes "The \\endnote macro"
+     (("\\endnote[]{}" ?n nil nil 2 (regexp "Endnotes?"))))
+    (fancybox "The Beqnarray environment"
+     (("Beqnarray" ?e nil nil eqnarray-like)))
+    (floatfig "The floatingfigure environment"
+     (("floatingfigure" ?f nil nil caption)))
+    (longtable   "The longtable environment"
+     (("longtable"  ?t nil nil caption)))
+    (picinpar    "The figwindow and tabwindow environments"
+     (("figwindow" ?f nil nil 1)
+      ("tabwindow" ?f nil nil 1)))
+    (rotating    "Sidewaysfigure and table"
+     (("sidewaysfigure" ?f nil nil caption)
+      ("sidewaystable"  ?t nil nil caption)))
+    (subfigure   "Subfigure environments/macro"
+     (("subfigure"   ?f nil nil caption)
+      ("subfigure*"  ?f nil nil caption)
+      ("\\subfigure[]{}" ?f nil nil 1)))
+    (supertab    "Supertabular environment"
+     (("supertabular" ?t nil nil "\\tablecaption{")))
+    (wrapfig     "The wrapfigure environment"
+     (("wrapfigure" ?f nil nil caption)))
+    ;; The LaTeX core stuff
+    (LaTeX       "LaTeX default environments"
+     (("section"   ?s "sec:" "~\\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\\."))
+      ("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 "note:" "~\\ref{%s}" 2
+       (regexp "Footnotes?" "Notes?"))
+      ("any"       ?\  " "   "~\\ref{%s}" nil)))
+    )
+  "The default label environment descriptions.
+Lower-case symbols correspond to a style file of the same name in the LaTeX
+distribution.  Mixed-case symbols are convenience aliases.")
+(defconst reftex-cite-format-builtin
+  '(
+    (default "Default macro \\cite{%l}"
+      "\\cite{%l}")
+    (natbib "The Natbib package"
+     ((?\C-m . "\\cite{%l}")
+      (?t    . "\\citet{%l}")
+      (?T    . "\\citet*{%l}")
+      (?p    . "\\citep{%l}")
+      (?P    . "\\citep*{%l}")
+      (?e    . "\\citep[e.g.][]{%l}")
+      (?a    . "\\citeauthor{%l}")
+      (?y    . "\\citeyear{%l}")))
+    (harvard "The Harvard package"
+     ((?\C-m . "\\cite{%l}")
+      (?p    . "\\cite{%l}")
+      (?t    . "\\citeasnoun{%l}")
+      (?n    . "\\citeasnoun{%l}")
+      (?s    . "\\possessivecite{%l}")
+      (?e    . "\\citeaffixed{%l}{?}")
+      (?y    . "\\citeyear{%l}")
+      (?a    . "\\citename{%l}")))
+    (chicago "The Chicago package"
+     ((?\C-m . "\\cite{%l}")
+      (?t    . "\\citeN{%l}")
+      (?T    . "\\shortciteN{%l}")
+      (?p    . "\\cite{%l}")
+      (?P    . "\\shortcite{%l}")
+      (?a    . "\\citeA{%l}")
+      (?A    . "\\shortciteA{%l}")
+      (?y    . "\\citeyear{%l}")))
+    (astron "The Astron package"
+     ((?\C-m . "\\cite{%l}")
+      (?p    . "\\cite{%l}" )
+      (?t    . "%2a (\\cite{%l})")))
+    (author-year "Do-it-yourself Author-year"
+     ((?\C-m . "\\cite{%l}")
+      (?t    . "%2a (%y)\\nocite{%l}")
+      (?p    . "(%2a %y\\nocite{%l})")))
+    (locally     "Full info in parenthesis"
+     "(%2a %y, %j %v, %P, %e: %b, %u, %s %<)")
+    ;; undocumented feature: `%<' kills white space and punctuation locally.
+    )
+  "Builtin versions of for the citation format.
+The following conventions are valid for all alist entries:
+`?\C-m' should always point to a straight \\cite{%l} macro.
+`?t'    should point to a textual citation (citation as a noun).
+`?p'    should point to a parenthetical citation.")
+;; Configuration Variables and User Options for RefTeX ------------------
+(defgroup reftex nil
+  "LaTeX label and citation support."
+  :tag "RefTeX"
+  :link '(url-link :tag "Home Page" 
+		   "")
+  :link '(emacs-commentary-link :tag "Commentary in reftex.el" "reftex.el")
+  :prefix "reftex-"
+  :group 'tex)
+(defun reftex-customize ()
+  "Call the customize function with reftex as argument."
+  (interactive)
+  ;; Depending on the customize version we can call different functions.
+  (cond
+   ((fboundp 'customize-browse)
+    (customize-browse 'reftex))
+   ((fboundp 'customize-group)
+    (customize-group 'reftex))
+   ((fboundp 'customize)
+    (customize 'reftex))
+   (t (error "Custom.el not available"))))
+(defun reftex-create-customize-menu ()
+  "Create a full customization menu for RefTeX."
+  (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"))
+    (error "Cannot expand menu (outdated version of cus-edit.el)")))
+(defun reftex-show-commentary ()
+  "Use the finder to view the file documentation from `reftex.el'."
+  (interactive)
+  (require 'finder)
+  (finder-commentary "reftex.el"))
+(defun reftex-info ()
+  "Read documentation for RefTeX in the info system."
+  (interactive)
+  (require 'info)
+  (Info-goto-node "(reftex)"))
+;; Support for \label and \ref --------------------------------------
+(defgroup reftex-label-support nil
+  "Support for creation, insertion and referencing of labels in LaTeX."
+  :group 'reftex)
+(defgroup reftex-defining-label-environments nil
+  "Definition of environments and macros to do with label."
+  :group 'reftex-label-support)
+;; Make a constant for the customization stuff
+  (defconst reftex-tmp
+    '((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))))
+(defcustom reftex-default-label-alist-entries
+  '(amsmath endnotes fancybox floatfig longtable picinpar
+	    rotating subfigure supertab wrapfig LaTeX)
+  "Default label alist specifications.  LaTeX should be the last entry.
+This list describes the default label environments RefTeX should always use.
+It is probably a mistake to remove the LaTeX symbol from this list.
+The options include:
+LaTeX      The standard LaTeX environments.
+Sideways   The sidewaysfigure and sidewaystable environments.
+AMSTeX     The math environments in the AMS-LaTeX amsmath package.
+For the full list of options, try
+M-x customize-variable RET reftex-default-label-alist-entries RET."
+  :group 'reftex-defining-label-environments
+  :set   'reftex-set-dirty
+  :type `(set
+	  :indent 4
+          :inline t
+          :greedy t
+          ,@(mapcar
+             (function
+              (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
+  "Alist with information on environments for \\label-\\ref use.
+This docstring is easier to understand after reading the configuration
+examples in `reftex.el'.  Looking at the builtin defaults in the constant
+`reftex-label-alist-builtin' may also be instructive.
+Set this variable to define additions and changes to the default.  The only
+things you MUST NOT change is that `?s' is the type indicator for section
+labels, and SPC for the `any' label type.  These are hard-coded at other
+places in the code.
+Each list entry describes either an environment carrying a counter for use
+with \\label and \\ref, or a LaTeX macro defining a label as (or inside)
+one of its arguments.  The elements of each list entry are:
+0.  Name of the environment (like \"table\") or macro (like \"\\\\myfig\").
+    For macros, indicate the macro arguments for best results, as in
+    \"\\\\myfig[]{}{}{*}{}\".  Use square brackets for optional arguments,
+    a star to mark the label argument, if any.  The macro does not have to
+    have a label argument - you could also use \\label{..} inside one of
+    its arguments.
+    Special names: `section' for section labels, `any' to define a group
+    which contains all labels.
+    This may also be nil if the entry is only meant to change some settings
+    associated with the type indicator character (see below).
+1.  Type indicator character, like `?t', must be a printable ASCII character.
+    The type indicator is a single character which defines a label type.
+    Any label inside the environment or macro is assumed to belong to this
+    type.  The same character may occur several times in this list, to cover
+    cases in which different environments carry the same label type (like
+    `equation' and `eqnarray').
+2.  Label prefix string, like \"tab:\".
+    The prefix is a short string used as the start of a label.  It may be the
+    empty string.  The prefix may contain the following `%' escapes:
+       %f   Current file name with directory and extension stripped.
+       %F   Current file name relative to directory of master file.
+       %u   User login name, on systems which support this.
+    Example: In a file `intro.tex', \"eq:%f:\" will become \"eq:intro:\").
+3.  Format string for reference insert in buffer.  `%s' will be replaced by
+    the label.
+    When the format starts with `~', the `~' will only be inserted if
+    there is not already a whitespace before point.
+4.  Indication on how to find the short context.
+    - If nil, use the text following the \\label{...} macro.
+    - If t, use
+       - the section heading for section labels.
+       - text following the \\begin{...} statement of environments.
+         (not a good choice for environments like eqnarray or enumerate,
+         where one has several labels in a single environment).
+       - text after the macro name (starting with the first arg) for macros.
+    - If an integer, use the nth argument of the macro.  As a special case,
+      1000 means to get text after the last macro argument.
+    - If a string, use as regexp to search *backward* from the label.  Context
+      is then the text following the end of the match.  E.g. putting this to
+      \"\\\\\\\\caption[[{]\" will use the caption in a figure or table
+      environment.
+      \"\\\\\\\\begin{eqnarray}\\\\|\\\\\\\\\\\\\\\\\" works for eqnarrays.
+    - If any of `caption', `item', `eqnarray-like', `alignat-like', this
+      symbol will internally be translated into an appropriate regexp
+      (see also the variable `reftex-default-context-regexps').
+    - If a function, call this function with the name of the environment/macro
+      as argument.  On call, point will be just after the \\label macro.  The
+      function is expected to return a suitable context string.  It should
+      throw an exception (error) when failing to find context.
+      As an example, here is a function returning the 10 chars following
+      the label macro as context:
+        (defun my-context-function (env-or-mac)
+          (if (> (point-max) (+ 10 (point)))
+              (buffer-substring (point) (+ 10 (point)))
+            (error \"Buffer too small\")))
+    Label context is used in two ways by RefTeX: For display in the label
+    menu, and to derive a label string.  If you want to use a different
+    method for each of these, specify them as a dotted pair.
+    E.g. `(nil . t)' uses the text after the label (nil) for display, and
+    text from the default position (t) to derive a label string.  This is
+    actually used for section labels.
+    Setting the variable `reftex-use-text-after-label-as-context' to t
+    overrides the setting here.
+5.  List of magic words which identify a reference to be of this type.
+    If the word before point is equal to one of these words when calling
+    `reftex-reference', the label list offered will be automatically
+    restricted to labels of the correct type.
+    If the first element of this wordlist is the symbol `regexp', the
+    strings are interpreted as regular expressions.  RefTeX will add
+    a \"\\\\W\" to the beginning and other stuff to the end of the regexp.
+If the type indicator characters of two or more entries are the same, RefTeX
+will use
+ - the first non-nil format and prefix
+ - the magic words of all involved entries.
+Any list entry may also be a symbol.  If that has an association in
+`reftex-label-alist-builtin', the cddr of that association is spliced into the
+list.  However, builtin defaults should normally be set with the variable
+  :group 'reftex-defining-label-environments
+  :set 'reftex-set-dirty
+  :type
+  `(repeat
+    (choice
+     :value ("" ?a nil nil nil nil)
+     (list :tag "Detailed label alist entry"
+           :value ("" ?a nil nil nil nil)
+           (choice    :tag "Environment or \\macro "
+                      (const  :tag "Ignore, just use typekey" nil)
+                      (string ""))
+           (character :tag "Typekey character     " ?a)
+           (choice    :tag "Label prefix string   "
+                      (const  :tag "Default" nil)
+                      (string :tag "String" "lab:"))
+           (choice    :tag "Label reference format"
+                      (const  :tag "Default" nil)
+                      (string :tag "String" "~\\ref{%s}"))
+           (choice :tag "Context"
+                   (choice
+                    :tag "1 method"
+                    ,@reftex-tmp)
+                   (cons :tag "Split methods"
+                         (choice
+                          :tag "  Display context     "
+                          ,@reftex-tmp)
+                         (choice
+                          :tag "  Derive label context"
+                          ,@reftex-tmp)))
+	   (repeat :tag "List of Magic Words" (string)))
+     (choice
+      :tag "Package"
+      :value AMSTeX
+      ,@(mapcar
+         (function
+          (lambda (x)
+            (list 'const ':tag (concat (symbol-name (nth 0 x)))
+                  (nth 0 x))))
+         reftex-label-alist-builtin)))))
+;; LaTeX section commands and level numbers
+(defcustom reftex-section-levels
+  '(
+    ("part"            . 0)
+    ("chapter"         . 1)
+    ("section"         . 2)
+    ("subsection"      . 3)
+    ("subsubsection"   . 4)
+    ("paragraph"       . 5)
+    ("subparagraph"    . 6)
+    ("subsubparagraph" . 7)
+    )
+  "Commands and levels used for defining sections in the document.
+The car of each cons cell is the name of the section macro.  The cdr is a
+number indicating its level."
+  :group 'reftex-defining-label-environments
+  :set 'reftex-set-dirty
+  :type '(repeat
+          (cons (string :tag "sectioning macro" "")
+                (number :tag "level           " 0))))
+(defcustom reftex-default-context-regexps
+  '((caption       . "\\\\\\(rot\\)?caption\\*?[[{]")
+    (item          . "\\\\item\\(\\[[^]]*\\]\\)?")
+    (eqnarray-like . "\\\\begin{%s}\\|\\\\\\\\")
+    (alignat-like  . "\\\\begin{%s}{[0-9]*}\\|\\\\\\\\"))
+"Alist with default regular expressions for finding context.
+The form (format regexp (regexp-quote environment)) is used to calculate
+the final regular expression - so %s will be replaced with the environment
+or macro."
+  :group 'reftex-defining-label-environments
+  :type '(repeat (cons (symbol) (regexp))))
+(defcustom reftex-use-text-after-label-as-context nil
+  "*t means, grab context from directly after the \\label{..} macro.
+This is the fastest method for obtaining context of the label definition, but
+requires discipline when placing labels.  Setting this variable to t takes
+precedence over the individual settings in `reftex-label-alist'.
+This variable may be set to t, nil, or a string of label type letters
+indicating the label types for which it should be true."
+  :group 'reftex-defining-label-environments
+  :set 'reftex-set-dirty
+  :type '(choice
+          (const :tag "on" t) (const :tag "off" nil)
+          (string :tag "Selected label types")))
+;; Label insertion
+(defgroup reftex-making-and-inserting-labels nil
+  "Options on how to create new labels."
+  :group 'reftex-label-support)
+(defcustom reftex-insert-label-flags '("s" "sft")
+  "Flags governing label insertion.  First flag DERIVE, second flag PROMPT.
+If DERIVE is t, RefTeX will try to derive a sensible label from context.
+A section label for example will be derived from the section heading.
+The conversion of the context to a legal label is governed by the
+specifications given in `reftex-derive-label-parameters'.
+If RefTeX fails to derive a label, it will prompt the user.
+If DERIVE is nil, the label generated will consist of the prefix and a
+unique number, like `eq:23'.
+If PROMPT is t, the user will be prompted for a label string.  The prompt will
+already contain the prefix, and (if DERIVE is t) a default label derived from
+context.  When PROMPT is nil, the default label will be inserted without
+So the combination of DERIVE and PROMPT controls label insertion.  Here is a
+table describing all four possibilities:
+ nil     nil     Insert simple label, like eq:22 or sec:13.  No query.
+ nil     t       Prompt for label.
+ t       nil     Derive a label from context and insert without query.
+ t       t       Derive a label from context and prompt for confirmation.
+Each flag may be set to t, nil, or a string of label type letters
+indicating the label types for which it should be true.  The strings work
+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
+without confirmation for everything else.
+The available label types are: s (section), f (figure), t (table), i (item),
+e (equation), n (footnote), plus any definitions in `reftex-label-alist'."
+  :group 'reftex-making-and-inserting-labels
+  :type  '(list (choice :tag "Derive label from context"
+                         (const  :tag "always" t)
+                         (const  :tag "never" nil)
+                         (string :tag "selected label types" ""))
+                (choice :tag "Prompt for label string  "
+                        :entry-format "  %b %v"
+                        (const  :tag "always" t)
+                        (const  :tag "never" nil)
+                        (string :tag "selected label types" ""))))
+(defcustom reftex-derive-label-parameters '(3 20 t 1 "-"
+         ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is"))
+  "Parameters for converting a string into a label.
+NWORDS      Number of words to use.
+MAXCHAR     Maximum number of characters in a label string.
+ILLEGAL     nil: Throw away any words containing characters illegal in labels.
+            t:   Throw away only the illegal characters, not the whole word.
+ABBREV      nil: Never abbreviate words.
+            t:   Always abbreviate words (see `reftex-abbrev-parameters').
+            not t and not nil: Abbreviate words if necessary to shorten
+                               label string below MAXCHAR.
+SEPARATOR   String separating different words in the label.
+IGNOREWORDS List of words which should not be part of labels."
+  :group 'reftex-making-and-inserting-labels
+  :type  '(list (integer :tag "Number of words            "  3)
+                (integer :tag "Maximum label length       " 20)
+                (choice  :tag "Illegal characters in words"
+                         (const :tag "throw away entire word" nil)
+                         (const :tag "throw away single chars" t))
+                (choice  :tag "Abbreviate words           "
+                         (const :tag "never" nil)
+                         (const :tag "always" t)
+                         (const :tag "when label is too long" 1))
+                (string  :tag "Separator between words    " "-")
+                (repeat  :tag "Ignore words"
+                         :entry-format "           %i %d %v"
+                         (string :tag ""))))
+(defcustom reftex-label-illegal-re "[\000-\040\177-\377\\\\#$%&~^_{}]"
+  "Regexp matching characters not legal in labels.
+For historic reasons, this character class comes *with* the [] brackets."
+  :group 'reftex-making-and-inserting-labels
+  :type '(regexp :tag "Character class"))
+(defcustom reftex-abbrev-parameters '(4 2 "^saeiou" "aeiou")
+  "Parameters for abbreviation of words.
+MIN-CHARS    Minimum number of characters remaining after abbreviation.
+MIN-KILL     Minimum number of characters to remove when abbreviating words.
+BEFORE       Character class before abbrev point in word.
+AFTER        Character class after  abbrev point in word."
+  :group 'reftex-making-and-inserting-labels
+  :type '(list
+          (integer :tag "Minimum chars per word" 4)
+          (integer :tag "Shorten by at least   " 2)
+          (string  :tag "cut before char class " "^saeiou")
+          (string  :tag "cut after  char class " "aeiou")))
+(defcustom reftex-format-label-function nil
+  "Function which produces the string to insert as a label definition.
+Normally should be nil, unless you want to do something fancy.
+The function will be called with two arguments, the LABEL and the DEFAULT
+FORMAT, which usually is `\label{%s}'.  The function should return the
+string to insert into the buffer."
+  :group 'reftex-making-and-inserting-labels
+  :type 'function)
+;; Label referencing
+(defgroup reftex-referencing-labels nil
+  "Options on how to reference labels."
+  :group 'reftex-label-support)
+  (defconst reftex-tmp
+    '((const :tag "on" t)
+      (const :tag "off" nil)
+      (string :tag "Selected label types"))))
+(defcustom reftex-label-menu-flags '(t t nil nil nil nil t nil)
+  "List of flags governing the label menu makeup.
+The flags are:
+TABLE-OF-CONTENTS  Show the labels embedded in a table of context.
+SECTION-NUMBERS    Include section numbers (like 4.1.3) in table of contents.
+COUNTERS           Show counters.  This just numbers the labels in the menu.
+NO-CONTEXT         Non-nil means do NOT show the short context.
+FOLLOW             Follow full context in other window.
+SHOW-COMMENTED     Show labels from regions which are commented out.
+MATCH-IN-TOC       Searches in label menu will also match in toc lines.
+SHOW FILES         Show Begin and end of included files.
+Each of these flags can be set to t or nil, or to a string of type letters
+indicating the label types for which it should be true.  These strings work
+like character classes in regular expressions.  Thus, setting one of the
+flags to \"sf\" makes the flag true for section and figure labels, nil
+for everything else.  Setting it to \"^ft\" makes it the other way round.
+The available label types are: s (section), f (figure), t (table), i (item),
+e (equation), n (footnote), plus any definitions in `reftex-label-alist'.
+Most options can also be switched from the label menu itself - so if you
+decide here to not have a table of contents in the label menu, you can still
+get one interactively during selection from the label menu."
+  :group 'reftex-referencing-labels
+  :type
+  `(list
+    (choice :tag "Embed in table of contents      " ,@reftex-tmp)
+    (choice :tag "Show section numbers            " ,@reftex-tmp)
+    (choice :tag "Show individual counters        " ,@reftex-tmp)
+    (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 "Searches match in toc lines     " ,@reftex-tmp)
+    (choice :tag "Show begin/end of included files" ,@reftex-tmp)))
+(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 
+`\\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
+the label types for which it should be true."
+  :group  'reftex-referencing-labels
+  :type `(choice :tag "\\vref is default macro" ,@reftex-tmp))
+(defcustom reftex-level-indent 2
+  "*Number of spaces to be used for indentation per section level."
+  :group 'reftex-referencing-labels
+  :type '(integer))
+(defcustom reftex-refontify-context 1
+  "*Non-nil means, re-fontify the context in the label menu with font-lock.
+This slightly slows down the creation of the label menu.  It is only necessary
+when you definitely want the context fontified.
+This option may have 3 different values:
+nil  Never refontify.
+t    Always refontify.
+1    Refontify when absolutely necessary, e.g. when with the x-symbol package.
+The option is ignored when `reftex-use-fonts' is nil."
+  :group 'reftex-referencing-labels
+  :type '(choice
+          (const :tag "Never" nil)
+          (const :tag "Always" t)
+          (const :tag "When necessary" 1)))
+(defcustom reftex-guess-label-type t
+  "*Non-nil means, `reftex-reference' will try to guess the label type.
+To do that, RefTeX will look at the word before the cursor and compare it with
+the words given in `reftex-label-alist'.  When it finds a match, RefTeX will
+immediately offer the correct label menu - otherwise it will prompt you for
+a label type.  If you set this variable to nil, RefTeX will always prompt."
+  :group 'reftex-referencing-labels
+  :type '(boolean))
+(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 
+already be specified in `reftex-label-alist'.
+The function will be called with two arguments, the LABEL and the DEFAULT
+FORMAT, which normally is `~\ref{%s}'.  The function should return the
+string to insert into the buffer."
+  :group 'reftex-referencing-labels
+  :type 'function)
+;; BibteX citation configuration ----------------------------------------
+(defgroup reftex-citation-support nil
+  "Support for referencing bibliographic data with BibTeX."
+  :group 'reftex)
+(defcustom reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB")
+  "*List of env vars which might contain the path to BibTeX database files."
+  :group 'reftex-citation-support
+  :set 'reftex-set-dirty
+  :type '(repeat (string :tag "Environment variable")))
+(defcustom reftex-bibfile-ignore-list nil
+  "*List of files in \\bibliography{..} RefTeX should *not* parse.
+The file names have to be in the exact same form as in the bibliography
+macro - i.e. without the `.bib' extension.
+Intended for files which contain only `@string' macro definitions and the
+like, which are ignored by RefTeX anyway."
+  :group 'reftex-citation-support
+  :set 'reftex-set-dirty
+  :type '(repeat (string :tag "File name")))
+(defcustom reftex-default-bibliography nil
+  "*List of BibTeX database file which should be used if none are specified.
+When `reftex-citation' is called from a document which has neither a
+`\bibliography{..}' statement nor a `thebibliography' environment,
+RefTeX will scan these files instead.  Intended for using
+`reftex-citation' in non-LaTeX files."
+  :group 'reftex-citation-support
+  :type '(repeat (file)))
+(defcustom reftex-sort-bibtex-matches 'reverse-year
+  "*Sorting of the entries found in BibTeX databases by reftex-citation.
+Possible values:
+nil            Do not sort entries.
+'author        Sort entries by author name.
+'year          Sort entries by increasing year.
+'reverse-year  Sort entries by decreasing year."
+  :group 'reftex-citation-support
+  :type '(choice (const :tag "not" nil)
+                 (const :tag "by author" author)
+                 (const :tag "by year"   year)
+                 (const :tag "by year, reversed" reverse-year)))
+(defcustom reftex-cite-format 'default
+  "*The format of citations to be inserted into the buffer.
+It can be a string or an alist.  In the simplest case this is just
+the string \"\\cite{%l}\", which is also the default.  See the
+definition of `reftex-cite-format-builtin' for more complex examples.
+If `reftex-cite-format' is a string, it will be used as the format.
+In the format, the following percent escapes will be expanded.
+%l   The BibTeX label of the citation.
+%a   List of author names, see also `reftex-cite-punctuation.
+%2a  Like %a, but abbreviate more than 2 authors like Jones et al.
+%A   First author name only.
+%e   Works like %a, but on list of editor names. (%2e and %E work a well)
+It is also possible to access all other BibTeX database fields:
+%b booktitle     %c chapter        %d edition    %h howpublished
+%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
+Usually, only %l is needed.  Try, however, (setq reftex-comment-citations t).
+Beware that all this only works when using BibTeX database files.  When
+citations are made from the \\bibitems in an explicit thebibliography
+environment, only %l is available.
+If `reftex-cite-format' is an alist of characters and strings, the user
+will be prompted for a character to select one of the possible format
+  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 (see `reftex-cite-format-builtin').  E.g.:
+(setq reftex-cite-format 'harvard)"
+  :group 'reftex-citation-support
+  :type
+  `(choice
+    :format "%{%t%}: \n%[Value Menu%] %v"
+    (radio :tag "Symbolic Builtins"
+           :indent 4
+           :value default
+           ,@(mapcar
+              (function
+               (lambda (x)
+                 (list 'const ':tag (concat (symbol-name (nth 0 x))
+                                            ": " (nth 1 x))
+                       (nth 0 x))))
+              reftex-cite-format-builtin))
+    (string :tag "format string" "\\cite{%l}")
+    (repeat :tag "key-ed format strings"
+            :value ((?\r . "\\cite{%l}")
+                    (?t  . "\\cite{%l}") (?p . "\\cite{%l}"))
+            (cons (character :tag "Key character" ?\r)
+                  (string    :tag "Format string" "")))))
+(defcustom reftex-comment-citations nil
+  "*Non-nil means add a comment for each citation describing the full entry.
+The comment is formatted according to `reftex-cite-comment-format'."
+  :group 'reftex-citation-support
+  :type '(boolean))
+(defcustom reftex-cite-comment-format
+  "%% %2a %y, %j %v, %P, %e: %b, %u, %s %<\n"
+  "Citation format used for commented citations.  Must NOT contain %l."
+  :group 'reftex-citation-support
+  :type '(string))
+(defcustom reftex-cite-punctuation '(", " " \\& " " {\\it et al.}")
+  "Punctuation for formatting of name lists in citations.
+This is a list of 3 strings.
+1. normal names separator, like \", \"     in Jones, Brown and Miller
+2. final names separator,  like \" and \"  in Jones, Brown and Miller
+3. The \"et al\" string,   like \" {\\it et al.}\" in Jones {\\it et al.}"
+  :group 'reftex-citation-support
+  :type '(list
+          (string :tag "Separator for names            ")
+          (string :tag "Separator for last name in list")
+          (string :tag "string used as et al.          ")))
+(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 
+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
+should return the string to insert into the buffer."
+  :group 'reftex-citation-support
+  :type 'function)
+;; Table of contents configuration --------------------------------------
+(defgroup reftex-table-of-contents-browser nil
+  "A multifile table of contents browser."
+  :group 'reftex)
+(defcustom reftex-toc-follow-mode nil
+  "*Non-nil means, point in *toc* buffer will cause other window to follow.
+The other window will show the corresponding part of the document.
+This flag can be toggled from within the *toc* buffer with the `f' key."
+  :group 'reftex-table-of-contents-browser
+  :type '(boolean))
+;; Tuning the parser ----------------------------------------------------
+(defgroup reftex-optimizations-for-large-documents nil
+  "Configuration of parser speed and memory usage."
+  :group 'reftex)
+(defcustom reftex-keep-temporary-buffers 1
+  "*Non-nil means, keep buffers created for parsing and lookup.
+RefTeX sometimes needs to visit files related to the current document.
+We distinguish files visited for
+PARSING: Parts of a multifile document loaded when (re)-parsing the document.
+LOOKUP:  BibTeX database files and TeX files loaded to find a reference,
+         to display label context, etc.
+The created buffers can be kept for later use, or be thrown away immediately
+after use, depending on the value of this variable:
+nil  Throw away as much as possible.
+t    Keep everything.
+1    Throw away buffers created for parsing, but keep the ones created
+     for lookup.
+If a buffer is to be kept, the file is visited normally (which is potentially
+slow but will happen only once).
+If a buffer is to be thrown away, the initialization of the buffer depends
+upon the variable `reftex-initialize-temporary-buffers'."
+  :group 'reftex-miscellaneous-configurations
+  :type '(choice
+          (const :tag "Throw away everything" nil)
+          (const :tag "Keep everything" t)
+          (const :tag "Keep lookup buffers only" 1)))
+(defcustom reftex-initialize-temporary-buffers nil
+  "*Non-nil means do initializations even when visiting file temporarily.
+When nil, RefTeX may turn off find-file hooks and other stuff to briefly
+visit a file.
+When t, the full default initializations are done (find-file-hook etc.).
+Instead of t or nil, this variable may also be a list of hook functions to
+do a minimal initialization."
+  :group 'reftex-miscellaneous-configurations
+  :type '(choice
+          (const :tag "Read files literally" nil)
+          (const :tag "Fully initialize buffers" t)
+          (repeat :tag "Hook functions" :value (nil)
+           (function-item))))
+(defcustom reftex-no-include-regexps '("\\.pstex_t\\'") ; default for x-symbol
+  "*List of regular expressions to exclude certain input files from parsing.
+If the name of a file included via \\include or \\input is matched by any
+of the regular expressions in this list, that file is not parsed by RefTeX."
+  :group 'reftex-optimizations-for-large-documents
+  :type '(repeat (regexp)))
+(defcustom reftex-enable-partial-scans nil
+  "*Non-nil means, re-parse only 1 file when asked to re-parse.
+Re-parsing is normally requested with a `C-u' prefix to many RefTeX commands,
+or with the `r' key in menus.  When this option is t in a multifile document,
+we will only parse the current buffer, or the file associated with the label
+or section heading near point in a menu.  Requesting re-parsing of an entire
+multifile document then requires a `C-u C-u' prefix or the capital `R' key
+in menus."
+  :group 'reftex-optimizations-for-large-documents
+  :type 'boolean)
+(defcustom reftex-allow-automatic-rescan t
+  "*Non-nil means, RefTeX may rescan the document when this seems necessary.
+Currently this applies only to rescanning after label insertion, when
+the new label cannot be inserted correctly into the internal label
+  :group 'reftex-optimizations-for-large-documents
+  :type 'boolean)
+(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, 
+- accessing the parsing information for the first time in an editing session
+  will read that file (if available) instead of parsing the document.
+- each time (part of) the document is rescanned, a new version of the file
+  is written."
+  :group 'reftex-optimizations-for-large-documents
+  :type 'boolean)
+(defcustom reftex-use-multiple-selection-buffers nil
+  "*Non-nil means use a separate selection buffer for each label type.
+These buffers are kept from one selection to the next and need not to be
+created for each use - so the menu generally comes up faster.  The
+selection buffers will be erased (and therefore updated) automatically
+when new labels in its category are added.  See the variable
+  :group 'reftex-optimizations-for-large-documents
+  :type 'boolean)
+(defcustom reftex-auto-update-selection-buffers t
+  "*Non-nil means, selection buffers will be updated automatically.
+When a new label is defined with `reftex-label', all selection buffers
+associated with that label category are emptied, in order to force an
+update upon next use.  When nil, the buffers are left alone and have to be
+updated by hand, with the `g' key from the label selection process.
+The value of this variable will only have any effect when
+`reftex-use-multiple-selection-buffers' is non-nil."
+  :group 'reftex-optimizations-for-large-documents
+  :type 'boolean)
+;; Miscellaneous configurations -----------------------------------------
+(defgroup reftex-miscellaneous-configurations nil
+  "Collection of further configurations."
+  :group 'reftex)
+(defcustom reftex-extra-bindings nil
+  "Non-nil means, make additional key bindings on startup.
+These extra bindings are located in the users `C-c letter' map."
+  :group 'reftex-miscellaneous-configurations
+  :type '(boolean))
+(defcustom reftex-plug-into-AUCTeX nil
+  "*Plug-in flags for AUCTeX interface.
+This variable is a list of 4 boolean flags.  When a flag is non-nil, it
+  Flag 1:  use `reftex-label'     as `LaTeX-label-function'.
+  Flag 2:  use `reftex-arg-label' as `TeX-arg-label'
+  Flag 3:  use `reftex-arg-ref'   as `TeX-arg-ref'
+  Flag 4:  use `reftex-arg-cite'  as `TeX-arg-cite'
+You may also set the variable itself to t or nil in order to turn all
+plug-ins on or off, respectively.
+\\<LaTeX-mode-map>`LaTeX-label-function' is the function used for label insertion when you
+enter a new environment in AUCTeX with \\[LaTeX-environment].
+The `TeX-arg-label' etc. functions are for entering macro arguments during
+macro insertion with \\[TeX-insert-macro].
+See the AUCTeX documentation for more information.
+RefTeX uses `fset' to take over the function calls.  Changing the variable
+may require a restart of Emacs in order to become effective."
+  :group 'reftex-miscellaneous-configurations
+  :type '(choice (const :tag "No plug-ins" nil)
+                 (const :tag "All possible plug-ins" t)
+                 (list
+                  :tag "Individual choice"
+                  :value (nil nil nil nil)
+                  (boolean :tag "Use reftex-label     as LaTeX-label-function")
+                  (boolean :tag "Use reftex-arg-label as TeX-arg-label       ")
+                  (boolean :tag "Use reftex-arg-ref   as TeX-arg-ref         ")
+                  (boolean :tag "Use reftex-arg-cite  as TeX-arg-cite        ")
+                  )))
+(defcustom reftex-use-fonts t
+  "*Non-nil means, use fonts in label menu and on-the-fly help.
+Font-lock must be loaded as well to actually get fontified display."
+  :group 'reftex-miscellaneous-configurations
+  :type '(boolean))
+(defcustom reftex-auto-show-entry 'copy
+  "*Non-nil means, do something when context in other window is hidden.
+Some modes like `outline-mode' or `folding-mode' hide parts of buffers.
+When RefTeX is asked to show context for a label definition, and the context
+is invisible, it can unhide that section permanently (value t), or copy the
+context to a temporary buffer (value 'copy)."
+  :group 'reftex-miscellaneous-configurations
+  :type '(radio :value copy
+                :indent 4
+          (const :tag "Do nothing" nil)
+          (const :tag "Unhide section permanently" t)
+          (const :tag "Copy context to show" copy)))
+(defcustom reftex-revisit-to-follow t
+  "*Non-nil means, follow-mode will revisit files if necessary.
+When nil, follow-mode will be suspended for stuff in unvisited files."
+  :group 'reftex-miscellaneous-configurations
+  :type '(boolean))
+(defcustom reftex-load-hook nil
+  "Hook which is being run when loading reftex.el."
+  :group 'reftex-miscellaneous-configurations
+  :type 'hook)
+(defcustom reftex-mode-hook nil
+  "Hook which is being run when turning on RefTeX mode."
+  :group 'reftex-miscellaneous-configurations
+  :type 'hook)
+;;; End of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;; Define the formal stuff for a minor mode named RefTeX.
+(defconst reftex-version "RefTeX version 3.17"
+  "Version string for RefTeX.")
+(defvar reftex-mode nil
+  "Determines if RefTeX minor mode is active.")
+(make-variable-buffer-local 'reftex-mode)
+(defvar reftex-mode-map (make-sparse-keymap)
+  "Keymap for RefTeX minor mode.")
+(defvar reftex-mode-menu nil)
+(defun turn-on-reftex ()
+  "Turn on RefTeX minor mode."
+  (reftex-mode t))
+(defun reftex-mode (&optional arg)
+  "Minor mode with distinct support for \\label, \\ref and \\cite in LaTeX.
+Labels can be created with `\\[reftex-label]' and referenced with `\\[reftex-reference]'.
+When referencing, you get a menu with all labels of a given type and
+context of the label definition.  The selected label is inserted as a
+\\ref macro.
+Citations can be made with `\\[reftex-citation]' which will use a regular expression
+to pull out a *formatted* list of articles from your BibTeX
+database.  The selected citation is inserted as a \\cite macro.
+A Table of Contents of the entire (multifile) document with browsing
+capabilities is available with `\\[reftex-toc]'.
+Most command have help available on the fly.  This help is accessed by
+pressing `?' to any prompt mentioning this feature.
+Extensive documentation about RefTeX is in the file header of `reftex.el'.
+You can view this information with `\\[reftex-show-commentary]'.
+Under X, these and other functions will also be available as `Ref' menu
+on the menu bar.
+  (interactive "P")
+  (setq reftex-mode (not (or (and (null arg) reftex-mode)
+                             (<= (prefix-numeric-value arg) 0))))
+  ; Add or remove the menu, and run the hook
+  (if reftex-mode
+      (progn
+        (easy-menu-add reftex-mode-menu)
+        (reftex-plug-into-AUCTeX)
+        (run-hooks 'reftex-mode-hook))
+    (easy-menu-remove reftex-mode-menu)))
+(or (assoc 'reftex-mode minor-mode-alist)
+    (push '(reftex-mode " Ref") minor-mode-alist))
+(or (assoc 'reftex-mode minor-mode-map-alist)
+    (push (cons 'reftex-mode reftex-mode-map) minor-mode-map-alist))
+;;; ===========================================================================
+;;; Silence warnings about variables in other packages.
+(defvar TeX-master)
+(defvar LaTeX-label-function)
+(defvar tex-main-file)
+(defvar outline-minor-mode)
+(defvar font-lock-fontify-region-function)
+(defvar font-lock-syntactic-keywords)
+;;; ===========================================================================
+;;; Interfaces for other packages
+;;; -----------------------------
+;;; AUCTeX
+;;; ------
+(defun reftex-arg-label (optional &optional prompt definition)
+  "Use `reftex-label' to create label.  Insert it with `TeX-argument-insert'.
+This function is intended for AUCTeX macro support."
+  (let ((label (reftex-label nil t)))
+    (if (and definition (not (string-equal "" label)))
+        (LaTeX-add-labels label))
+    (TeX-argument-insert label optional optional)))
+(defun reftex-arg-ref (optional &optional prompt definition)
+  "Use `reftex-reference' to select label.  Insert with `TeX-argument-insert'.
+This function is intended for AUCTeX macro support."
+  (let ((label (reftex-reference nil t)))
+    (if (and definition (not (string-equal "" label)))
+        (LaTeX-add-labels label))
+    (TeX-argument-insert label optional optional)))
+(defun reftex-arg-cite (optional &optional prompt definition)
+  "Use reftex-citation to select a key.  Insert with `TeX-argument-insert'.
+This function is intended for AUCTeX macro support."
+  (let ((key (reftex-citation t)))
+    (TeX-argument-insert (or key "") optional optional)))
+(defun reftex-plug-into-AUCTeX ()
+  ;; Replace AUCTeX functions with RefTeX functions.
+  ;; Which functions are replaced is controlled by the variable
+  ;; `reftex-plug-into-AUCTeX'.
+  (let ((flags
+         (cond ((eq reftex-plug-into-AUCTeX t) '(t t t t))
+               ((eq reftex-plug-into-AUCTeX nil) '(nil nil nil nil))
+               (t reftex-plug-into-AUCTeX))))
+    (and (nth 0 flags)
+         (boundp 'LaTeX-label-function)
+         (setq LaTeX-label-function 'reftex-label))
+    (and (nth 1 flags)
+         (fboundp 'TeX-arg-label)
+         (fset 'TeX-arg-label 'reftex-arg-label))
+    (and (nth 2 flags)
+         (fboundp 'TeX-arg-ref)
+         (fset 'TeX-arg-ref 'reftex-arg-ref))
+    (and (nth 3 flags)
+         (fboundp 'TeX-arg-cite)
+         (fset 'TeX-arg-cite 'reftex-arg-cite))))
+(defvar reftex-label-alist-external-add-ons nil
+  "List of label alist entries added with reftex-add-to-label-alist.")
+(defun reftex-add-to-label-alist (entry-list)
+  "Add label environment descriptions to `reftex-label-alist-external-add-ons'.
+The format of ENTRY-LIST is exactly like `reftex-label-alist'.  See there
+for details.
+This function makes it possible to support RefTeX from AUCTeX style files.
+The entries in ENTRY-LIST will be processed after the user settings in
+`reftex-label-alist', and before the defaults (specified in
+`reftex-default-label-alist-entries').  Any changes made to
+`reftex-label-alist-external-add-ons' will raise a flag to the effect that a
+mode reset is done on the next occasion."
+  (let (entry)
+    (while entry-list
+      (setq entry (car entry-list)
+            entry-list (cdr entry-list))
+      (unless (member entry reftex-label-alist-external-add-ons)
+        (setq reftex-tables-dirty t)
+        (push entry reftex-label-alist-external-add-ons)))))
+;;; ===========================================================================
+;;; Multifile support
+;;; Technical notes: Multifile works as follows: We keep just one list
+;;; of labels for each master file - this can save a lot of memory.
+;;; `reftex-master-index-list' is an alist which connects the true file name
+;;; of each master file with the symbols holding the information on that
+;;; document.  Each buffer has local variables which point to these symbols.
+;; List of variables which handle the multifile stuff.
+;; This list is used to tie, untie, and reset these symbols.
+(defconst reftex-multifile-symbols
+  '(reftex-docstruct-symbol))
+;; Alist connecting master file names with the corresponding lisp symbols.
+(defvar reftex-master-index-list nil)
+;; Last index used for a master file.
+(defvar reftex-multifile-index 0)
+;; Variable holding the symbol with the label list of the document.
+(defvar reftex-docstruct-symbol nil)
+(make-variable-buffer-local 'reftex-docstruct-symbol)
+(defun reftex-next-multifile-index ()
+  ;; Return the next free index for multifile symbols.
+  (incf reftex-multifile-index))
+(defun reftex-tie-multifile-symbols ()
+  ;; Tie the buffer-local symbols to globals connected with the master file.
+  ;; If the symbols for the current master file do not exist, they are created.
+  (let* ((master (file-truename (reftex-TeX-master-file)))
+         (index (assoc master reftex-master-index-list))
+         (symlist reftex-multifile-symbols)
+         (symbol nil)
+         (symname nil)
+         (newflag nil))
+    ;; Find the correct index.
+    (if index
+        ;; symbols do exist
+        (setq index (cdr index))
+      ;; Get a new index and add info to the alist.
+      (setq index (reftex-next-multifile-index)
+            newflag t)
+      (push (cons master index) reftex-master-index-list))
+    ;; Get/create symbols and tie them.
+    (while symlist
+      (setq symbol (car symlist)
+            symlist (cdr symlist)
+            symname (symbol-name symbol))
+      (set symbol (intern (concat symname "-" (int-to-string index))))
+      (put (symbol-value symbol) ':master-index index)
+      ;; Initialize if new symbols.
+      (if newflag (set (symbol-value symbol) nil)))
+    ;; Return t if the symbols did already exist, nil when we've made them.
+    (not newflag)))
+(defun reftex-untie-multifile-symbols ()
+  ;; Remove ties from multifile symbols, so that next use makes new ones.
+  (let ((symlist reftex-multifile-symbols)
+        (symbol nil))
+    (while symlist
+      (setq symbol  (car symlist)
+            symlist (cdr symlist))
+      (set symbol nil))))
+(defun reftex-TeX-master-file ()
+  ;; Return the name of the master file associated with the current buffer.
+  ;; When AUCTeX is loaded, we will use it's more sophisticated method.
+  ;; We also support the default TeX and LaTeX modes by checking for a
+  ;; variable tex-main-file.
+  (let
+      ((master
+        (cond
+         ((fboundp 'TeX-master-file) ; AUCTeX is loaded.  Use its mechanism.
+          (TeX-master-file t))
+         ((boundp 'TeX-master)       ; The variable is defined - lets use it.
+          (cond
+           ((eq TeX-master t)
+            (buffer-file-name))
+           ((eq TeX-master 'shared)
+            (setq TeX-master (read-file-name "Master file: "
+                                             nil nil t nil)))
+           (TeX-master)
+           (t
+            (setq TeX-master (read-file-name "Master file: "
+                                             nil nil t nil)))))
+         ((boundp 'tex-main-file)
+          ;; This is the variable from the default TeX modes.
+          (cond
+           ((stringp tex-main-file)
+            ;; ok, this must be it
+            tex-main-file)
+           (t
+            ;; In this case, the buffer is its own master.
+            (buffer-file-name))))
+         (t
+          ;; Know nothing about master file.  Assume this is a master file.
+          (buffer-file-name)))))
+    (cond
+     ((null master)
+      (error "Need a filename for this buffer.  Please save it first."))
+     ((or (file-exists-p master)
+          (reftex-get-buffer-visiting master))
+      ;; We either see the file, or have a buffer on it.  OK.
+      )
+     ((or (file-exists-p (concat master ".tex"))
+          (reftex-get-buffer-visiting (concat master ".tex")))
+      ;; Ahh, an extra .tex was missing...
+      (setq master (concat master ".tex")))
+     (t
+      ;; Something is wrong here.  Throw an exception.
+      (buffer-file-name)))
+;      (error "No such master file %s" master)))
+    (expand-file-name master)))
+(defun reftex-parse-one ()
+  "Re-parse this file."
+  (interactive)
+  (let ((reftex-enable-partial-scans t))
+    (reftex-access-scan-info '(4))))
+(defun reftex-parse-all ()
+  "Re-parse entire document."
+  (interactive)
+  (reftex-access-scan-info '(16)))
+(defun reftex-all-document-files (&optional relative)
+  ;; Return a list of all files belonging to the current document.
+  ;; When RELATIVE is non-nil, give file names relative to directory
+  ;; of master file.
+  (let* ((all (symbol-value reftex-docstruct-symbol))
+         (master-dir (file-name-directory (reftex-TeX-master-file)))
+         (re (concat "\\`" (regexp-quote master-dir)))
+        file-list tmp file)
+    (while (setq tmp (assoc 'bof all))
+      (setq file (nth 1 tmp)
+            all (cdr (memq tmp all)))
+      (and relative
+           (string-match re file)
+           (setq file (substring file (match-end 0))))
+      (push file file-list))
+    (nreverse file-list)))
+(defun reftex-create-tags-file ()
+  "Create TAGS file by running `etags' on the current document.
+The TAGS file is also immediately visited with `visit-tags-table'."
+  (interactive)
+  (reftex-access-scan-info current-prefix-arg)
+  (let* ((master (reftex-TeX-master-file))
+         (files  (reftex-all-document-files))
+         (cmd    (format "etags %s" (mapconcat 'identity files " "))))
+    (save-excursion
+      (set-buffer (reftex-get-buffer-visiting master))
+      (message "Running etags to create TAGS file...")
+      (shell-command cmd)
+      (visit-tags-table "TAGS"))))
+;; History of grep commands.
+(defvar reftex-grep-history nil)
+(defvar reftex-grep-command "grep -n "
+  "Last grep command used in \\[reftex-grep-document]; default for next grep.")
+(defun reftex-grep-document (grep-cmd)
+  "Run grep query through all files related to this document.
+With prefix arg, force to rescan document.
+This works also without an active TAGS table."
+  (interactive
+   (list (read-from-minibuffer "Run grep on document (like this): "
+                               reftex-grep-command nil nil
+                               'reftex-grep-history)))
+  (reftex-access-scan-info current-prefix-arg)
+  (let* ((files  (reftex-all-document-files t))
+         (cmd    (format
+                  "%s %s" grep-cmd
+                  (mapconcat 'identity files " "))))
+    (grep cmd)))
+(defun reftex-search-document (&optional regexp)
+  "Regexp search through all files of the current TeX document.
+Starts always in the master file.  Stops when a match is found.
+To continue searching for next match, use command \\[tags-loop-continue].
+This works also without an active TAGS table."
+  (interactive)
+  (let ((default (reftex-this-word)))
+    (unless regexp
+      (setq regexp (read-string (format "Search regexp in document [%s]: "
+                                        default))))
+    (if (string= regexp "") (setq regexp (regexp-quote default)))
+    (reftex-access-scan-info current-prefix-arg)
+    (tags-search regexp (list 'reftex-all-document-files))))
+(defun reftex-query-replace-document (&optional from to delimited)
+  "Run a query-replace-regexp of FROM with TO over the entire TeX document.
+Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
+If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
+with the command \\[tags-loop-continue].
+This works also without an active TAGS table."
+  (interactive)
+  (let ((default (reftex-this-word)))
+    (unless from
+      (setq from (read-string (format "Replace regexp in document [%s]: "
+                                      default)))
+      (if (string= from "") (setq from (regexp-quote default))))
+    (unless to
+      (setq to (read-string (format "Replace regexp %s with: " from))))
+    (reftex-access-scan-info current-prefix-arg)
+    (tags-query-replace from to (or delimited current-prefix-arg)
+                        (list 'reftex-all-document-files))))
+(defun reftex-change-label (&optional from to)
+  "Query replace FROM with TO in all \\label and \\ref commands.
+Works on the entire multifile document.
+If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
+with the command \\[tags-loop-continue].
+This works also without an active TAGS table."
+  (interactive)
+  (let ((default (reftex-this-word "-a-zA-Z0-9_*.:")))
+    (unless from
+      (setq from (read-string (format "Replace label globally [%s]: "
+                                      default))))
+    (if (string= from "") (setq from default))
+    (unless to
+      (setq to (read-string (format "Replace label %s with: "
+                                    from))))
+    (reftex-query-replace-document
+     (concat "\\\\\\(label\\|[a-z]*ref\\){" (regexp-quote from) "}")
+     (format "\\\\\\1{%s}" to))))
+(defun reftex-save-all-document-buffers ()
+  "Save all documents associated with the current document.
+The function is useful after a global action like replacing or renumbering
+  (interactive)
+  (let ((files (reftex-all-document-files))
+	file buffer)
+    (save-excursion
+      (while (setq file (pop files))
+	(setq buffer (reftex-get-buffer-visiting file))
+	(when buffer
+	  (set-buffer buffer)
+	  (save-buffer))))))
+;;; ===========================================================================
+;;; Functions to create and reference automatic labels.
+;; The following constants are derived from `reftex-label-alist'.
+;; Prompt used for label type queries directed to the user.
+(defconst reftex-type-query-prompt nil)
+;; Help string for label type queries.
+(defconst reftex-type-query-help nil)
+;; Alist relating label type to reference format.
+(defconst reftex-typekey-to-format-alist nil)
+;; Alist relating label type to label affix.
+(defconst reftex-typekey-to-prefix-alist nil)
+;; Alist relating environments or macros to label type and context regexp.
+(defconst reftex-env-or-mac-alist nil)
+;; List of macros carrying a label.
+(defconst reftex-label-mac-list nil)
+;; List of environments carrying a label.
+(defconst reftex-label-env-list nil)
+;; List of all typekey letters in use.
+(defconst reftex-typekey-list nil)
+;; Alist relating magic words to a label type.
+(defconst reftex-words-to-typekey-alist nil)
+;; The last list-of-labels entry used in a reference.
+(defvar reftex-last-used-reference (list nil nil nil nil))
+;; The regular expression used to abbreviate words.
+(defconst reftex-abbrev-regexp
+  (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)) ?.)))
+;; Global variables used for communication between functions.
+(defvar reftex-default-context-position nil)
+(defvar reftex-location-start nil)
+(defvar reftex-call-back-to-this-buffer nil)
+(defvar reftex-active-toc nil)
+(defvar reftex-tex-path nil)
+(defvar reftex-bib-path nil)
+(defvar reftex-prefix)
+;; List of buffers created temporarily for lookup, which should be killed.
+(defvar reftex-buffers-to-kill nil)
+;; Regexp to find section statements.  Computed from reftex-section-levels.
+(defvar reftex-section-regexp nil)
+(defvar reftex-section-or-include-regexp nil)
+(defvar reftex-everything-regexp nil)
+(defvar reftex-find-label-regexp-format nil)
+(defvar reftex-find-label-regexp-format2 nil)
+;; The parser functions ----------------------------------
+(defvar reftex-memory nil
+  "Memorizes old variable values to indicate changes in these variables.")
+(defun reftex-access-scan-info (&optional rescan file)
+  ;; Access the scanning info.  When the multifile symbols are not yet tied,
+  ;; tie them.  When they are empty or RESCAN is non-nil, scan the document.
+  ;; When FILE is non-nil, parse only from that file.
+  ;; Reset the mode if we had changes to important variables.
+  (when (or reftex-tables-dirty
+	    (not (eq reftex-label-alist (nth 0 reftex-memory)))
+	    (not (eq reftex-label-alist-external-add-ons
+		     (nth 1 reftex-memory)))
+	    (not (eq reftex-default-label-alist-entries
+		     (nth 2 reftex-memory))))
+    (reftex-reset-mode))
+  (if (eq reftex-docstruct-symbol nil)
+      ;; Symbols are not yet tied: Tie them.
+      (reftex-tie-multifile-symbols))
+  (when (or (null (symbol-value reftex-docstruct-symbol))
+	    (member rescan '(t 1 (4) (16))))
+    ;; The docstruct will change: Remove selection buffers.
+    (save-excursion
+      (reftex-erase-all-selection-buffers)))
+  (if (and (null (symbol-value reftex-docstruct-symbol))
+           reftex-save-parse-info)
+      ;; Try to read the stuff from a file
+      (reftex-access-parse-file 'read))
+  (cond
+   ((not (symbol-value reftex-docstruct-symbol))
+    (reftex-do-parse 1 file))
+   ((member rescan '(t 1 (4) (16)))
+    (reftex-do-parse rescan file))))
+(defun reftex-do-parse (rescan &optional file)
+  ;; Do a rescan.  When allowed, do only a partial scan from FILE.
+  ;; Normalize the rescan argument
+  (setq rescan (cond ((eq rescan t) t)
+                     ((eq rescan 1) 1)
+                     ((equal rescan '(4)) t)
+                     ((equal rescan '(16)) 1)
+                     (t 1)))
+  ;; Partial scans only when allowed
+  (unless reftex-enable-partial-scans
+    (setq rescan 1))
+  ;; Do the scanning.
+  (let* ((old-list (symbol-value reftex-docstruct-symbol))
+         (master (reftex-TeX-master-file))
+	 (master-dir (file-name-as-directory (file-name-directory master)))
+         (file (or file (buffer-file-name)))
+         from-file appendix docstruct tmp)
+    ;; Make sure replacement is really an option here
+    (when (and (eq rescan t)
+               (not (and (member (list 'bof file) old-list)
+                         (member (list 'eof file) old-list))))
+      (message "Scanning whole document (no file section %s)" file)
+      (setq rescan 1))
+    (when (string= file master)
+      (message "Scanning whole document (%s is master)" file)
+      (setq rescan 1))
+    ;; From which file do we start?
+    (setq from-file
+          (cond ((eq rescan t) (or file master))
+                ((eq rescan 1) master)
+                (t (error "horrible!!"))))
+    ;; 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))
+    (reftex-init-section-numbers reftex-active-toc appendix)
+    (if (eq rescan 1)
+        (message "Scanning entire document...")
+      (message "Scanning document from %s..." from-file))
+    (save-window-excursion
+      (save-excursion
+        (unwind-protect
+            (setq docstruct
+                  (reftex-parse-from-file
+                   from-file docstruct master-dir))
+          (reftex-kill-temporary-buffers))))
+    (message "Scanning document... done")
+    ;; Turn the list around.
+    (setq docstruct (nreverse docstruct))
+    ;; Set or insert
+    (setq docstruct (reftex-replace-label-list-segment
+                     old-list docstruct (eq rescan 1)))
+    ;; Add all missing information
+    (unless (assq 'label-numbers docstruct)
+      (push (cons 'label-numbers nil) docstruct))
+    (unless (assq 'master-dir docstruct)
+      (push (cons 'master-dir master-dir) docstruct))
+    (let* ((bof1 (memq (assq 'bof docstruct) docstruct))
+           (bof2 (assq 'bof (cdr bof1)))
+           (is-multi (not (not (and bof1 bof2))))
+           (entry (or (assq 'is-multi docstruct)
+                      (car (push (list 'is-multi is-multi) docstruct)))))
+      (setcdr entry (cons is-multi nil)))
+    (unless (assq 'xr docstruct)
+      (let* ((allxr (reftex-all-assq 'xr-doc docstruct))
+	     (alist (mapcar
+		     (function
+		      (lambda (x) 
+			(if (setq tmp (reftex-find-tex-file (nth 2 x)
+							    master-dir))
+			    (cons (nth 1 x) tmp)
+			  (message "Can't find external document %s"
+				   (nth 2 x))
+			  nil)))
+		    allxr))
+	     (alist (delete nil alist))
+	     (allprefix (delete 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)
+    ;; Save the parsing information into a file?
+    (if reftex-save-parse-info
+        (reftex-access-parse-file 'write))))
+(defun reftex-is-multi ()
+  ;; Tell if this is a multifile document.  When not sure, say yes.
+  (let ((entry (assq 'is-multi (symbol-value reftex-docstruct-symbol))))
+    (if entry
+        (nth 1 entry)
+      t)))
+(defun reftex-parse-from-file (file docstruct master-dir)
+  ;; Scan the buffer for labels and save them in a list.
+  (let ((regexp reftex-everything-regexp)
+        (bound 0)
+        file-found tmp include-file
+        (level 1)
+        (highest-level 100)
+        toc-entry next-buf)
+    (catch 'exit
+      (setq file-found (reftex-find-tex-file file master-dir))
+      (unless file-found
+        (push (list 'file-error file) docstruct)
+        (throw 'exit nil))
+      (save-excursion
+        (message "Scanning file %s" file)
+        (set-buffer
+         (setq next-buf
+               (reftex-get-file-buffer-force
+                file-found
+                (not (eq t reftex-keep-temporary-buffers)))))
+        ;; Begin of file mark
+        (setq file (buffer-file-name))
+        (push (list 'bof file) docstruct)
+        (save-excursion
+          (save-restriction
+            (widen)
+            (goto-char 1)
+            (while (re-search-forward regexp nil t)
+              (cond
+               ((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))
+                ;; Insert in List
+                (setq toc-entry (reftex-section-info file))
+                (setq level (nth 5 toc-entry))
+                (setq highest-level (min highest-level level))
+                (if (= level highest-level)
+                    (message
+                     "Scanning %s %s ..."
+                     (car (nth level reftex-section-levels))
+                     (nth 6 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))
+		(if (delq nil (mapcar 
+			       (lambda (x) (string-match x include-file))
+			       reftex-no-include-regexps))
+		    (progn
+		      ;; Ignore the file
+		      (push (list 'bof include-file) docstruct)
+		      (push (list 'eof include-file) docstruct))
+		  ;; 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 10)
+                ;; A macro with label
+                (save-excursion
+                  (let* ((mac (reftex-match-string 10))
+			 (label (progn (goto-char (match-end 10))
+				       (save-match-data
+					 (reftex-no-props
+					  (reftex-nth-arg-wrapper
+					   mac)))))
+                         (entry (progn (goto-char (match-end 0))
+                                       (reftex-label-info
+					label file bound mac))))
+                    (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 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))))
+      ;; Kill the scanned buffer
+      (reftex-kill-temporary-buffers next-buf))
+    ;; Return the list
+    docstruct))
+(defun reftex-locate-bibliography-files (master-dir)
+  ;; Scan buffer for bibliography macro and return file list.
+  (let (file-list)
+    (save-excursion
+      (goto-char (point-min))
+      (if (re-search-forward
+           "\\(\\`\\|[\n\r]\\)[ \t]*\\\\bibliography{[ \t]*\\([^}]+\\)" nil t)
+          (setq file-list
+                (mapcar (function (lambda (x) (concat x ".bib")))
+                        (reftex-delete-list
+                         reftex-bibfile-ignore-list
+                         (split-string
+                          (reftex-match-string 2)
+                          "[ \t\n\r]*,[ \t\n\r]*")))))
+      (delete nil
+	      (mapcar 
+	       (function 
+		(lambda (file)
+		  (reftex-find-bib-file file master-dir)))
+	       file-list)))))
+(defun reftex-last-assoc-before-elt (key elt list)
+  ;; Find the last association of KEY in LIST before or at ELT
+  ;; ELT is found in LIST with equal, not eq.
+  ;; Returns nil when either KEY or elt are not found in LIST.
+  ;; On success, returns the association.
+  (let* ((elt (car (member elt list))) ass last-ass)
+    (while (and (setq ass (assoc key list))
+                (setq list (memq ass list))
+                (memq elt list))
+      (setq last-ass ass
+            list (cdr list)))
+    last-ass))
+(defun reftex-replace-label-list-segment (old insert &optional entirely)
+  ;; Replace the segment in OLD which corresponds to INSERT.
+  ;; Works with side effects, directly changes old.
+  ;; If entirely is t, just return INSERT.
+  ;; This function also makes sure the old toc markers do not point anywhere.
+  (cond
+   (entirely
+    (reftex-silence-toc-markers old (length old))
+    insert)
+   (t (let* ((new old)
+             (file (nth 1 (car insert)))
+             (eof-list (member (list 'eof file) old))
+             (bof-list (member (list 'bof file) old))
+             n)
+        (if (not (and bof-list eof-list))
+            (error "Cannot splice")
+          ;; Splice
+          (reftex-silence-toc-markers bof-list (- (length bof-list)
+                                                  (length eof-list)))
+          (setq n (- (length old) (length bof-list)))
+          (setcdr (nthcdr n new) (cdr insert))
+          (setcdr (nthcdr (1- (length new)) new) (cdr eof-list)))
+        new))))
+(defun reftex-silence-toc-markers (list n)
+  ;; Set all markers in list to nil
+  (while (and list (> (decf n) -1))
+    (and (eq (car (car list)) 'toc)
+         (markerp (nth 4 (car list)))
+         (set-marker (nth 4 (car list)) nil))
+    (pop list)))
+(defun reftex-access-parse-file (action)
+  (let* ((list (symbol-value reftex-docstruct-symbol))
+         (master (reftex-TeX-master-file))
+	 (enable-local-variables nil)
+         (file (if (string-match "\\.[a-zA-Z]+\\'" master)
+                   (concat (substring master 0 (match-beginning 0)) ".rel")
+                 (concat master ".rel"))))
+    (cond
+     ((eq action 'readable)
+      (file-readable-p file))
+     ((eq action 'restore)
+      (if (eq reftex-docstruct-symbol nil)
+          ;; Symbols are not yet tied: Tie them.
+          (reftex-tie-multifile-symbols))
+      (if (file-exists-p file)
+          ;; load the file and return t for success
+          (progn (load-file file) t)
+        ;; throw an exception
+        (error "No restore file %s" file)))
+     ((eq action 'read)
+      (if (file-exists-p file)
+          ;; load the file and return t for success
+          (progn (load-file file) t)
+        ;; return nil for failure, but no exception
+        nil))
+     (t
+      (save-excursion
+        (if (file-writable-p file)
+            (progn
+              (message "Writing parse file %s" (abbreviate-file-name file))
+              (find-file file)
+              (erase-buffer)
+              (insert (format ";; RefTeX parse info file\n"))
+              (insert (format ";; File: %s\n" master))
+              (insert (format ";; Date: %s\n"
+                              (format-time-string "%D %T"
+                                                  (current-time))))
+              (insert (format ";; User: %s (%s)\n\n"
+                              (user-login-name) (user-full-name)))
+              (insert "(set reftex-docstruct-symbol '(\n\n")
+              (let ((standard-output (current-buffer)))
+                (mapcar
+                 (function
+                  (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)))))
+                          (t (print x)))))
+                 list))
+              (insert "))")
+              (save-buffer 0)
+              (kill-buffer (current-buffer)))
+          (error "Cannot write to file %s" file)))
+      t))))
+;; Creating labels --------------
+(defun reftex-label (&optional environment no-insert)
+  "Insert a unique label.  Return the label.
+If ENVIRONMENT is given, don't bother to find out yourself.
+If NO-INSERT is non-nil, do not insert label into buffer.
+With prefix arg, force to rescan document first.
+When you are prompted to enter or confirm a label, and you reply with
+just the prefix or an empty string, no label at all will be inserted.
+A new label is also recorded into the label list.
+This function is controlled by the settings of reftex-insert-label-flags."
+  (interactive)
+  ;; Ensure access to scanning info and rescan buffer if prefix are is '(4).
+  (reftex-access-scan-info current-prefix-arg)
+  ;; Find out what kind of environment this is and abort if necessary.
+  (if (or (not environment)
+          (not (assoc environment reftex-env-or-mac-alist)))
+      (setq environment (reftex-label-location)))
+  (unless environment
+    (error "Can't figure out what kind of label should be inserted"))
+  ;; Ok, go ahead.
+  (catch 'exit
+    (let* ((entry (assoc environment reftex-env-or-mac-alist))
+	   (typekey (nth 1 entry))
+	   (format (nth 3 entry))
+	   label prefix valid default force-prompt rescan-is-useful)
+      (when (and (eq (string-to-char environment) ?\\)
+		 (nth 5 entry)
+		 (memq (preceding-char) '(?\[ ?\{)))
+	(setq format "%s"))
+      (setq prefix (or (cdr (assoc typekey reftex-typekey-to-prefix-alist))
+		       (concat typekey "-")))
+      ;; Replace any escapes in the prefix
+      (setq prefix (reftex-replace-prefix-escapes prefix))