1 ;; reftex.el --- Minor mode for doing \label, \ref and \cite in LaTeX
3 ;; Copyright (c) 1997 Free Software Foundation, Inc.
5 ;; Author: Carsten Dominik <dominik@strw.LeidenUniv.nl>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
25 ;;---------------------------------------------------------------------------
29 ;; RefTeX is a minor mode with distinct support for \ref, \label and
30 ;; \cite commands in (multi-file) LaTeX documents.
31 ;; Labels are created semi-automatically. Definition context of labels is
32 ;; provided when creating a reference. Citations are simplified with
33 ;; efficient database lookup.
35 ;; To turn RefTeX Minor Mode on and off in a particular buffer, use
38 ;; To turn on RefTeX Minor Mode for all LaTeX files, add one of the
39 ;; following lines to your .emacs file:
41 ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
42 ;; (add-hook 'latex-mode-hook 'turn-on-reftex) ; with Emacs latex mode
44 ;; For key bindings, see further down in this documentation.
46 ;;---------------------------------------------------------------------------
50 ;; 1. USING \label AND \ref. Labels and references are one of the
51 ;; strong points of LaTeX. But, in documents with hundreds of
52 ;; equations, figures, tables etc. it becomes quickly impossible to
53 ;; find good label names and to actually remember them. Then, also
54 ;; completion of labels in not enough. One actually needs to see the
55 ;; context of the label definition to find the right one.
57 ;; - RefTeX distinguishes labels for different environments. It
58 ;; always knows if a certain label references a figure, table
59 ;; etc.. You can configure RefTeX to recognize any additional
60 ;; labeled environments you might have defined yourself.
62 ;; - RefTeX defines automatically unique labels. Type `C-c ('
63 ;; (reftex-label) to insert a label at point. RefTeX will either
64 ;; - derive a label from context (default for section labels)
65 ;; - insert a simple label consisting of a prefix and a number
66 ;; (default for equations and enumerate items) or
67 ;; - prompt for a label string (figures and tables).
68 ;; Which labels are created how can be controlled with the variable
69 ;; `reftex-insert-label-flags'.
71 ;; - Referencing labels is a snap and I promise you'll love it.
72 ;; In order to make a reference, type `C-c )' (`reftex-reference').
73 ;; This shows an outline of the document with all labels of a
74 ;; certain type (figure, equation,...) and context of the label
75 ;; definition. Selecting one of the labels inserts a \ref macro
76 ;; into the original buffer. Online help during the selection is
77 ;; available with `?'.
79 ;; 2. CITATIONS. After typing `C-c [' (`reftex-citation'), RefTeX will
80 ;; let you specify a regexp to search in current BibTeX database files
81 ;; (as specified in the \bibliography command) and pull out a formatted
82 ;; list of matches for you to choose from. The list is *formatted* and
83 ;; thus much easier to read than the raw database entries. It can also
84 ;; be sorted. The text inserted into the buffer is by default just
85 ;; `\cite{KEY}', but can also contain author names and the year in a
86 ;; configurable way. See documentation of the variable
87 ;; `reftex-cite-format'.
89 ;; 3. TABLE OF CONTENTS. Typing `C-c =' (`reftex-toc') will show a table
90 ;; of contents of the document. From that buffer, you can jump quickly
91 ;; to every part of your document. This is similar to imenu, only it
92 ;; works for entire multifile documents and uses the keyboard rather
93 ;; than the mouse. The initial version of this function was contributed
96 ;; 4. MULTIFILE DOCUMENTS are fully supported by RefTeX. Such documents
97 ;; consist of a master file and many other files being included via
98 ;; \input or \include. (La)TeX source files included from another file
99 ;; should specify the name of the top level master file with a `file
100 ;; variable' (see the Emacs documentation on file variables for details:
101 ;; [Emacs/Customization/Variables/File Variables]). With AUCTeX, this
102 ;; variable is called `TeX-master'. The Emacs (La)TeX modes use
103 ;; `tex-main-file' instead. RefTeX will check for both. Check the
104 ;; documentation of your (La)TeX modes on how to specify the master
106 ;; RefTeX knows about all files related to a document via \input and
107 ;; \include. It provides functions to run regular expression searches
108 ;; and replaces over the entire document and to create a TAGS file.
110 ;; 5. DOCUMENT PARSING. RefTeX needs to parse the document in order to find
111 ;; labels and other information. It will do it automatically once, when
112 ;; you start working with a document. If you need to enforce reparsing
113 ;; later, call any of the functions `reftex-citation', `reftex-label',
114 ;; `reftex-reference', `reftex-toc' with a raw C-u prefix.
116 ;;-------------------------------------------------------------------------
120 ;; RefTeX contains configurable options which change the way it works.
122 ;; Most importantly, RefTeX needs to be configured if you use labels to
123 ;; mark non-standard environments. RefTeX always understands LaTeX section
124 ;; commands and the following environments: figure, figure*,
125 ;; sidewaysfigure, table, table*, sidewaystable, equation, eqnarray,
126 ;; enumerate. For everythings else, it needs to be configured.
128 ;; A good way to configure RefTeX is with the custom.el package by Per
129 ;; Abrahamsen, shipped with Emacs 20 and XEmacs 19.15. To do this, just
130 ;; say `M-x reftex-customize'.
132 ;; Here is a complete list of the RefTeX configuration variables with
133 ;; their default settings. You could copy part of this list to your
134 ;; .emacs file and change whatever is necessary. Each variable has an
135 ;; extensive documentation string. Look it up for more information!
137 ;; ;; Configuration Variables and User Options for RefTeX ------------------
138 ;; ;; Support for \label and \ref ------------------------------------------
139 ;; (setq reftex-label-alist nil)
140 ;; (setq reftex-default-label-alist-entries '(Sideways LaTeX))
141 ;; (setq reftex-use-text-after-label-as-context nil)
142 ;; ;; Label insertion
143 ;; (setq reftex-insert-label-flags '("s" "sft"))
144 ;; (setq reftex-derive-label-parameters '(3 20 t 1 "-"
145 ;; ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is")))
146 ;; (setq reftex-label-illegal-re "[\000-\040\177-\377\\\\#$%&~^_{}]")
147 ;; (setq reftex-abbrev-parameters '(4 2 "^saeiou" "aeiou"))
148 ;; ;; Label referencing
149 ;; (setq reftex-label-menu-flags '(t t nil nil nil nil t))
150 ;; (setq reftex-guess-label-type t)
151 ;; ;; BibteX citation configuration ----------------------------------------
152 ;; (setq reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB"))
153 ;; (setq reftex-bibfile-ignore-list nil)
154 ;; (setq reftex-sort-bibtex-matches 'reverse-year)
155 ;; (setq reftex-cite-format 'default)
156 ;; (setq reftex-comment-citations nil)
157 ;; (setq reftex-cite-comment-format
158 ;; "%% %2a %y, %j %v, %P, %e: %b, %u, %s %<\n")
159 ;; (setq reftex-cite-punctuation '(", " " \\& " " {\\it et al.}"))
160 ;; ;; Table of contents configuration --------------------------------------
161 ;; (setq reftex-toc-follow-mode nil)
162 ;; ;; Miscellaneous configurations -----------------------------------------
163 ;; (setq reftex-extra-bindings nil)
164 ;; (setq reftex-plug-into-AUCTeX nil)
165 ;; (setq reftex-use-fonts t)
166 ;; (setq reftex-keep-temporary-buffers t)
167 ;; (setq reftex-auto-show-entry t)
169 ;; CONFIGURATION EXAMPLES:
170 ;; =======================
172 ;; Suppose you are working with AMS-LaTeX amsmath package (with its math
173 ;; environments like `align', `multline' etc.). Here is how you would
174 ;; configure RefTeX to recognize these environments:
176 ;; (setq reftex-label-alist '(AMSTeX))
178 ;; This is very easy since RefTeX has builtin support for AMS-LaTeX.
179 ;; Suppose, however, you are also
181 ;; - using "\newtheorem" in LaTeX in order to define two new environments
182 ;; "Theorem" and "Axiom" like this:
184 ;; \newtheorem{axiom}{Axiom}
185 ;; \newtheorem{theorem}{Theorem}
187 ;; - making your figures not directly with the figure environment, but with
190 ;; \newcommand{\myfig}[4][tbp]{
191 ;; \begin{figure}[#1]
196 ;; which would be called like
198 ;; \myfig{filename}{\label{fig:13} caption text}{1}
200 ;; Here is how to tell RefTeX to also recognize Theorem and Axiom as
201 ;; labeled environments, and that any labels defined inside the \myfig
202 ;; macro are figure labels:
204 ;; (setq reftex-label-alist
206 ;; ("axiom" ?a "ax:" "~\\ref{%s}" nil ("Axiom" "Ax."))
207 ;; ("theorem" ?h "thr:" "~\\ref{%s}" t ("Theorem" "Theor." "Th."))
208 ;; ("\\myfig" ?f "fig:" nil 2)))
210 ;; The type indicator characters ?a and ?h are used for prompts when
211 ;; RefTeX queries for a label type. Note that "h" was chosen for "theorem"
212 ;; since "t" is already taken by "table". Note that also "s", "f", "e", "n"
213 ;; are taken by the standard environments.
214 ;; The automatic labels for Axioms and Theorems will look like "ax:23" or
216 ;; The "\ref{%s}" is a format string indicating how to insert references to
217 ;; these labels. The nil format in the \myfig entry means to use the same
218 ;; format as other figure labels.
219 ;; The next item indicates how to grab context of the label definition.
220 ;; - t means to get it from a default location (from the beginning of a \macro
221 ;; or after the \begin statement). t is *not* a good choice for eqnarray
222 ;; and similar environments.
223 ;; - nil means to use the text right after the label definition.
224 ;; - 2 means grab the 2nd macro argument: \myfig{xxx}{THIS IS CONTEXT}{1}
225 ;; - For more complex ways of getting context, see the docstring of
226 ;; `reftex-label-alist'.
227 ;; The strings at the end of each entry are used to guess the correct label
228 ;; type from the word before point when creating a reference. E.g. if you
229 ;; write: "As we have shown in Theorem" and then press `C-)', RefTeX will
230 ;; know that you are looking for a Theorem label and restrict the labels in
231 ;; the menu to only these labels without even asking.
232 ;; See also the documentation string of the variable `reftex-label-alist'.
234 ;; Depending on how you would like the label insertion and selection for the
235 ;; new environments to work, you might want to add the letters "a" and "h"
236 ;; to some of the flags in the following variables:
238 ;; reftex-insert-label-flags
239 ;; reftex-label-menu-flags
241 ;; The individual flags in these variables can be set to t or nil to enable or
242 ;; disable the feature for all label types. They may also contain a string of
243 ;; label type letters in order to turn on the feature for those types only.
246 ;; If you are writing in a language different from English you might want to
247 ;; add magic words for that language. Here is a German example:
249 ;; (setq reftex-label-alist
250 ;; '((nil ?s nil nil nil ("Kapitel" "Kap." "Abschnitt" "Teil"))
251 ;; (nil ?e nil nil nil ("Gleichung" "Gl."))
252 ;; (nil ?t nil nil nil ("Tabelle"))
253 ;; (nil ?f nil nil nil ("Figur" "Abbildung" "Abb."))
254 ;; (nil ?n nil nil nil ("Punkt"))))
256 ;; Using nil as first item in each entry makes sure that this entry does
257 ;; not replace the original entry for that label type, but just adds magic
262 ;; By default, citations are inserted simply as \cite{KEY}. You can have
263 ;; more complex citation commands with many available packages, most
264 ;; notably the harvard and natbib packages. RefTeX can be configured to
265 ;; support these and other styles by setting the variable reftex-cite-format.
266 ;; E.g., for the natbib package you would use
268 ;; (setq reftex-cite-format 'natbib)
270 ;; This can also be done as a file variable. For the full list of builtin
271 ;; options, try `M-x customize-variable RET reftex-cite-format RET'.
275 ;; - Loading reftex.el runs the hook `reftex-load-hook'.
276 ;; - Turning on reftex-mode runs `reftex-mode-hook'.
277 ;; - Creating the master buffer runs `reftex-make-master-buffer-hook'
278 ;; on the master buffer just before parsing starts.
280 ;;-------------------------------------------------------------------------
284 ;; All important functions of RefTeX can be reached from its menu which
285 ;; is installed in the menu bar as "Ref" menu. Only the more frequently used
286 ;; functions have key bindings.
288 ;; Here is the default set of keybindings from RefTeX.
291 ;; C-c ( reftex-label
292 ;; C-c ) reftex-reference
293 ;; C-c [ reftex-citation
294 ;; C-c & reftex-view-crossref
296 ;; I've used these bindings in order to avoid interfering with AUCTeX's
297 ;; settings. Personally, I also bind some functions in the C-c LETTER
298 ;; map for easier access:
301 ;; C-c l reftex-label
302 ;; C-c r reftex-reference
303 ;; C-c c reftex-citation
304 ;; C-c v reftex-view-crossref
305 ;; C-c s reftex-search-document
306 ;; C-c g reftex-grep-document
308 ;; If you want to copy those as well, set in your .emacs file:
310 ;; (setq reftex-extra-bindings t)
312 ;; It is possible to bind the function for viewing cross references to a
313 ;; mouse event. Something like the following in .emacs will do the trick:
315 ;; (add-hook 'reftex-load-hook
317 ;; (define-key reftex-mode-map [(alt mouse-1)]
318 ;; 'reftex-mouse-view-crossref)))
320 ;;-------------------------------------------------------------------------
326 ;; If you are writing TeX or LaTeX documents with Emacs, you should have
327 ;; a look at AUCTeX, the definitive package to work with TeX and LaTeX.
328 ;; Information on AUCTeX can be found here:
330 ;; http://www.sunsite.auc.dk/auctex/
332 ;; Instead of using the RefTeX functions described above directly, you
333 ;; can also use them indirectly through AUCTeX (>9.7p). RefTeX provides
334 ;; several interface functions which can be used as replacement for
335 ;; corresponding AUCTeX functions dealing with labels and citations.
336 ;; In this way you can work normally with AUCTeX and use RefTeX
337 ;; internals to create and complete labels and citation keys.
339 ;; `reftex-label' can be used as the `LaTeX-label-function' which does
340 ;; label insertion when new environments are created with C-c C-e.
342 ;; `reftex-arg-label', `reftex-arg-ref' and `reftex-arg-cite' can replace
343 ;; the corresponding `TeX-arg-...' functions. E.g. when you insert a
344 ;; label macro with `C-c RET label RET', RefTeX will be transparently used
345 ;; to create the label.
347 ;; In order to plug all 4 functions into AUCTeX, use in .emacs:
349 ;; (setq reftex-plug-into-AUCTeX t)
351 ;; You may also choose to plug in only some of these functions. See
352 ;; the doc string of `reftex-plug-into-AUCTeX'.
354 ;; AUCTeX can support RefTeX via style files. A style file may contain
355 ;; calls to `reftex-add-to-label-alist' which defines additions to
356 ;; `reftex-label-alist'. The argument taken by this function must have
357 ;; the same format as `reftex-label-alist'. The `amsmath.el' style file
358 ;; of AUCTeX (>9.7p) for example contains the following:
360 ;; (TeX-add-style-hook "amsmath"
363 ;; (if (featurep 'reftex)
364 ;; (reftex-add-to-label-alist '(AMSTeX))))))
366 ;; while a package `myprop' defining a proposition environment with
367 ;; \newtheorem might use
369 ;; (TeX-add-style-hook "myprop"
372 ;; (if (featurep 'reftex)
373 ;; (reftex-add-to-label-alist
374 ;; '(("proposition" ?p "prop:" "~\\ref{%s}" t
375 ;; ("Proposition" "Prop."))))))))
379 ;; Once you have written a document with labels, refs and citations,
380 ;; it can be nice to read such a file like a hypertext document.
381 ;; RefTeX has some support for that (`reftex-view-crossref',
382 ;; `reftex-search-document'). A more elegant interface with mouse
383 ;; support and links into Hyperbole is provided (among other things)
384 ;; by Peter S. Galbraith's `bib-cite.el'. There is some overlap in the
385 ;; functionalities of Bib-cite and RefTeX. Bib-cite.el comes bundled
386 ;; with AUCTeX. You can also get the latest version from
388 ;; ftp://ftp.phys.ocean.dal.ca/users/rhogee/elisp/bib-cite.el
390 ;;-------------------------------------------------------------------------
392 ;; PERFORMANCE ISSUES
394 ;; 1. RefTeX will load other parts of a multifile document as well as BibTeX
395 ;; database files for lookup purposes. These buffers are kept, so that
396 ;; subsequent lookup in the same files is fast. For large documents and
397 ;; large BibTeX databases, this can use up a lot of memory. If you have
398 ;; more time than memory, try the following option, which will remove
399 ;; buffers created for lookup after use.
401 ;; (setq reftex-keep-temporary-buffers nil)
403 ;; 2. Parsing the document for labels and their context can be slow.
404 ;; Therefore, RefTeX does it just once automatically. Further parsing
405 ;; happens only on user request
406 ;; - with a raw C-u prefix arg to any of the functions `reftex-label',
407 ;; `reftex-reference', `reftex-citation', `reftex-toc'.
408 ;; - with the `r' key from the label selection menu or the *toc* buffer.
410 ;; *** If you use `reftex-label' to create labels, the list will be
411 ;; *** updated internally, so that no extra parsing is required.
413 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
415 ;; KNOWN BUGS AND WORK-AROUNDS
417 ;; o If you change `reftex-label-alist' in an editing session, you need to
418 ;; reset reftex with `M-x reftex-reset-mode' in order to make these
419 ;; changes effective. Changes introduced with the function
420 ;; `reftex-add-to-label-alist' as well as changes applied from the
421 ;; customization buffer automatically trigger a reset.
423 ;; o At times the short context shown by RefTeX may not be what you want.
424 ;; In particular, eqnarray environments can be difficult to parse.
425 ;; RefTeX's default behavior for eqnarrays is to scan backwards to either
426 ;; a double backslash or the beginning of the environment. If this gives
427 ;; unsatisfactory results, make it a habit to place the label *before*
432 ;; E = \gamma m c^2 \\
434 ;; \gamma = \sqrt{1-v^2/c^2}
437 ;; and turn off parsing for context in equation and eqnarray environments
440 ;; (setq reftex-use-text-after-label-as-context "e").
442 ;; o RefTeX keeps only one global copy of the configuration variables.
443 ;; Also, any additions from style files go into a global variable.
444 ;; Practically, this should not be a problem. Theoretically, it could
445 ;; give conflicts if two documents used environments with identical
446 ;; names, but different associated label types.
448 ;; o Input, include, bibliography and section statements have to be first
449 ;; on a line (except for white space) in order to be seen by RefTeX.
451 ;; o When the document is scanned, RefTeX creates a large "master" buffer
452 ;; containing the entire document instead of scanning the individual
453 ;; files one by one. I hope to change this eventually.
455 ;; o Creating the master buffer bypasses `find-file-hook' as well as
456 ;; TeX/LaTeX mode hooks for efficiency reasons. If any of the relevant
457 ;; hooks contains functions filtering (La)TeX files (e.g. isotex), these
458 ;; functions should go into `reftex-make-master-buffer-hook' as well.
460 ;; o If you have two identical section headings in the same file,
461 ;; `reftex-toc' will only let you jump to the first one because it searches
462 ;; for the section heading from the beginning of the file. You can work
463 ;; around this by changing one of the section titles in a way LaTeX does
464 ;; not see, e.g. with extra white space. RefTeX will distinguish
465 ;; \section{Introduction} from \section{ Introduction}.
467 ;; o RefTeX needs a \label macro to identify a label during parsing. Some
468 ;; packages, however, define environments and macros which require a naked
469 ;; label as argument. This is currently not possible with RefTeX. It
470 ;; will be in version 3.00.
472 ;; o RefTeX sees also labels in regions commented out and will refuse to
473 ;; make duplicates of such a label. This is considered to be a feature.
475 ;; o When RefTeX tries to show a window full of context from inside a
476 ;; section hidden with `outline-minor-mode', it will unhide that section.
477 ;; This change will not be reversed automatically.
479 ;;---------------------------------------------------------------------------
483 ;; Rewriting the parser so that it can parse the file without making a
484 ;; master buffer, save parsing information and reparse only parts of
485 ;; the document. This will make RefTeX better suited for very large
488 ;; Deal with naked labels.
490 ;;---------------------------------------------------------------------------
494 ;; Carsten Dominik <dominik@strw.LeidenUniv.nl>
496 ;; with contributions from Stephen Eglen
498 ;; The newest version of RefTeX can be found at
500 ;; http://www.strw.leidenuniv.nl/~dominik/Tools/
501 ;; ftp://strw.leidenuniv.nl/pub/dominik/
505 ;; At least the following people have invested time to test and bug-fix
506 ;; reftex.el. Some have send patches for fixes or new features.
508 ;; Stephen Eglen <stephene@cogs.susx.ac.uk>
509 ;; F.E.Burstall <F.E.Burstall@maths.bath.ac.uk>
510 ;; Karl Eichwalder <ke@ke.Central.DE>
511 ;; Laurent Mugnier <mugnier@onera.fr>
512 ;; Rory Molinari <molinari@yunt.math.lsa.umich.edu>
513 ;; Soren Dayton <csdayton@cs.uchicago.edu>
514 ;; Daniel Polani <polani@Informatik.Uni-Mainz.DE>
515 ;; Allan Strand <astrand@trillium.NMSU.Edu>
516 ;; Adrian Lanz <lanz@waho.ethz.ch>
517 ;; Jan Vroonhof <vroonhof@math.ethz.ch>
519 ;; The view crossref feature was inspired by the similar function in
520 ;; Peter S. Galbraith's bib-cite.el.
522 ;; Finally thanks to Uwe Bolick <bolick@physik.tu-berlin.de> who first
523 ;; got me (some years ago) into supporting LaTeX labels and references
524 ;; with an Editor (which was MicroEmacs at the time).
526 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
531 ;; Stuff that needs to be there when we use defcustom
532 ;; --------------------------------------------------
536 (defvar reftex-tables-dirty t
537 "Flag showing if tables need to be re-computed.")
540 (defun reftex-set-dirty (symbol value)
541 (setq reftex-tables-dirty t)
544 ;;; Begin of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
546 ;; Configuration Variables and User Options for RefTeX ------------------
549 "LaTeX label and citation support."
551 :link '(url-link :tag "Home Page" "http://strw.leidenuniv.nl/~dominik/Tools/")
555 (defun reftex-customize ()
556 "Call the customize function with reftex as argument."
558 ;; Depending on the customize version we can call different functions.
560 ((fboundp 'customize-browse)
561 (customize-browse 'reftex))
562 ((fboundp 'customize-group)
563 (customize-group 'reftex))
565 (customize 'reftex))))
567 (defun reftex-show-commentary ()
568 "Use the finder to view the file documentation from `reftex.el'."
571 (finder-commentary "reftex.el"))
573 ;; Support for \label and \ref --------------------------------------
575 (defgroup reftex-label-support nil
576 "Support for creation, insertion and referencing of labels in LaTeX."
579 (defgroup reftex-defining-label-environments nil
580 "Definition of environments and macros to do with label."
581 :group 'reftex-label-support)
583 (defcustom reftex-label-alist nil
584 "Alist with information on environments for \\label-\\ref use.
585 See the definition of `reftex-label-alist-builtin' for examples. This variable
586 should define additions and changes to the default. The only things you MUST
587 NOT change is that `?s' is the type indicator for section labels and SPACE is
588 for the `any' label type. These are hard-coded at other places in the code.
590 Changes to this variable after RefTeX has been loaded become only
591 effective when RefTeX is reset with \\[reftex-reset-mode].
593 Each list entry is a list describing an environment or macro carrying a
594 label. The elements of each list entry are:
596 0. Name of the environment (like \"table\") or macro (like \"\\\\myfig\").
597 Special names: `section' for section labels, `any' to define a group
598 which contains all labels.
599 This may also be nil if this entry is only meant to change some settings
600 associated with the type indicator character (see below).
602 1. Type indicator character, like `?t'.
603 The type indicator is a single character used in prompts for
604 label types. It must be a printable character. The same character
605 may occur several times in this list, to cover cases in which different
606 environments carry the same label type (like equation and eqnarray).
608 2. Label prefix string, like \"tab:\".
609 The prefix is a short string used as the start of a label. It may be the
610 empty string. If `nil', a prefix will be constructed from the typekey.
611 The prefix may contain the following `%' escapes:
612 %f Current file name with directory and extension stripped.
613 %F Current file name relative to directory of master file.
614 %u User login name, on systems which support this.
616 Example: In a file `intro.tex', \"eq:%f:\" will become \"eq:intro:\").
618 3. Format string for reference insert in buffer. `%s' will be replaced by
620 When the format starts with `~', whitespace before point will be removed
621 so that the reference cannot be separated from the word before it.
623 4. Indication on how to find the short context.
624 - If nil, use the text following the \\label{...} macro.
626 - text following the \\begin{...} statement of environments
627 (not a good choice in in eqnarray or enumerate environments!)
628 - the section heading for section labels.
629 - the begin of the macro for macros.
630 - If an integer, use the nth argument of the macro. If there are less
631 than n arguments (parenthesis pairs), use text after the last one.
632 - If a string, use as regexp to search *backward* from the label. Context
633 is then the text following the end of the match. E.g. putting this to
634 \"\\\\\\\\caption{\" will use the beginning of the caption in a figure
635 or table environment.
636 \"\\\\\\\\begin{eqnarray}\\\\|\\\\\\\\\\\\\\\\\" works for eqnarrays.
637 - If a function, call this function with the name of the environment/macro
638 as argument. On call, point will be just after the \\label macro. The
639 function is expected to return a suitable context string. It should
640 throw an exception (error) when failing to find context.
641 As an example, here is a function returning the 10 chars following
642 the label macro as context:
644 (defun my-context-function (env-or-mac)
645 (if (> (point-max) (+ 10 (point)))
646 (buffer-substring (point) (+ 10 (point)))
647 (error \"Buffer too small\")))
649 Label context is used in two ways by RefTeX: For display in the label
650 menu, and to derive a label string. If you want to use a different
651 method for each of these, specify them as a dotted pair.
652 E.g. `(nil . t)' uses the text after the label (nil) for display, and
653 text from the default position (t) to derive a label string. This is
654 actually used for section labels.
656 Setting the variable `reftex-use-text-after-label-as-context' to t
657 overrides the setting here.
659 5. List of magic words which identify a reference to be of this type.
660 If the word before point is equal to one of these words when calling
661 `reftex-reference', the label list offered will be automatically
662 restricted to labels of the correct type.
664 If the type indicator characters of two or more entries are the same, RefTeX
666 - the first non-nil format and prefix
667 - the magic words of all involved entries.
669 Any list entry may also be a symbol. If that has an association in
670 `reftex-label-alist-builtin', the cdr of that association is spliced into the
671 list. See the AMSTeX configuration example in the comment section of
673 :group 'reftex-defining-label-environments
674 :set 'reftex-set-dirty
679 :value ("" ?a nil nil t nil)
683 ;; Update here with: update-builtin-label-1
684 (const :tag "Sideways : Alias for -->rotating" Sideways)
685 (const :tag "AMSTeX : Alias for -->amsmath" AMSTeX)
686 (const :tag "amsmath : AMS math environments" amsmath)
687 (const :tag "longtable: The longtable environment" longtable)
688 (const :tag "rotating : Sidewaysfigure and table" rotating)
689 (const :tag "subfigure: Subfigure environments/macro" subfigure)
690 (const :tag "LaTeX : LaTeX default environments" LaTeX))
691 (list :tag "Detailed custom entry"
692 (choice :tag "Environment or \\macro "
693 (const :tag "Ignore, just use typekey" nil)
695 (character :tag "Typekey character " ?a)
696 (choice :tag "Label prefix string "
697 (const :tag "Default" nil)
698 (string :tag "String" "lab:"))
699 (choice :tag "Label reference format"
700 (const :tag "Default" nil)
701 (string :tag "String" "~\\ref{%s}"))
702 (choice :tag "Context"
705 (const :tag "Default position" t)
706 (const :tag "After label" nil)
707 (number :tag "Macro arg nr" 1)
708 (regexp :tag "Regexp" "")
709 (symbol :tag "Function" my-func))
710 (cons :tag "2 different methods"
712 :tag " Display context "
713 (const :tag "Default position" t)
714 (const :tag "After label" nil)
715 (number :tag "Macro arg nr" 1)
716 (regexp :tag "Regexp" "")
717 (symbol :tag "Function" my-func))
719 :tag " Derive label context"
720 (const :tag "Default position" t)
721 (const :tag "After label" nil)
722 (number :tag "Macro arg nr" 1)
723 (regexp :tag "Regexp" "")
724 (symbol :tag "Function" my-func))))
725 (repeat :tag "List of Magic Words" (string))))))
727 (defcustom reftex-default-label-alist-entries '(Sideways LaTeX)
728 "Default label alist specifications. LaTeX should be the last entry.
729 This list describes the default label environments RefTeX should always use
730 in addition to the specifications in reftex-label-alist. It is probably a
731 mistake to remove the LaTeX symbol from this list.
734 LaTeX The standard LaTeX environments
735 Sideways The sidewaysfigure and sidewaystable environments
736 AMSTeX The math environments in the AMS_LaTeX amsmath package
738 For the full list of options, try
740 M-x customize-variable RET reftex-default-label-alist-entries RET."
741 :group 'reftex-defining-label-environments
742 :set 'reftex-set-dirty
747 ;; Update here with: update-builtin-label-2
748 (const :tag "Sideways : Alias for -->rotating" Sideways)
749 (const :tag "AMSTeX : Alias for -->amsmath" AMSTeX)
750 (const :tag "amsmath : AMS math environments" amsmath)
751 (const :tag "longtable: The longtable environment" longtable)
752 (const :tag "rotating : Sidewaysfigure and table" rotating)
753 (const :tag "subfigure: Subfigure environments/macro" subfigure)
754 (const :tag "LaTeX : LaTeX default environments" LaTeX))
757 (defcustom reftex-use-text-after-label-as-context nil
758 "*t means, grab context from directly after the \\label{..} macro.
759 This is the fastest method for obtaining context of the label definition, but
760 requires discipline when placing labels. Setting this variable to t takes
761 precedence over the individual settings in `reftex-label-alist'.
762 This variable may be set to t, nil, or a string of label type letters
763 indicating the label types for which it should be true."
764 :group 'reftex-defining-label-environments
765 :set 'reftex-set-dirty
767 (const :tag "on" t) (const :tag "off" nil)
768 (string :tag "Selected label types")))
772 (defgroup reftex-making-and-inserting-labels nil
773 "Options on how to create new labels."
774 :group 'reftex-label-support)
776 (defcustom reftex-insert-label-flags '("s" "sft")
777 "Flags governing label insertion. First flag DERIVE, second flag PROMPT.
779 If DERIVE is t, RefTeX will try to derive a sensible label from context.
780 A section label for example will be derived from the section heading.
781 The conversion of the context to a legal label is governed by the
782 specifications given in `reftex-derive-label-parameters'.
783 If RefTeX fails to derive a label, it will prompt the user.
785 If PROMPT is t, the user will be prompted for a label string. The prompt will
786 already contain the prefix, and (if DERIVE is t) a default label derived from
787 context. When PROMPT is nil, the default label will be inserted without
790 So the combination of DERIVE and PROMPT controls label insertion. Here is a
791 table describing all four possibilities:
794 -------------------------------------------------------------------------
795 nil nil Insert simple label, like eq:22 or sec:13. No query.
796 nil t Prompt for label.
797 t nil Derive a label from context and insert without query.
798 t t Derive a label from context and prompt for confirmation.
800 Each flag may be set to t, nil, or a string of label type letters
801 indicating the label types for which it should be true.
802 Thus, the combination may be set differently for each label type. The
803 default settings \"s\" and \"sft\" mean: Derive section labels from headings
804 (with confirmation). Prompt for figure and table labels. Use simple labels
805 without confirmation for everything else."
806 :group 'reftex-making-and-inserting-labels
807 :type '(list (choice :tag "Derive label from context"
808 (const :tag "always" t)
809 (const :tag "never" nil)
810 (string :tag "selected label types" ""))
811 (choice :tag "Prompt for label string "
812 :entry-format " %b %v"
813 (const :tag "always" t)
814 (const :tag "never" nil)
815 (string :tag "selected label types" ""))))
817 (defcustom reftex-derive-label-parameters '(3 20 t 1 "-" ; continue
818 ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is"))
819 "Parameters for converting a string into a label.
820 NWORDS Number of words to use.
821 MAXCHAR Maximum number of characters in a label string.
822 ILLEGAL nil: Throw away any words containing characters illegal in labels.
823 t: Throw away only the illegal characters, not the whole word.
824 ABBREV nil: Never abbreviate words.
825 t: Always abbreviate words (see `reftex-abbrev-parameters').
826 not t and not nil: Abbreviate words if necessary to shorten
827 label string below MAXCHAR.
828 SEPARATOR String separating different words in the label.
829 IGNOREWORDS List of words which should not be part of labels."
830 :group 'reftex-making-and-inserting-labels
831 :type '(list (integer :tag "Number of words " 3)
832 (integer :tag "Maximum label length " 20)
833 (choice :tag "Illegal characters in words"
834 (const :tag "throw away entire word" nil)
835 (const :tag "throw away single chars" t))
836 (choice :tag "Abbreviate words "
837 (const :tag "never" nil)
838 (const :tag "always" t)
839 (const :tag "when label is too long" 1))
840 (string :tag "Separator between words " "-")
841 (repeat :tag "Ignore words"
842 :entry-format " %i %d %v"
845 (defcustom reftex-label-illegal-re "[\000-\040\177-\377\\\\#$%&~^_{}]"
846 "Regexp matching characters not legal in labels.
847 For historic reasons, this character class comes *with* the [] brackets."
848 :group 'reftex-making-and-inserting-labels
849 :type '(regexp :tag "Character class"))
851 (defcustom reftex-abbrev-parameters '(4 2 "^saeiou" "aeiou")
852 "Parameters for abbreviation of words.
853 MIN-CHARS Minimum number of characters remaining after abbreviation.
854 MIN-KILL Minimum number of characters to remove when abbreviating words.
855 BEFORE Character class before abbrev point in word.
856 AFTER Character class after abbrev point in word."
857 :group 'reftex-making-and-inserting-labels
859 (integer :tag "Minimum chars per word" 4)
860 (integer :tag "Shorten by at least " 2)
861 (string :tag "cut before char class " "^saeiou")
862 (string :tag "cut after char class " "aeiou")))
866 (defgroup reftex-referencing-labels nil
867 "Options on how to reference labels."
868 :group 'reftex-label-support)
870 (defcustom reftex-label-menu-flags '(t t nil nil nil nil t)
871 "*List of flags governing the label menu makeup.
874 TABLE-OF-CONTENTS Show the labels embedded in a table of context.
875 SECTION-NUMBERS Include section numbers (like 4.1.3) in table of contents.
876 COUNTERS Show counters. This just numbers the labels in the menu.
877 NO-CONTEXT Non-nil means do NOT show the short context.
878 FOLLOW Follow full context in other window.
879 SHOW-COMMENTED Show labels from regions which are commented out.
880 MATCH-IN-TOC Searches in label menu will also match in toc lines.
882 Each of these flags can be set to t or nil, or to a string of type letters
883 indicating the label types for which it should be true. These strings work
884 like character classes in regular expressions. Thus, setting one of the
885 flags to \"sf\" makes the flag true for section and figure labels, nil
886 for everything else. Setting it to \"^ft\" makes it the other way round.
888 Most options can also be switched from the label menu itself - so if you
889 decide here to not have a table of contents in the label menu, you can still
890 get one interactively during selection from the label menu."
891 :group 'reftex-referencing-labels
893 (choice :tag "Embed in table of contents "
894 (const :tag "on" t) (const :tag "off" nil)
895 (string :tag "Selected label types"))
896 (choice :tag "Show section numbers "
897 (const :tag "on" t) (const :tag "off" nil))
898 (choice :tag "Show individual counters "
899 (const :tag "on" t) (const :tag "off" nil)
900 (string :tag "Selected label types"))
901 (choice :tag "Hide short context "
902 (const :tag "on" t) (const :tag "off" nil)
903 (string :tag "Selected label types"))
904 (choice :tag "Follow context in other window"
905 (const :tag "on" t) (const :tag "off" nil)
906 (string :tag "Selected label types"))
907 (choice :tag "Show commented labels "
908 (const :tag "on" t) (const :tag "off" nil)
909 (string :tag "Selected label types"))
910 (choice :tag "Searches match in toc lines "
911 (const :tag "on" t) (const :tag "off" nil)
912 (string :tag "Selected label types"))))
915 (defcustom reftex-guess-label-type t
916 "*Non-nil means, `reftex-reference' will try to guess the label type.
917 To do that, RefTeX will look at the word before the cursor and compare it with
918 the words given in `reftex-label-alist'. When it finds a match, RefTeX will
919 immediately offer the correct label menu - otherwise it will prompt you for
920 a label type. If you set this variable to nil, RefTeX will always prompt."
921 :group 'reftex-referencing-labels
924 ;; BibteX citation configuration ----------------------------------------
926 (defgroup reftex-citation-support nil
927 "Support for referencing bibliographic data with BibTeX."
930 (defcustom reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB")
931 "*List of env vars which might contain the path to BibTeX database files."
932 :group 'reftex-citation-support
933 :set 'reftex-set-dirty
934 :type '(repeat (string :tag "Environment variable")))
936 (defcustom reftex-bibfile-ignore-list nil
937 "List of files in \\bibliography{..} RefTeX should *not* parse.
938 The file names have to be in the exact same form as in the bibliography
939 macro - i.e. without the `.bib' extension.
940 Intended for files which contain only `@string' macro definitions and the
941 like, which are ignored by RefTeX anyway."
942 :group 'reftex-citation-support
943 :set 'reftex-set-dirty
944 :type '(repeat (string :tag "File name")))
946 (defcustom reftex-sort-bibtex-matches 'reverse-year
947 "*Sorting of the entries found in BibTeX databases by reftex-citation.
949 nil Do not sort entries.
950 'author Sort entries by author name.
951 'year Sort entries by increasing year.
952 'reverse-year Sort entries by decreasing year."
953 :group 'reftex-citation-support
954 :type '(choice (const :tag "not" nil)
955 (const :tag "by author" author)
956 (const :tag "by year" year)
957 (const :tag "by year, reversed" reverse-year)))
959 (defcustom reftex-cite-format 'default
960 "The format of citations to be inserted into the buffer.
961 It can be a string or an alist. In the simplest case this is just
962 the string \"\\cite{%l}\", which is also the default. See the
963 definition of `reftex-cite-format-builtin' for more complex examples.
965 If `reftex-cite-format' is a string, it will be used as the format.
966 In the format, the following percent escapes will be expanded.
968 %l The BibTeX label of the citation.
969 %a List of author names, see also `reftex-cite-punctuation.
970 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
971 %A First author name only.
972 %e Works like %a, but on list of editor names. (%2e and %E work a well)
974 It is also possible to access all other BibTeX database fields:
975 %b booktitle %c chapter %d edition %h howpublished
976 %i institution %j journal %k key %m month
977 %n number %o organization %p pages %P first page
978 %r address %s school %u publisher %t title
981 Usually, only %l is needed. Try, however, (setq reftex-comment-citations t).
983 If `reftex-cite-format' is an alist of characters and strings, the user
984 will be prompted for a character to select one of the possible format
986 In order to configure this variable, you can either set
987 `reftex-cite-format' directly yourself or set it to the SYMBOL of one of
988 the predefined styles (see `reftex-cite-format-builtin'). E.g.:
989 (setq reftex-cite-format 'harvard)"
990 :group 'reftex-citation-support
992 '(choice :format "%{%t%}: \n%[Value Menu%] %v"
993 (radio :tag "Symbolic Builtins"
996 ;; Update here with: update-builtin-cite
997 (const :tag "default: Default macro \\cite{%l}" default)
998 (const :tag "harvard: P. William's and T. Schnier's Harvard package" harvard)
999 (const :tag "natbib: Patrick W. Daly's Natbib package" natbib)
1000 (const :tag "astron: S. Hogeveen's Astron package" astron)
1001 (const :tag "author-year: Do-it-yourself Author year citation" author-year)
1002 (const :tag "locally: Put full info in parenthesis" locally))
1003 (string :tag "format string" "\\cite{%l}")
1004 (repeat :tag "key-ed format strings"
1005 :value ((?\r . "\\cite{%l}")
1006 (?t . "\\cite{%l}") (?p . "\\cite{%l}"))
1007 (cons (character :tag "Key character" ?\r)
1008 (string :tag "Format string" "")))))
1010 (defcustom reftex-comment-citations nil
1011 "Non-nil means add a comment for each citation describing the full entry.
1012 The comment is formatted according to `reftex-cite-comment-format'."
1013 :group 'reftex-citation-support
1016 (defcustom reftex-cite-comment-format ; continue
1017 "%% %2a %y, %j %v, %P, %e: %b, %u, %s %<\n"
1018 "Citation format used for commented citations. Must NOT contain %l."
1019 :group 'reftex-citation-support
1022 (defcustom reftex-cite-punctuation '(", " " \\& " " {\\it et al.}")
1023 "Punctuation for formatting of name lists in citations.
1024 This is a list of 3 strings.
1025 1. normal names separator, like \", \" in Jones, Brown and Miller
1026 2. final names separator, like \" and \" in Jones, Brown and Miller
1027 3. The \"et al\" string, like \" {...}\" in Jones {\\it et al.}"
1028 :group 'reftex-citation-support
1030 (string :tag "Separator for names ")
1031 (string :tag "Separator for last name in list")
1032 (string :tag "string used as et al. ")))
1034 ;; Table of contents configuration --------------------------------------
1036 (defgroup reftex-table-of-contents-browser nil
1037 "A multifile table of contents browser."
1040 (defcustom reftex-toc-follow-mode nil
1041 "Non-nil means, point in *toc* buffer will cause other window to follow.
1042 The other window will show the corresponding part of the document.
1043 This flag can be toggled from within the *toc* buffer with the `f' key."
1044 :group 'reftex-table-of-contents-browser
1047 ;; Miscellaneous configurations -----------------------------------------
1049 (defgroup reftex-miscellaneous-configurations nil
1050 "Collection of further configurations."
1053 (defcustom reftex-extra-bindings nil
1054 "Non-nil means, make additional key bindings on startup.
1055 These extra bindings are located in the users `C-c letter' map."
1056 :group 'reftex-miscellaneous-configurations
1059 (defcustom reftex-plug-into-AUCTeX nil
1060 "Plug-in flags for AUCTeX interface.
1061 This variable is a list of 4 boolean flags. When a flag is non-nil, it
1064 Flag 1: use `reftex-label' as `LaTeX-label-function'.
1065 Flag 2: use `reftex-arg-label' as `TeX-arg-label'
1066 Flag 3: use `reftex-arg-ref' as `TeX-arg-ref'
1067 Flag 4: use `reftex-arg-cite' as `TeX-arg-cite'
1069 You may also set the variable itself to t or nil in order to turn all
1070 plug-ins on or off, respectively.
1071 \\<LaTeX-mode-map>`LaTeX-label-function' is the function used for label insertion when you
1072 enter a new environment in AUCTeX with \\[LaTeX-environment].
1073 The `TeX-arg-label' etc. functions are for entering macro arguments during
1074 macro insertion with \\[TeX-insert-macro].
1075 See the AUCTeX documentation for more information.
1076 RefTeX uses `fset' to take over the function calls. Changing the variable
1077 may require a restart of Emacs in order to become effective."
1078 :group 'reftex-miscellaneous-configurations
1079 :type '(choice (const :tag "No plug-ins" nil)
1080 (const :tag "All possible plug-ins" t)
1082 :tag "Individual choice"
1083 :value (nil nil nil nil)
1084 (boolean :tag "Use reftex-label as LaTeX-label-function")
1085 (boolean :tag "Use reftex-arg-label as TeX-arg-label ")
1086 (boolean :tag "Use reftex-arg-ref as TeX-arg-ref ")
1087 (boolean :tag "Use reftex-arg-cite as TeX-arg-cite ")
1090 (defcustom reftex-use-fonts t
1091 "*Non-nil means, use fonts in label menu and on-the-fly help.
1092 Font-lock must be loaded as well to actually get fontified display."
1093 :group 'reftex-miscellaneous-configurations
1096 (defcustom reftex-keep-temporary-buffers t
1097 "*Non-nil means, keep any TeX and BibTeX files loaded for lookup.
1098 Nil means, kill it immediately after use unless it was already an existing
1099 buffer before the lookup happened. It is faster to keep the buffers, but can
1100 use a lot of memory, depending on the size of your database and document."
1101 :group 'reftex-miscellaneous-configurations
1104 (defcustom reftex-auto-show-entry t
1105 "*Non-nil means, showing context in another window may unhide a section.
1106 This is important when using outline-minor-mode. If the context to be shown
1107 is in a hidden section, RefTeX will issue a \"show-entry\" command in order
1108 to show it. This is not reversed when the label is selected - so the section
1109 remains shown after command completion."
1110 :group 'reftex-miscellaneous-configurations
1113 ;;; End of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1115 ;;;===========================================================================
1117 ;;; Define the formal stuff for a minor mode named RefTeX.
1120 (defvar reftex-mode nil
1121 "Determines if RefTeX minor mode is active.")
1122 (make-variable-buffer-local 'reftex-mode)
1124 (defvar reftex-mode-map (make-sparse-keymap)
1125 "Keymap for RefTeX minor mode.")
1127 (defvar reftex-mode-menu nil)
1130 (defun turn-on-reftex ()
1131 "Turn on RefTeX minor mode."
1135 (defun reftex-mode (&optional arg)
1136 "Minor mode with distinct support for \\label, \\ref and \\cite in LaTeX.
1138 Labels can be created with `\\[reftex-label]' and referenced with `\\[reftex-reference]'.
1139 When referencing, you get a menu with all labels of a given type and
1140 context of the label definition. The selected label is inserted as a
1143 Citations can be made with `\\[reftex-citation]' which will use a regular expression
1144 to pull out a *formatted* list of articles from your BibTeX
1145 database. The selected citation is inserted as a \\cite macro.
1147 A Table of Contents of the entire (multifile) document with browsing
1148 capabilities is available with `\\[reftex-toc]'.
1150 Most command have help available on the fly. This help is accessed by
1151 pressing `?' to any prompt mentioning this feature.
1153 Extensive documentation about reftex is in the file header of `reftex.el'.
1156 Under X, these functions will also be available in a menu on the menu bar.
1158 ------------------------------------------------------------------------------"
1161 (setq reftex-mode (not (or (and (null arg) reftex-mode)
1162 (<= (prefix-numeric-value arg) 0))))
1164 ; Add or remove the menu, and run the hook
1167 (easy-menu-add reftex-mode-menu)
1168 (reftex-plug-into-AUCTeX)
1169 (run-hooks 'reftex-mode-hook))
1170 (easy-menu-remove reftex-mode-menu)))
1172 (or (assoc 'reftex-mode minor-mode-alist)
1173 (setq minor-mode-alist
1174 (cons '(reftex-mode " Ref") minor-mode-alist)))
1176 (or (assoc 'reftex-mode minor-mode-map-alist)
1177 (setq minor-mode-map-alist
1178 (cons (cons 'reftex-mode reftex-mode-map)
1179 minor-mode-map-alist)))
1190 ;;; ===========================================================================
1192 ;;; Silence warnings about variables in other packages.
1194 (defvar LaTeX-label-function)
1195 (defvar tex-main-file)
1196 (defvar outline-minor-mode)
1198 ;;; ===========================================================================
1200 ;;; Interfaces for other packages
1201 ;;; -----------------------------
1206 (defun reftex-arg-label (optional &optional prompt definition)
1207 "Use `reftex-label' to create label. Insert it with `TeX-argument-insert'.
1208 This function is intended for AUCTeX macro support."
1209 (let ((label (reftex-label nil t)))
1210 (if (and definition (not (string-equal "" label)))
1211 (LaTeX-add-labels label))
1212 (TeX-argument-insert label optional optional)))
1214 (defun reftex-arg-ref (optional &optional prompt definition)
1215 "Use `reftex-reference' to select label. Insert with `TeX-argument-insert'.
1216 This function is intended for AUCTeX macro support."
1217 (let ((label (reftex-reference nil t)))
1218 (if (and definition (not (string-equal "" label)))
1219 (LaTeX-add-labels label))
1220 (TeX-argument-insert label optional optional)))
1222 (defun reftex-arg-cite (optional &optional prompt definition)
1223 "Use reftex-citation to select a key. Insert with `TeX-argument-insert'.
1224 This function is intended for AUCTeX macro support."
1225 (let ((key (reftex-citation nil t)))
1226 (TeX-argument-insert (or key "") optional optional)))
1228 (defun reftex-plug-into-AUCTeX ()
1229 ;; Replace AucTeX functions with RefTeX functions.
1230 ;; Which functions are replaced is controlled by the variable
1231 ;; `reftex-plug-into-AUCTeX'.
1233 (cond ((eq reftex-plug-into-AUCTeX t) '(t t t t))
1234 ((eq reftex-plug-into-AUCTeX nil) '(nil nil nil nil))
1235 (t reftex-plug-into-AUCTeX))))
1238 (boundp 'LaTeX-label-function)
1239 (setq LaTeX-label-function 'reftex-label))
1242 (fboundp 'TeX-arg-label)
1243 (fset 'TeX-arg-label 'reftex-arg-label))
1246 (fboundp 'TeX-arg-ref)
1247 (fset 'TeX-arg-ref 'reftex-arg-ref))
1250 (fboundp 'TeX-arg-cite)
1251 (fset 'TeX-arg-cite 'reftex-arg-cite))))
1254 (defvar reftex-label-alist-external-add-ons nil
1255 "List of label alist entries added with reftex-add-to-label-alist.")
1258 (defun reftex-add-to-label-alist (entry-list)
1259 "Add label environment descriptions to `reftex-label-alist-external-add-ons'.
1260 The format of ENTRY-LIST is exactly like `reftex-label-alist'. See there
1262 This function makes it possible to support RefTeX from AUCTeX style files.
1263 The entries in ENTRY-LIST will be processed after the user settings in
1264 `reftex-label-alist', and before the defaults (specified in
1265 `reftex-default-label-alist-entries'). Any changes made to
1266 `reftex-label-alist-external-add-ons' will raise a flag to the effect that a
1267 mode reset is done on the next occasion."
1270 (setq entry (car entry-list)
1271 entry-list (cdr entry-list))
1272 (if (not (member entry reftex-label-alist-external-add-ons))
1273 (setq reftex-tables-dirty t
1274 reftex-label-alist-external-add-ons
1275 (cons entry reftex-label-alist-external-add-ons))))))
1277 ;;; ===========================================================================
1279 ;;; Multifile support
1281 ;;; Technical notes: Multifile works as follows: We keep just one list
1282 ;;; of labels for each master file - this can save a lot of memory.
1283 ;;; `reftex-master-index-list' is an alist which connects the true file name
1284 ;;; of each master file with the symbols holding the information on that
1285 ;;; document. Each buffer has local variables which point to these symbols.
1287 ;; List of variables which handle the multifile stuff.
1288 ;; This list is used to tie, untie, and reset these symbols.
1289 (defconst reftex-multifile-symbols
1290 '(reftex-label-numbers-symbol reftex-list-of-labels-symbol
1291 reftex-bibfile-list-symbol))
1293 ;; Alist connecting master file names with the corresponding lisp symbols.
1294 (defvar reftex-master-index-list nil)
1296 ;; Last index used for a master file.
1297 (defvar reftex-multifile-index 0)
1299 ;; Alist connecting a master file with all included files.
1300 (defvar reftex-master-include-list nil)
1302 ;; Variable holding the symbol with current value of label postfix.
1303 (defvar reftex-label-numbers-symbol nil )
1304 (make-variable-buffer-local 'reftex-label-numbers-symbol)
1306 ;; Variable holding the symbol with the label list of the document.
1307 ;; Each element of the label list is again a list with the following elements:
1308 ;; 0: One character label type indicator.
1309 ;; 1: Short context to put into label menu.
1311 ;; 3: The name of the file where the label is defined.
1312 (defvar reftex-list-of-labels-symbol nil)
1313 (make-variable-buffer-local 'reftex-list-of-labels-symbol)
1315 ;; Variable holding the symbol with a list of library files for this document.
1316 (defvar reftex-bibfile-list-symbol nil)
1317 (make-variable-buffer-local 'reftex-bibfile-list-symbol)
1319 (defun reftex-next-multifile-index ()
1320 ;; Return the next free index for multifile symbols.
1321 (setq reftex-multifile-index (1+ reftex-multifile-index)))
1323 (defun reftex-tie-multifile-symbols ()
1324 ;; Tie the buffer-local symbols to globals connected with the master file.
1325 ;; If the symbols for the current master file do not exist, they are created.
1327 (let* ((master (file-truename (reftex-TeX-master-file)))
1328 (index (assoc master reftex-master-index-list))
1329 (symlist reftex-multifile-symbols)
1333 ;; Find the correct index.
1336 (setq index (cdr index))
1337 ;; Get a new index and add info to the alist.
1338 (setq index (reftex-next-multifile-index)
1339 reftex-master-index-list (cons
1341 reftex-master-index-list)
1344 ;; Get/create symbols and tie them.
1346 (setq symbol (car symlist)
1347 symlist (cdr symlist)
1348 symname (symbol-name symbol))
1349 (set symbol (intern (concat symname "-" (int-to-string index))))
1350 ;; Initialize if new symbols.
1351 (if newflag (set (symbol-value symbol) nil)))
1353 ;; Return t if the symbols did already exist, nil when we've made them.
1356 (defun reftex-untie-multifile-symbols ()
1357 ;; Remove ties from multifile symbols, so that next use makes new ones.
1358 (let ((symlist reftex-multifile-symbols)
1361 (setq symbol (car symlist)
1362 symlist (cdr symlist))
1365 (defun reftex-TeX-master-file ()
1366 ;; Return the name of the master file associated with the current buffer.
1367 ;; When AUCTeX is loaded, we will use it's more sophisticated method.
1368 ;; We also support the default TeX and LaTeX modes by checking for a
1369 ;; variable tex-main-file.
1374 ((fboundp 'TeX-master-file) ; AUCTeX is loaded. Use its mechanism.
1375 (TeX-master-file t))
1376 ((boundp 'TeX-master) ; The variable is defined - lets use it.
1380 ((eq TeX-master 'shared)
1381 (setq TeX-master (read-file-name "Master file: "
1385 (setq TeX-master (read-file-name "Master file: "
1387 ((boundp 'tex-main-file)
1388 ;; This is the variable from the default TeX modes.
1390 ((stringp tex-main-file)
1391 ;; ok, this must be it
1394 ;; In this case, the buffer is its own master.
1395 (buffer-file-name))))
1397 ;; Know nothing about master file. Assume this is a master file.
1398 (buffer-file-name)))))
1401 (error "Need a filename for this buffer. Please save it first."))
1402 ((or (file-exists-p master)
1403 (reftex-get-buffer-visiting master))
1404 ;; We either see the file, or have a buffer on it. OK.
1406 ((or (file-exists-p (concat master ".tex"))
1407 (reftex-get-buffer-visiting (concat master ".tex")))
1408 ;; Ahh, an extra .tex was missing...
1409 (setq master (concat master ".tex")))
1411 ;; Something is wrong here. Throw an exception.
1412 (error "No such master file %s" master)))
1413 (expand-file-name master)))
1415 (defun reftex-make-master-buffer (master-file)
1416 ;; Make a master buffer which contains the MASTER-FILE and all includes.
1417 ;; This is to prepare a buffer containing the entire document in correct
1418 ;; sequence for parsing.
1419 ;; After making the buffer, it runs reftex-make-master-buffer-hook.
1420 ;; The function returns the number of input/include files not found.
1422 (let ((not-found 0) file file1
1423 file-list dir-list tmp
1424 (this-syntax-table (syntax-table))
1426 (default-major-mode 'fundamental-mode)
1427 (after-insert-file-functions nil))
1429 ;; Set up the buffer with correct syntax table for parsing a tex buffer.
1430 ;; We do not use the mode because that may involve heavy stuff
1431 ;; like font-lock etc.
1432 (switch-to-buffer "*RefTeX Master*")
1434 (set-syntax-table this-syntax-table)
1436 ;; First insert the master file.
1437 (if (not (file-exists-p master-file))
1438 (error "No such master file: %s" master-file))
1439 (reftex-insert-buffer-or-file master-file)
1440 (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
1441 (setq file-list (cons master-file file-list))
1444 ;; Remember from which file these lines came.
1445 (put-text-property (point-min) (point-max) 'file
1446 (expand-file-name master-file))
1448 ;; Make the default directory that of the master file.
1449 ;; All input and include stuff works relative to that directory.
1450 (cd (file-name-directory (expand-file-name master-file)))
1452 ;; Create the list of directories from the TEXINPUTS environment variable
1453 (setq dir-list (cons default-directory
1454 (reftex-split (concat path-separator "+")
1455 (or (getenv "TEXINPUTS") ""))))
1457 ;; Now find recursively all include/input statements and expand them.
1460 "^[ \t]*\\\\\\(include\\|input\\)[{ \t]+\\([^} \t\n\r]+\\)[} \t\n\r]"
1462 (setq file (reftex-no-props (match-string 2)))
1463 (if (not (and (> (length file) 4)
1464 (string= (substring file -4) ".tex")))
1465 (setq file (concat file ".tex")))
1467 (if (setq file (car (reftex-find-files-on-path (list file) dir-list)))
1470 (format "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% START OF %s FILE: %s\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% END OF %s FILE: %s\n"
1471 (match-string 1) file
1472 (match-string 1) file))
1473 (beginning-of-line 0)
1474 (narrow-to-region (point) (point))
1476 (reftex-insert-buffer-or-file file)
1477 (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
1478 (setq file-list (cons (expand-file-name file) file-list))
1479 ;; Remember from which file these lines came.
1480 (put-text-property (point-min) (point-max)
1481 'file (expand-file-name file))
1482 (goto-char (point-min))
1484 (message "Input/include file %s not found. Ignored. Continuing..."
1486 (setq not-found (1+ not-found))))
1487 (setq file-list (nreverse file-list))
1488 (while (setq tmp (assoc (car file-list) reftex-master-include-list))
1489 (setq reftex-master-include-list (delq tmp reftex-master-include-list)))
1490 (setq reftex-master-include-list
1491 (cons file-list reftex-master-include-list))
1494 (run-hooks 'reftex-make-master-buffer-hook)
1498 (defun reftex-insert-buffer-or-file (file)
1499 "If there is a buffer associated with FILE, insert it - otherwise the FILE."
1500 (let ((buffer (reftex-get-buffer-visiting file)))
1502 (let (beg end beg1 end1)
1504 ;; Make sure we get the whole buffer.
1506 (setq beg (point-min) end (point-max))
1508 (setq beg1 (point-min) end1 (point-max)))
1509 (insert-buffer-substring buffer beg1 end1)
1512 (narrow-to-region beg end)))
1513 (insert-file-contents file))))
1516 (defun reftex-parse-document (&optional buffer)
1517 "Rescan the document."
1519 (save-window-excursion
1522 (if (not (bufferp buffer))
1523 (error "No such buffer %s" (buffer-name buffer))
1524 (set-buffer buffer)))
1525 (reftex-access-scan-info t))))
1527 (defun reftex-access-scan-info (&optional rescan)
1528 ;; Access the scanning info. When the multifile symbols are not yet tied,
1529 ;; tie them. When they are have to be created, do a buffer scan to
1532 ;; If RESCAN is non-nil, enforce document scanning
1535 (let ((rescan (or (equal rescan t) (equal rescan '(4)))))
1537 ;; Reset the mode if we had changes from style hooks.
1538 (and reftex-tables-dirty
1539 (reftex-reset-mode))
1541 (if (eq reftex-list-of-labels-symbol nil)
1542 ;; Symbols are not yet tied: Tie them and see if they are set.
1543 (reftex-tie-multifile-symbols))
1545 (if (and (symbol-value reftex-list-of-labels-symbol)
1547 ;; Lists do already exist and we don't need to rescan.
1548 ;; Return from here.
1551 ;; We need to rescan
1552 ;; =================
1555 (save-window-excursion
1560 (let ((label-list-symbol reftex-list-of-labels-symbol)
1561 (label-numbers-symbol reftex-label-numbers-symbol)
1562 (bibfile-list-symbol reftex-bibfile-list-symbol))
1564 (message "Creating master buffer...")
1565 (reftex-make-master-buffer (reftex-TeX-master-file))
1567 (message "Scanning document...")
1569 (reftex-scan-buffer-for-labels
1570 label-numbers-symbol label-list-symbol)
1572 (reftex-scan-buffer-for-bibliography-statement
1573 bibfile-list-symbol)
1575 (message "Scanning document... done"))))
1577 (if (get-buffer "*RefTeX Master*")
1578 (kill-buffer "*RefTeX Master*"))))))
1580 (defun reftex-create-tags-file ()
1581 "Create TAGS file by running `etags' on the current document.
1582 The TAGS file is also immediately visited with `visit-tags-table'."
1584 (reftex-access-scan-info current-prefix-arg)
1585 (let* ((master (reftex-TeX-master-file))
1586 (files (assoc master reftex-master-include-list))
1587 (cmd (format "etags %s" (mapconcat 'identity files " "))))
1589 (set-buffer (reftex-get-buffer-visiting master))
1590 (message "Running etags to create TAGS file...")
1592 (visit-tags-table "TAGS"))))
1594 ;; History of grep commands.
1595 (defvar reftex-grep-history nil)
1596 (defvar reftex-grep-command "grep -n "
1597 "Last grep command used in \\[reftex-grep-document]; default for next grep.")
1599 (defun reftex-grep-document (grep-cmd)
1600 "Run grep query through all files related to this document.
1601 With prefix arg, force to rescan document.
1602 This works also without an active TAGS table."
1605 (list (read-from-minibuffer "Run grep on document (like this): "
1606 reftex-grep-command nil nil
1607 'reftex-grep-history)))
1608 (reftex-access-scan-info current-prefix-arg)
1609 (let* ((master (reftex-TeX-master-file))
1610 (default-directory (file-name-directory master))
1611 (re (format "\\`%s\\(.*\\)" (regexp-quote
1612 (expand-file-name default-directory))))
1613 (files (assoc master reftex-master-include-list))
1616 (mapconcat (function (lambda (x)
1617 (if (string-match re x)
1623 (defun reftex-search-document (&optional regexp)
1624 "Regexp search through all files of the current TeX document.
1625 Starts always in the master file. Stops when a match is found.
1626 To continue searching for next match, use command \\[tags-loop-continue].
1627 This works also without an active TAGS table."
1629 (let ((default (reftex-this-word)))
1631 (setq regexp (read-string (format "Search regexp in document [%s]: "
1633 (if (string= regexp "") (setq regexp (regexp-quote default)))
1635 (reftex-access-scan-info current-prefix-arg)
1636 (tags-search regexp (list 'assoc (reftex-TeX-master-file)
1637 'reftex-master-include-list))))
1639 (defun reftex-query-replace-document (&optional from to delimited)
1640 "Run a query-replace-regexp of FROM with TO over the entire TeX document.
1641 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
1642 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1643 with the command \\[tags-loop-continue].
1644 This works also without an active TAGS table."
1646 (let ((default (reftex-this-word)))
1649 (setq from (read-string (format "Replace regexp in document [%s]: "
1651 (if (string= from "") (setq from (regexp-quote default)))))
1653 (setq to (read-string (format "Replace regexp %s with: " from))))
1654 (reftex-access-scan-info current-prefix-arg)
1655 (tags-query-replace from to (or delimited current-prefix-arg)
1656 (list 'assoc (reftex-TeX-master-file)
1657 'reftex-master-include-list))))
1659 (defun reftex-change-label (&optional from to)
1660 "Query replace FROM with TO in all \\label and \\ref commands.
1661 Works on the entire multifile document.
1662 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1663 with the command \\[tags-loop-continue].
1664 This works also without an active TAGS table."
1666 (let ((default (reftex-this-word "-a-zA-Z0-9_*.:")))
1668 (setq from (read-string (format "Replace label globally [%s]: "
1670 (if (string= from "") (setq from default))
1672 (setq to (read-string (format "Replace label %s with: "
1674 (reftex-query-replace-document
1675 (concat "\\\\\\(label\\|[a-z]*ref\\){" (regexp-quote from) "}")
1676 (format "\\\\\\1{%s}" to))))
1678 (defun reftex-this-word (&optional class)
1679 ;; Grab the word around point.
1680 (setq class (or class "-a-zA-Z0-9:_/.*;|"))
1682 (buffer-substring-no-properties
1683 (progn (skip-chars-backward class) (point))
1684 (progn (skip-chars-forward class) (point)))))
1686 ;;; ===========================================================================
1688 ;;; Functions to create and reference automatic labels.
1690 ;; The following constants are derived from `reftex-label-alist'.
1692 ;; Prompt used for label type querys directed to the user.
1693 (defconst reftex-type-query-prompt nil)
1695 ;; Help string for label type querys.
1696 (defconst reftex-type-query-help nil)
1698 ;; Alist relating label type to reference format.
1699 (defconst reftex-typekey-to-format-alist nil)
1701 ;; Alist relating label type to label affix.
1702 (defconst reftex-typekey-to-prefix-alist nil)
1704 ;; Alist relating environments or macros to label type and context regexp.
1705 (defconst reftex-env-or-mac-alist nil)
1707 ;; List of macros carrying a label.
1708 (defconst reftex-label-mac-list nil)
1710 ;; List of environments carrying a label.
1711 (defconst reftex-label-env-list nil)
1713 ;; List of all typekey letters in use.
1714 (defconst reftex-typekey-list nil)
1716 ;; Alist relating magic words to a label type.
1717 (defconst reftex-words-to-typekey-alist nil)
1719 ;; The last list-of-labels entry used in a reference.
1720 (defvar reftex-last-used-reference (list nil nil nil nil))
1722 ;; The regular expression used to abbreviate words.
1723 (defconst reftex-abbrev-regexp
1726 (make-string (nth 0 reftex-abbrev-parameters) ?.)
1727 "[" (nth 2 reftex-abbrev-parameters) "]*"
1729 "[" (nth 3 reftex-abbrev-parameters) "]"
1730 (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
1732 ;; Global variables used for communication between functions.
1733 (defvar reftex-default-context-position nil)
1734 (defvar reftex-location-start nil)
1735 (defvar reftex-call-back-to-this-buffer nil)
1737 ;; List of buffers created temporarily for lookup, which should be killed.
1738 (defvar reftex-buffers-to-kill nil)
1740 ;; Regexp to find section statements. Computed from reftex-section-levels.
1741 (defvar reftex-section-regexp nil)
1743 ;; LaTeX section commands and level numbers
1744 (defcustom reftex-section-levels
1750 ("subsubsection" . 4)
1752 ("subparagraph" . 6)
1753 ("subsubparagraph" . 7)
1755 "Commands and levels used for defining sections in the document.
1756 The car of each cons cell is the name of the section macro. The cdr is a
1757 number indicating its level."
1758 :group 'reftex-defining-label-environments
1759 :set 'reftex-set-dirty
1761 (cons (string :tag "sectioning macro" "")
1762 (number :tag "level " 0))))
1764 (defun reftex-label (&optional environment no-insert)
1765 "Insert a unique label. Return the label.
1766 If ENVIRONMENT is given, don't bother to find out yourself.
1767 If NO-INSERT is non-nil, do not insert label into buffer.
1768 With prefix arg, force to rescan document first.
1769 The label is also inserted into the label list.
1770 This function is controlled by the settings of reftex-insert-label-flags."
1773 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4).
1774 (reftex-access-scan-info current-prefix-arg)
1776 ;; Find out what kind of environment this is and abort if necessary.
1777 (if (or (not environment)
1778 (not (assoc environment reftex-env-or-mac-alist)))
1779 (setq environment (reftex-label-location)))
1780 (if (not environment)
1781 (error "Can't figure out what kind of label should be inserted"))
1784 (let (label typekey prefix
1785 entry format cell lab valid default force-prompt)
1786 (setq typekey (nth 1 (assoc environment reftex-env-or-mac-alist))
1787 format (nth 3 (assoc environment reftex-env-or-mac-alist)))
1788 (setq prefix (or (cdr (assoc typekey reftex-typekey-to-prefix-alist))
1789 (concat typekey "-")))
1790 ;; Replace any escapes in the prefix
1791 (setq prefix (reftex-replace-prefix-escapes prefix))
1793 ;; Make a default label.
1796 ((reftex-typekey-check typekey (nth 0 reftex-insert-label-flags))
1797 ;; Derive a label from context.
1798 (setq default (nth 2 (reftex-label-info " " nil nil t)))
1799 ;; Catch the cases where the is actually no context available.
1800 (if (or (string-match "NO MATCH FOR CONTEXT REGEXP" default)
1801 (string-match "ILLEGAL VALUE OF PARSE" default)
1802 (string-match "SECTION HEADING NOT FOUND" default)
1803 (string-match "HOOK ERROR" default)
1804 (string-match "^[ \t]*$" default))
1805 (setq default prefix
1806 force-prompt t) ; need to prompt
1807 (setq default (concat prefix (reftex-string-to-label default)))
1810 (setq default (reftex-uniquify-label default nil "-"))))
1812 ((reftex-typekey-check typekey (nth 1 reftex-insert-label-flags)) ; prompt
1813 ;; Minimal default: the user will be prompted.
1814 (setq default prefix))
1817 ;; Make an automatic label.
1818 (setq default (reftex-uniquify-label prefix t))))
1820 ;; Should we ask the user?
1821 (if (or (reftex-typekey-check typekey
1822 (nth 1 reftex-insert-label-flags)) ; prompt
1826 ;; iterate until we get a legal label
1828 (setq label (read-string "Label: " default))
1830 ;; Lets make sure that this is a legal label
1833 ;; Test if label contains strange characters
1834 ((string-match reftex-label-illegal-re label)
1835 (message "Label \"%s\" contains illegal characters" label)
1839 ;; Look it up in the label list
1840 ((setq entry (assoc label
1841 (symbol-value reftex-list-of-labels-symbol)))
1842 (message "Label \"%s\" exists in file %s" label (nth 3 entry))
1849 (setq label default))
1853 (insert (format format label)))
1855 ;; Insert the label into the label list
1856 (if (symbol-value reftex-list-of-labels-symbol)
1859 (all (symbol-value reftex-list-of-labels-symbol))
1863 (file (buffer-file-name)))
1865 ;; find the previous label in order to know where to insert new label
1868 (if (re-search-backward "\\\\[a-z]*label{\\([^}]+\\)}" nil 1 2)
1869 (setq look-for (reftex-no-props (match-string 1))))
1870 (if (or (re-search-forward
1871 "\\\\\\(include\\|input\\){[^}\n]+}" pos t)
1872 (re-search-forward reftex-section-regexp pos t)
1874 (setq note "POSITION UNCERTAIN. RESCAN TO FIX.")))
1876 (set reftex-list-of-labels-symbol
1877 (cons (list label typekey text file note)
1878 (symbol-value reftex-list-of-labels-symbol)))
1880 (setq cell (car all)
1884 (if (string= lab look-for)
1888 (symbol-value reftex-list-of-labels-symbol))
1889 (cons (list label typekey text file note)
1891 cnt (symbol-value reftex-list-of-labels-symbol))))
1892 ;; to end the loop, set all to nil
1893 (setq all nil)))))))
1894 ;; return value of the function is the label
1897 (defun reftex-string-to-label (string)
1898 ;; Convert a string (a sentence) to a label.
1900 ;; Uses reftex-derive-label-parameters and reftex-abbrev-parameters
1903 (let* ((words0 (reftex-split "[- \t\n\r]+"
1904 (reftex-no-props string)))
1905 (ignore-words (nth 5 reftex-derive-label-parameters))
1908 ;; remove words from the ignore list or with funny characters
1910 (setq word (car words0) words0 (cdr words0))
1912 ((member (downcase word) ignore-words))
1913 ((string-match reftex-label-illegal-re word)
1914 (if (nth 2 reftex-derive-label-parameters)
1916 (while (string-match reftex-label-illegal-re word)
1917 (setq word (replace-match "" nil nil word)))
1918 (setq words (cons word words)))))
1920 (setq words (cons word words)))))
1921 (setq words (nreverse words))
1923 ;; restrict number of words
1924 (if (> (length words) (nth 0 reftex-derive-label-parameters))
1925 (setcdr (nthcdr (1- (nth 0 reftex-derive-label-parameters)) words) nil))
1927 ;; First, try to use all words
1928 (setq string (mapconcat '(lambda(w) w) words
1929 (nth 4 reftex-derive-label-parameters)))
1931 ;; Abbreviate words if enforced by user settings or string length
1932 (if (or (eq t (nth 3 reftex-derive-label-parameters))
1933 (and (nth 3 reftex-derive-label-parameters)
1934 (> (length string) (nth 1 reftex-derive-label-parameters))))
1937 '(lambda (w) (if (string-match reftex-abbrev-regexp w)
1941 string (mapconcat '(lambda(w) w) words
1942 (nth 4 reftex-derive-label-parameters))))
1944 ;; Shorten if still to long
1946 (if (> (length string) (nth 1 reftex-derive-label-parameters))
1947 (substring string 0 (nth 1 reftex-derive-label-parameters))
1950 ;; Delete the final punctuation, if any
1951 (if (string-match "[^a-zA-Z0-9]+$" string)
1952 (setq string (replace-match "" nil nil string)))
1955 (defun reftex-replace-prefix-escapes (prefix)
1956 ;; Replace %escapes in a label prefix
1958 (let (letter (num 0) replace)
1959 (while (string-match "\\%\\([a-zA-Z]\\)" prefix num)
1960 (setq letter (match-string 1 prefix))
1964 (file-name-sans-extension
1965 (file-name-nondirectory (buffer-file-name))))
1967 (let ((masterdir (file-name-directory (reftex-TeX-master-file)))
1968 (file (file-name-sans-extension (buffer-file-name))))
1969 (if (string-match (concat "\\`" (regexp-quote masterdir))
1971 (substring file (length masterdir))
1974 (or (user-login-name) ""))
1976 (setq num (1- (+ (match-beginning 1) (length replace)))
1977 prefix (replace-match replace nil nil prefix)))
1980 (defun reftex-label-location (&optional bound)
1981 ;; Return the environment or macro which determines the label type at point.
1982 ;; If optional BOUND is an integer, limit backward searches to that point.
1984 (let* ((loc1 (reftex-what-macro reftex-label-mac-list bound))
1985 (loc2 (reftex-what-environment reftex-label-env-list bound))
1986 (p1 (or (cdr loc1) 0))
1987 (p2 (or (cdr loc2) 0)))
1989 (setq reftex-location-start (max p1 p2))
1992 (setq reftex-default-context-position p1)
1994 (setq reftex-default-context-position
1995 (+ p2 8 (length (car loc2))))
1996 (or (car loc2) "section"))))
1999 (defun reftex-uniquify-label (label &optional force separator)
2000 ;; Make label unique by appending a number.
2001 ;; Optional FORCE means, force appending a number, even if label is unique.
2002 ;; Optional SEPARATOR is a string to stick between label and number.
2004 ;; Ensure access to scanning info
2005 (reftex-access-scan-info)
2009 (not (assoc label (symbol-value reftex-list-of-labels-symbol))))
2012 (let* ((cell (or (assoc label (symbol-value reftex-label-numbers-symbol))
2014 (set reftex-label-numbers-symbol
2015 (cons (cons label 0)
2016 (symbol-value reftex-label-numbers-symbol))))))
2017 (num (1+ (cdr cell)))
2018 (sep (or separator "")))
2019 (while (assoc (concat label sep (int-to-string num))
2020 (symbol-value reftex-list-of-labels-symbol))
2021 (setq num (1+ num)))
2023 (concat label sep (int-to-string num))))))
2025 ;; Help string for the reference label menu
2026 (defconst reftex-select-label-prompt
2027 "Select: [n]ext [p]revious [r]escan [ ]context [q]uit RET [?]HELP+more")
2029 (defconst reftex-select-label-help
2030 " AVAILABLE KEYS IN REFERENCE LABEL MENU
2031 ======================================
2032 n / p Go to next/previous label (Cursor motion works as well)
2033 C-s / C-r Search forward/backward. Use repeated C-s/C-r as in isearch.
2034 r / s Rescan document for labels / Switch label type
2035 t / # Toggle table of contents / Toggle counter mode
2036 c Toggle display of short context
2037 SPC Show full context for current label in other window
2038 f Toggle follow mode: other window will follow context
2039 l / q Reuse last referenced label / Quit without accepting label
2040 M-r Recursive Edit into other window
2041 RET Accept current label")
2043 (defun reftex-reference (&optional type no-insert)
2044 "Make a LaTeX reference. Look only for labels of a certain TYPE.
2045 With prefix arg, force to rescan buffer for labels. This should only be
2046 necessary if you have recently entered labels yourself without using
2047 reftex-label. Rescanning of the buffer can also be requested from the
2048 label selection menu.
2049 The function returns the selected label or nil.
2050 If NO-INSERT is non-nil, do not insert \\ref command, just return label.
2051 When called with 2 C-u prefix args, disable magic word recognition."
2055 ;; check for active recursive edits
2056 (reftex-check-recursive-edit)
2058 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
2059 (reftex-access-scan-info current-prefix-arg)
2062 ;; guess type from context
2063 (if (and reftex-guess-label-type
2064 (not (= 16 (prefix-numeric-value current-prefix-arg)))
2065 (setq type (assoc (downcase (reftex-word-before-point))
2066 reftex-words-to-typekey-alist)))
2067 (setq type (cdr type))
2068 (setq type (reftex-query-label-type))))
2071 (form (or (cdr (assoc type reftex-typekey-to-format-alist))
2074 ;; Have the user select a label
2075 (setq pair (reftex-offer-label-menu type))
2076 (setq label (car pair))
2081 ;; do we need to remove spaces?
2082 (if (string= "~" (substring form 0 1))
2083 (while (or (= (preceding-char) ?\ )
2084 (= (preceding-char) ?\C-i))
2085 (backward-delete-char 1)))
2086 ;; ok, insert the reference
2087 (insert (format form label label))
2093 (defun reftex-goto-label (&optional arg)
2094 "Go to a LaTeX label. With prefix ARG, go to label in another window."
2096 (let (type label file pair)
2098 (setq type (reftex-query-label-type)))
2100 (setq pair (reftex-offer-label-menu type)
2103 (if (and label file (file-exists-p file))
2106 (find-file-other-window file)
2108 (goto-char (point-min))
2109 (if (not (re-search-forward
2110 (concat "\\\\[a-z]*label{" (regexp-quote label) "}")
2112 (error "No such label found: %s" label)
2113 (reftex-highlight 0 (match-beginning 0) (match-end 0))
2114 (add-hook 'pre-command-hook 'reftex-highlight-shall-die)))
2118 ;; Internal list with index numbers of labels in the selection menu
2119 (defvar reftex-label-index-list nil)
2121 (defun reftex-offer-label-menu (typekey)
2122 ;; Offer a menu with the appropriate labels. Return (label . file).
2123 (let* ((buf (current-buffer))
2124 (near-label (reftex-find-nearby-label))
2125 (toc (reftex-typekey-check typekey reftex-label-menu-flags 0))
2126 (context (not (reftex-typekey-check
2127 typekey reftex-label-menu-flags 3)))
2128 (counter (reftex-typekey-check
2129 typekey reftex-label-menu-flags 2))
2130 (follow (reftex-typekey-check
2131 typekey reftex-label-menu-flags 4))
2132 (match-everywhere (reftex-typekey-check
2133 typekey reftex-label-menu-flags 6))
2134 offset rtn key cnt last-cnt entry)
2136 (setq reftex-call-back-to-this-buffer buf)
2137 (setq entry (cons nil nil))
2142 (save-window-excursion
2143 (switch-to-buffer-other-window "*RefTeX Select*")
2145 (setq truncate-lines t)
2146 (setq reftex-label-index-list (reftex-make-and-insert-label-list
2147 typekey buf toc context counter
2149 (setq near-label "_ ") ; turn off search for near label
2150 (setq offset (or (car reftex-label-index-list) offset))
2151 ;; use only when searched
2152 (setq reftex-label-index-list (cdr reftex-label-index-list))
2153 ;; only this is the true list
2154 (if (not reftex-label-index-list)
2155 (error "No labels of type \"%s\"" typekey))
2158 reftex-select-label-prompt
2161 reftex-select-label-help
2162 '(?r ?g ?c ?t ?s ?# ?l)
2164 'reftex-select-label-callback follow
2168 last-cnt (nth 2 rtn)
2169 offset (1+ (or cnt last-cnt)))
2170 (if (not key) (throw 'exit nil))
2175 (reftex-parse-document buf))
2177 ;; toggle context mode
2178 (setq context (not context)))
2181 (setq typekey (reftex-query-label-type)))
2183 ;; toggle tabel of contents display
2184 (setq toc (not toc)))
2186 ;; toggle counter display
2187 (setq counter (not counter)))
2189 ;; reuse the last referenced label again
2190 (setq entry reftex-last-used-reference)
2196 (setq entry (nth (nth cnt reftex-label-index-list)
2197 (symbol-value reftex-list-of-labels-symbol)))
2198 (setq reftex-last-used-reference entry))
2200 (throw 'exit t))))))
2201 (kill-buffer "*RefTeX Select*")
2202 (reftex-kill-temporary-buffers))
2203 (cons (reftex-no-props (nth 0 entry)) (nth 3 entry))))
2205 ;; Indentation for table of context lines in the menu
2206 (defconst reftex-toc-indent " ")
2207 ;; Indentation for the lines containing the label
2208 (defconst reftex-label-indent "> ")
2209 ;; Indentation for context lines
2210 (defconst reftex-context-indent ". ")
2211 ;; Indentation per section level
2212 (defvar reftex-level-indent 2
2213 "*Number of spaces to be used for indentation per section level.
2214 With more indentation, the label menu looks nicer, but shows less context.
2215 Changing this is only fully operational after the next buffer scan.")
2217 (defun reftex-make-and-insert-label-list (typekey0 buf toc context
2219 ;; Insert a menu of all labels in buffer BUF into current buffer.
2220 ;; Return the list of labels, with the index of NEAR-LABEL as extra car.
2221 (let (ins-list index-list offset)
2225 (font (reftex-use-fonts))
2229 (toc-indent reftex-toc-indent)
2231 (concat reftex-label-indent
2232 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
2234 (concat reftex-context-indent
2235 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
2236 cell text label typekey note comment)
2238 ; Ensure access to scanning info
2239 (reftex-access-scan-info)
2241 (setq all (symbol-value reftex-list-of-labels-symbol))
2245 (setq index (1+ index)
2249 (if (null (nth 2 cell))
2250 ;; No context yet. Quick update
2252 (setq cell (reftex-label-info-update cell))
2253 (setcar (nthcdr index
2254 (symbol-value reftex-list-of-labels-symbol))
2257 ;; in the following setq we *copy* the label, since we will change
2258 ;; its properties, and we cannot have any properties in the list
2259 ;; (because of assoc searches)
2260 (setq label (if (stringp (car cell))
2261 (copy-sequence (car cell))
2263 typekey (nth 1 cell)
2265 ;; file (nth 3 cell)
2267 comment (get-text-property 0 'in-comment text))
2269 (if (string= label near-label)
2270 (setq offset (1+ cnt)))
2273 ((and toc (string= typekey "toc"))
2275 (cons (concat toc-indent text "\n")
2277 ((string= typekey "toc"))
2278 ((and (or (string= typekey typekey0) (string= typekey0 " "))
2279 (or (nth 5 reftex-label-menu-flags) ; show-commented?
2282 (if comment (setq label (concat "% " label)))
2288 'font-lock-comment-face
2289 'font-lock-reference-face)
2291 (setq index-list (cons index index-list))
2296 (if counter (format " (%d) " cnt))
2297 (if comment " LABEL IS COMMENTED OUT ")
2298 (if note (concat " " note) "")
2300 (if context (concat context-indent text "\n")))
2302 (put-text-property 0 (length (car ins-list)) 'cnt (1- cnt)
2307 (apply 'insert (nreverse ins-list))
2308 (cons offset (nreverse index-list))))
2310 (defun reftex-query-label-type ()
2311 ;; Ask for label type
2312 (message reftex-type-query-prompt)
2313 (let ((key (read-char)))
2316 (save-window-excursion
2317 (with-output-to-temp-buffer "*RefTeX Help*"
2318 (princ reftex-type-query-help))
2319 (setq key (read-char))
2320 (kill-buffer "*RefTeX Help*"))))
2321 (if (not (member (char-to-string key) reftex-typekey-list))
2322 (error "No such label type: %s" (char-to-string key)))
2323 (char-to-string key)))
2325 (defun reftex-find-nearby-label ()
2326 ;; Find a nearby label.
2328 (if (or (re-search-backward "\\\\[a-z]*label{\\([^}]+\\)}" nil t)
2329 (re-search-forward "\\\\[a-z]*label{\\([^}]+\\)}" nil t))
2330 (reftex-no-props (match-string 1))
2333 ;; Variable holding the vector with section numbers
2334 (defvar reftex-section-numbers [0 0 0 0 0 0 0 0])
2336 (defun reftex-scan-buffer-for-labels (label-numbers-symbol label-list-symbol)
2337 ;; Scan the buffer for labels and save them in a list.
2339 (let ((regexp (concat "\\\\[a-z]*label{\\([^}]*\\)}" "\\|"
2340 reftex-section-regexp))
2341 (font (reftex-use-fonts))
2344 file (level 1) star text text1 label section-number macro find)
2345 (set label-list-symbol nil)
2348 ;; reset label numbers
2349 (set label-numbers-symbol nil)
2351 ;; reset section numbers
2352 (reftex-init-section-numbers reftex-section-numbers)
2354 (while (re-search-forward regexp nil t)
2355 (setq file (get-text-property (match-beginning 0) 'file))
2356 (if (match-string 1)
2359 (setq label (reftex-no-props (match-string 1)))
2360 (set label-list-symbol
2361 (cons (reftex-label-info label file bound)
2362 (symbol-value label-list-symbol))))
2365 (setq bound (point))
2366 (setq star (= ?* (char-after (match-end 2))))
2367 (setq find (buffer-substring-no-properties
2368 (1- (match-beginning 2)) (match-end 0)))
2369 (setq macro (reftex-no-props (match-string 2)))
2370 (setq level (cdr (assoc macro reftex-section-levels)))
2372 (setq section-number (reftex-section-number
2373 reftex-section-numbers level star))
2374 (setq highest-level (min highest-level level))
2375 (if (= level highest-level)
2377 "Scanning %s %s ..."
2378 (car (nth level reftex-section-levels))
2384 (setq text1 (reftex-context-substring))
2385 (setq text (reftex-nicify-text text1))))
2388 (reftex-allow-for-ctrl-m
2391 (char-after (+ (match-end 0) (length text1)))))))
2393 ;; add section number and indentation
2396 (make-string (* reftex-level-indent level) ?\ )
2397 (if (nth 1 reftex-label-menu-flags) ; section number flag
2398 (concat section-number " "))
2401 (if font (put-text-property 0 (length text)
2402 'face 'font-lock-comment-face text))
2405 (set label-list-symbol
2406 (cons (list 'toc "toc" text file find level section-number)
2407 (symbol-value label-list-symbol)))))
2408 (set label-list-symbol
2409 (nreverse (symbol-value label-list-symbol))))))
2411 (defun reftex-label-info-update (cell)
2412 ;; Update information about just one label in a different file.
2413 ;; CELL contains the old info list
2414 (let* ((label (nth 0 cell))
2415 (typekey (nth 1 cell))
2416 ;; (text (nth 2 cell))
2419 (buf (reftex-get-file-buffer-force
2420 file (not reftex-keep-temporary-buffers))))
2422 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")
2429 (if (re-search-forward (concat "\\\\[a-z]*label{"
2430 (regexp-quote label) "}")
2432 (append (reftex-label-info label file) (list note))
2433 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")))))))
2435 (defun reftex-label-info (label &optional file bound derive)
2436 ;; Return info list on LABEL at point.
2437 (let* ((env-or-mac (reftex-label-location bound))
2438 (typekey (nth 1 (assoc env-or-mac reftex-env-or-mac-alist)))
2439 (file (or file (buffer-file-name)))
2440 (parse (if (reftex-typekey-check
2441 typekey reftex-use-text-after-label-as-context)
2443 (nth 2 (assoc env-or-mac reftex-env-or-mac-alist))))
2444 (text (reftex-short-context env-or-mac parse reftex-location-start
2446 (if (reftex-in-comment)
2447 (put-text-property 0 1 'in-comment t text))
2448 (list label typekey text file)))
2450 (defun reftex-in-comment ()
2452 (skip-chars-backward "^%\n\r")
2453 (= (preceding-char) ?%)))
2455 (defun reftex-short-context (env parse &optional bound derive)
2456 ;; Get about one line of useful context for the label definition at point.
2459 (setq parse (if derive (cdr parse) (car parse))))
2467 (reftex-context-substring)))
2470 (if (string= env "section")
2471 ;; special treatment for section labels
2473 (if (re-search-backward reftex-section-regexp (point-min) t)
2475 (goto-char (match-end 0))
2476 (reftex-context-substring))
2477 "SECTION HEADING NOT FOUND"))
2479 (goto-char reftex-default-context-position)
2480 (reftex-context-substring))))
2484 (if (re-search-backward parse bound t)
2486 (goto-char (match-end 0))
2487 (reftex-context-substring))
2488 "NO MATCH FOR CONTEXT REGEXP")))
2492 (goto-char reftex-default-context-position)
2493 (reftex-nth-parens-substring parse)))
2496 ;; A hook function. Call it.
2498 (condition-case error-var
2500 (error (format "HOOK ERROR: %s" (cdr error-var))))))
2502 "ILLEGAL VALUE OF PARSE"))))
2504 (defun reftex-nth-parens-substring (n)
2505 ;; Return the nth following {} or [] parentheses content.
2506 ;; If we are sitting at a macro start, skip to ent of macro name.
2507 (and (eq (following-char) ?\\) (skip-chars-forward "a-zA-Z*\\\\"))
2509 ;; Skip parenthesis pairs.
2510 (while (and (> (setq n (1- n)) 0)
2511 (or (eq (following-char) ?{) (eq (following-char) ?\[))
2512 (condition-case nil (or (forward-list 1) t) (error nil))))
2513 (skip-chars-forward "{\\[")
2514 (reftex-context-substring))
2516 (defun reftex-context-substring ()
2517 ;; Return up to 100 chars from point
2518 ;; When point is just after a { or [, limit string to matching parenthesis
2520 ((or (= (preceding-char) ?\{)
2521 (= (preceding-char) ?\[))
2522 ;; Inside a list - get only the list.
2525 (min (+ 100 (point))
2531 (error (point-max))))))
2533 ;; no list - just grab 100 characters
2534 (buffer-substring (point) (min (+ 100 (point)) (point-max))))))
2536 (defun reftex-init-section-numbers (section-numbers &optional toc-entry)
2537 ;; Initialize the section numbers with zeros or with what is found
2538 ;; in the toc entry.
2539 (let* ((level (or (nth 5 toc-entry) -1))
2540 (numbers (nreverse (reftex-split "\\." (or (nth 6 toc-entry) ""))))
2541 (depth (1- (length section-numbers)))
2545 (aset section-numbers i 0)
2546 (aset section-numbers i (string-to-int (or (car numbers) "0")))
2547 (setq numbers (cdr numbers)))
2550 (defun reftex-section-number (section-numbers &optional level star)
2551 ;; Return a string with the current section number.
2552 ;; When LEVEL is non-nil, increase section numbers on that level.
2553 (let* ((depth (1- (length section-numbers))) idx n (string ""))
2556 (if (and (> level -1) (not star))
2557 (aset section-numbers level (1+ (aref section-numbers level))))
2558 (setq idx (1+ level))
2559 (while (<= idx depth)
2560 (aset section-numbers idx 0)
2561 (setq idx (1+ idx)))))
2563 (while (<= idx depth)
2564 (setq n (aref section-numbers idx))
2565 (setq string (concat string (if (not (string= string "")) "." "")
2567 (setq idx (1+ idx)))
2569 (if (string-match "\\`\\(0\\.\\)+" string)
2570 (setq string (replace-match "" nil nil string)))
2571 (if (string-match "\\(\\.0\\)+\\'" string)
2572 (setq string (replace-match "" nil nil string))))
2574 (concat (make-string (1- (length string)) ?\ ) "*")
2577 ;; A variable to remember the index of the last label context shown
2578 (defvar reftex-last-cnt 0)
2580 (defun reftex-select-label-callback (cnt)
2581 ;; Callback function called from the label selection in order to
2582 ;; show context in another window
2583 (let* ((this-window (selected-window))
2584 index entry label file buffer)
2585 ;; pop to original buffer in order to get correct variables
2588 (set-buffer reftex-call-back-to-this-buffer)
2589 (setq index (nth (or cnt 1) reftex-label-index-list)
2590 entry (nth index (symbol-value reftex-list-of-labels-symbol))
2592 file (nth 3 entry)))
2594 ;; goto the file in another window
2595 (setq buffer (reftex-get-file-buffer-force
2596 file (not reftex-keep-temporary-buffers)))
2598 ;; good - the file is available
2599 (switch-to-buffer-other-window buffer)
2600 ;; we have got a problem here. The file does not exist.
2601 ;; Let' get out of here..
2606 ;; search for that label
2607 (if (not (and (integerp cnt)
2608 (integerp reftex-last-cnt)
2609 (if (> cnt reftex-last-cnt)
2611 (concat "\\\\[a-z]*label{" (regexp-quote label)
2614 (concat "\\\\[a-z]*label{" (regexp-quote label)
2618 (re-search-forward (concat "\\\\[a-z]*label{"
2619 (regexp-quote label) "}") nil t)))
2620 (reftex-highlight 0 (match-beginning 0) (match-end 0))
2622 (recenter (/ (window-height) 2))
2623 (select-window this-window))))
2625 (defun reftex-pop-to-label (label file-list &optional mark-to-kill highlight)
2626 ;; Find LABEL in any file in FILE-LIST in another window.
2627 ;; If mark-to-kill is non-nil, mark new buffer for killing.
2628 ;; If HIGHLIGHT is non-nil, highlight the label definition.
2629 (let* ((re (concat "\\\\[a-z]*label{" (regexp-quote label) "}"))
2633 (setq file (car file-list)
2634 file-list (cdr file-list))
2635 (if (not (setq buf (reftex-get-file-buffer-force file mark-to-kill)))
2636 (error "No such file %s" file))
2639 (goto-char (point-min))
2640 (if (re-search-forward re nil t)
2642 (switch-to-buffer-other-window buf)
2643 (goto-char (match-beginning 0))
2644 (recenter (/ (window-height) 2))
2646 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
2647 (throw 'exit (selected-window)))))
2648 (error "Label %s not found" label))))
2650 (defun reftex-find-duplicate-labels ()
2651 "Produce a list of all duplicate labels in the document."
2655 ;; Rescan the document to make sure
2656 (reftex-access-scan-info t)
2658 (let ((master (reftex-TeX-master-file))
2664 ((memq (car x) '(toc bof eof)) nil)
2666 (setq x1 (reftex-all-assoc-string
2667 (car x) (symbol-value reftex-list-of-labels-symbol)))
2668 (if (< 1 (length x1))
2669 (append (list (reftex-no-props (car x)))
2671 (abbreviate-file-name (nth 3 x))) x1))
2673 (reftex-uniquify (symbol-value reftex-list-of-labels-symbol)))))
2674 (setq dlist (reftex-uniquify dlist))
2675 (if (null dlist) (error "No duplicate labels in document"))
2676 (switch-to-buffer-other-window "*Duplicate Labels*")
2677 (make-local-variable 'TeX-master)
2678 (setq TeX-master master)
2680 (insert " MULTIPLE LABELS IN CURRENT DOCUMENT:\n")
2681 (insert " Move point to label and type `M-x reftex-change-label'\n"
2682 " This will run a query-replace on the label and its references\n")
2683 (insert " LABEL FILE\n")
2684 (insert " -------------------------------------------------------------\n")
2686 (if (and (car (car dlist))
2689 (insert (mapconcat '(lambda(x) x) (car dlist) "\n ") "\n")))
2690 (setq dlist (cdr dlist)))
2691 (goto-char (point-min))))
2693 (defun reftex-all-assoc-string (key list)
2694 ;; Return a list of all associations of KEY in LIST. Comparison with string=
2697 (if (string= (car (car list)) key)
2698 (setq rtn (cons (car list) rtn)))
2699 (setq list (cdr list)))
2702 (defun reftex-kill-temporary-buffers ()
2703 ;; Kill all buffers in the list reftex-kill-temporary-buffers.
2704 (while reftex-buffers-to-kill
2705 (if (bufferp (car reftex-buffers-to-kill))
2707 (and (buffer-modified-p (car reftex-buffers-to-kill))
2708 (y-or-n-p (format "Save file %s? "
2710 (car reftex-buffers-to-kill))))
2712 (set-buffer (car reftex-buffers-to-kill))
2714 (kill-buffer (car reftex-buffers-to-kill))))
2715 (setq reftex-buffers-to-kill (cdr reftex-buffers-to-kill))))
2717 (defun reftex-show-entry ()
2718 ;; Show entry if point is hidden by outline mode
2719 (let ((pos (point)))
2720 (if (and reftex-auto-show-entry
2721 (boundp 'outline-minor-mode)
2723 (looking-at "[^\n\r]*\r"))
2725 (outline-back-to-heading)
2730 (defun reftex-nicify-text (text)
2731 ;; Make TEXT nice for inclusion into label menu
2732 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text) ; remove extra whitespace
2733 (setq text (replace-match " " nil t text)))
2734 (if (string-match "\\\\end{.*" text) ; nothing beyond \end{
2735 (setq text (replace-match "" nil t text)))
2736 (if (string-match "\\\\[a-z]*label{[^}]*}" text) ; kill the label
2737 (setq text (replace-match "" nil t text)))
2738 (if (string-match "^ +" text) ; leading whitespace
2739 (setq text (replace-match "" nil t text)))
2741 ((> (length text) 100) ; not to long
2742 (setq text (substring text 0 100)))
2743 ((= (length text) 0) ; not empty
2747 (defun reftex-typekey-check (typekey conf-variable &optional n)
2748 ;; Check if CONF-VARIABLE is true or contains TYPEKEY
2749 (and n (setq conf-variable (nth n conf-variable)))
2750 (or (eq conf-variable t)
2751 (and (stringp conf-variable)
2752 (string-match (concat "[" conf-variable "]") typekey))))
2754 ;;; ===========================================================================
2756 ;;; Table of contents (contributed from Stephen Eglen, changed by C. Dominik)
2758 ;; We keep at most one *toc* buffer - it is easy to make them
2760 (defvar reftex-last-toc-master nil
2761 "Stores the name of the tex file that `reftex-toc' was last run on.")
2763 (defvar reftex-last-toc-file nil
2764 "Stores the file name from which `reftex-toc' was called. For redo command.")
2766 (defvar reftex-last-window-height nil)
2768 (defvar reftex-toc-return-marker (make-marker)
2769 "Marker which makes it possible to return from toc to old position.")
2771 (defconst reftex-toc-help
2772 " AVAILABLE KEYS IN TOC BUFFER
2773 ============================
2774 SPC Show the corresponding section of the LaTeX document.
2775 TAB Goto the section.
2776 RET Goto the section and hide the *toc* buffer (also on mouse-2).
2777 q / Q Hide/Kill *toc* buffer, return to position of last reftex-toc command.
2778 f Toggle follow mode on and off.
2779 r / g Reparse the LaTeX document.")
2781 (defun reftex-toc ()
2782 "Show the table of contents for the current document.
2783 When called with a raw C-u prefix, rescan the document first."
2787 (if (or (not (string= reftex-last-toc-master (reftex-TeX-master-file)))
2789 (reftex-empty-toc-buffer))
2791 (setq reftex-last-toc-file (buffer-file-name))
2792 (setq reftex-last-toc-master (reftex-TeX-master-file))
2794 (set-marker reftex-toc-return-marker (point))
2796 ;; If follow mode is active, arrange to delay it one command
2797 (if reftex-toc-follow-mode
2798 (setq reftex-toc-follow-mode 1))
2800 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
2801 (reftex-access-scan-info current-prefix-arg)
2803 (let* ((all (symbol-value reftex-list-of-labels-symbol))
2804 (where (reftex-nearest-section))
2805 toc toc1 cell label file find startpos)
2807 (if (get-buffer-window "*toc*")
2808 (select-window (get-buffer-window "*toc*"))
2809 (setq reftex-last-window-height (window-height)) ; remember
2810 (split-window-vertically)
2811 (switch-to-buffer (get-buffer-create "*toc*")))
2814 ;; buffer is empty - fill it with the table of contents
2815 ((= (buffer-size) 0)
2817 (local-set-key "?" 'reftex-toc-show-help)
2818 (local-set-key " " 'reftex-toc-view-line)
2819 (local-set-key "\C-m" 'reftex-toc-goto-line-and-hide)
2820 (local-set-key "\C-i" 'reftex-toc-goto-line)
2821 (local-set-key "r" 'reftex-toc-redo)
2822 (local-set-key "g" 'revert-buffer)
2823 (local-set-key "q" 'reftex-toc-quit)
2824 (local-set-key "Q" 'reftex-toc-quit-and-kill)
2825 (local-set-key "f" 'reftex-toc-toggle-follow)
2826 (local-set-key [(mouse-2)] 'reftex-toc-mouse-goto-line-and-hide); Emacs
2827 (local-set-key [(button2)] 'reftex-toc-mouse-goto-line-and-hide); XEmacs
2828 (make-local-variable 'revert-buffer-function)
2829 (setq revert-buffer-function 'reftex-toc-redo)
2830 (setq truncate-lines t)
2831 (make-local-hook 'post-command-hook)
2832 (make-local-hook 'pre-command-hook)
2833 (setq post-command-hook '(reftex-toc-post-command-hook))
2834 (setq pre-command-hook '(reftex-toc-pre-command-hook))
2837 "TABLE-OF-CONTENTS on %s
2838 SPC=view TAB=goto RET=goto+hide [q]uit [r]escan [f]ollow-mode [?]Help
2839 -------------------------------------------------------------------------------
2840 " (abbreviate-file-name reftex-last-toc-master)))
2841 (setq startpos (point))
2843 (if (reftex-use-fonts)
2844 (put-text-property 1 (point) 'face 'font-lock-keyword-face))
2845 (put-text-property 1 (point) 'intangible t)
2848 (setq cell (car all)
2850 (setq label (nth 0 cell)
2856 (setq toc1 (concat toc "\n"))
2857 (put-text-property 0 (length toc1)
2859 (put-text-property 0 (length toc1)
2864 (backward-delete-char 1)
2866 (setq buffer-read-only t))
2870 (setq startpos (point))))
2872 ;; Find the correct section
2873 (goto-char (point-max))
2875 (while (and (> (point) startpos)
2876 (or (not (string= (get-text-property (point) 'file)
2878 (not (string= (get-text-property (point) 'find)
2880 (beginning-of-line 0))))
2882 (defun reftex-nearest-section ()
2883 ;; Return (file . find) of nearest section command
2884 (let (cell label rest pos text1 text2)
2887 ;; Try to find a section heading
2888 ((or (re-search-backward reftex-section-regexp nil t)
2889 (re-search-forward reftex-section-regexp nil t))
2890 (goto-char (match-end 0))
2892 text1 (buffer-substring-no-properties
2893 (1- (match-beginning 1)) (match-end 0))
2894 text2 (reftex-context-substring))
2895 (cons (buffer-file-name)
2896 (reftex-allow-for-ctrl-m
2899 (char-after (+ pos (length text2))))))))
2900 ;; Try to find a label
2901 ((and (or (re-search-backward "\\\\[a-z]*label{\\([^}]+\\)}" nil t)
2902 (re-search-forward "\\\\[a-z]*label{\\([^}]+\\)}" nil t))
2903 (setq label (reftex-no-props (match-string 1)))
2904 (setq cell (assoc label (symbol-value
2905 reftex-list-of-labels-symbol)))
2906 (setq rest (memq cell (symbol-value reftex-list-of-labels-symbol)))
2907 (setq cell (car (memq (assoc nil rest) rest)))
2909 (cons (nth 3 cell) (nth 4 cell)))
2912 (defun reftex-toc-pre-command-hook ()
2913 ;; used as pre command hook in *toc* buffer
2914 (reftex-unhighlight 0)
2915 (reftex-unhighlight 1))
2917 (defun reftex-toc-post-command-hook ()
2918 ;; used in the post-command-hook for the *toc* buffer
2922 (progn (beginning-of-line) (point))
2923 (progn (end-of-line) (point)))))
2925 ((integerp reftex-toc-follow-mode)
2926 ;; remove delayed action
2927 (setq reftex-toc-follow-mode t))
2928 (reftex-toc-follow-mode
2929 ;; show context in other window
2931 (reftex-toc-visit-line)
2932 (error (ding) t)))))
2934 (defun reftex-empty-toc-buffer ()
2935 (if (get-buffer "*toc*")
2937 (set-buffer "*toc*")
2938 (setq buffer-read-only nil)
2941 (defun reftex-re-enlarge ()
2943 (max 0 (- (or reftex-last-window-height (window-height))
2946 (defun reftex-toc-show-help ()
2948 (with-output-to-temp-buffer "*RefTeX Help*"
2949 (princ reftex-toc-help))
2950 ;; If follow mode is active, arrange to delay it one command
2951 (if reftex-toc-follow-mode
2952 (setq reftex-toc-follow-mode 1)))
2954 (defun reftex-toc-toggle-follow ()
2955 "Toggle toc-follow mode.
2956 (It is not really a mode, just a flag)."
2958 (setq reftex-toc-follow-mode (not reftex-toc-follow-mode)))
2959 (defun reftex-toc-view-line ()
2960 "View document location in other window."
2962 (reftex-toc-visit-line))
2963 (defun reftex-toc-goto-line-and-hide ()
2964 "Go to document location in other window. Hide the *toc* window."
2966 (reftex-toc-visit-line 'hide))
2967 (defun reftex-toc-goto-line ()
2968 "Go to document location in other window. Hide the *toc* window."
2970 (reftex-toc-visit-line t))
2971 (defun reftex-toc-mouse-goto-line-and-hide (ev)
2972 "Go to document location in other window. Hide the *toc* window."
2974 (mouse-set-point ev)
2975 (reftex-toc-visit-line 'hide))
2976 (defun reftex-toc-quit ()
2977 "Hide the *toc* window and do not move point."
2979 (or (one-window-p) (delete-window))
2980 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
2982 (goto-char (marker-position reftex-toc-return-marker)))
2983 (defun reftex-toc-quit-and-kill ()
2984 "Kill the *toc* buffer."
2986 (kill-buffer "*toc*")
2987 (or (one-window-p) (delete-window))
2988 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
2990 (goto-char (marker-position reftex-toc-return-marker)))
2991 (defun reftex-toc-redo (&rest ignore)
2992 "Regenerate the *toc* buffer. Call only from within the *toc* buffer"
2994 (switch-to-buffer-other-window
2995 (reftex-get-file-buffer-force reftex-last-toc-file))
2996 (setq current-prefix-arg '(4))
2999 (defun reftex-toc-visit-line (&optional final)
3000 ;; Visit the tex file corresponding to the toc entry on the current line.
3001 ;; If FINAL is t, stay there
3002 ;; If FINAL is 'hide, hide the *toc* window.
3003 ;; Otherwise, move cursor back into *toc* window
3005 (let (file find beg end (toc-window (selected-window))
3006 show-window show-buffer)
3013 ;; get the file and the search string
3014 (setq file (get-text-property (point) 'file))
3015 (setq find (get-text-property (point) 'find))
3016 (if (or (not file) (not find))
3017 (error "Cannot visit line"))
3019 (switch-to-buffer-other-window (reftex-get-file-buffer-force file))
3020 (setq show-window (selected-window))
3021 (setq show-buffer (current-buffer))
3022 (goto-char (point-min))
3024 (if (not (re-search-forward find nil t))
3026 (select-window toc-window)
3027 (error "Cannot visit line")))
3029 (setq beg (match-beginning 0)
3034 (reftex-highlight 0 beg end (current-buffer))
3036 (select-window toc-window)
3038 ;; use the `final' parameter to decide what to do next
3041 (reftex-unhighlight 0)
3042 (select-window show-window))
3044 (reftex-unhighlight 0)
3045 (or (one-window-p) (delete-window))
3046 (switch-to-buffer show-buffer)
3047 (reftex-re-enlarge))
3050 ;;; ===========================================================================
3052 ;;; BibTeX citations.
3054 ;; Variables and constants
3056 ;; Define variable to silence compiler warnings
3057 (defvar reftex-found-list)
3058 (defvar reftex-cite-format-builtin)
3060 ;; The history list of regular expressions used for citations
3061 (defvar reftex-cite-regexp-hist nil)
3063 ;; Prompt and help string for citation selection
3064 (defconst reftex-citation-prompt
3065 "Select: [n]ext [p]revious [r]estrict [ ]full_entry [q]uit RET [?]Help+more")
3067 (defconst reftex-citation-help
3068 "AVAILABLE KEYS IN MAKE CITATION MENU
3069 ---------------------------------------
3070 n / p Go to next/previous entry (Cursor motion works as well).
3071 C-s / C-r Search forward/backward. Use repeated C-s/C-r as in isearch.
3072 g / r Start over with new regexp / Restrict with additional regexp.
3073 SPC Show full database entry in other window.
3074 f Toggle follow mode: Other window will follow with full db entry.
3075 q Quit without inserting \\cite macro into buffer.
3076 M-r Recursive edit into other window.
3077 RET / a Accept current entry / Accept all entries.")
3079 ;; Find bibtex files
3081 (defun reftex-get-bibfile-list ()
3082 ;; Return list of bibfiles for current document
3084 ;; Ensure access to scanning info
3085 (reftex-access-scan-info)
3087 (or (symbol-value reftex-bibfile-list-symbol)
3088 (error "No BibTeX files to parse. Add \\bibliography statment to document and reparse.")))
3090 (defun reftex-scan-buffer-for-bibliography-statement (bib-list-symbol)
3091 ;; Scan buffer for bibliography macro and store file list in bib-list-symbol.
3092 (let (file-list dir-list)
3095 (concat path-separator "+")
3096 (mapconcat '(lambda(x)
3097 (if (getenv x) (getenv x) ""))
3098 reftex-bibpath-environment-variables
3100 (goto-char (point-min))
3101 (if (re-search-forward "^[ \t]*\\\\bibliography{[ \t]*\\([^}]+\\)" nil t)
3104 (cons (file-name-directory
3105 (get-text-property (match-beginning 0) 'file))
3108 (mapcar '(lambda (x) (concat x ".bib"))
3110 reftex-bibfile-ignore-list
3113 (reftex-no-props (match-string 1)))))))
3114 (message "No \\bibliography command in document."))
3115 (set bib-list-symbol
3117 (reftex-find-files-on-path file-list dir-list
3118 "While parsing \\bibliography:")
3121 (defun reftex-find-files-on-path (file-list path-list &optional error-string)
3122 ;; Search for all files in FILE-LIST on PATH-LIST. Return absolute names.
3123 ;; A missing file throws an exception with the error message ERROR-STRING.
3124 ;; When error-string is nil, no exception is thrown.
3126 (let (found-list found file)
3128 (setq file (car file-list)
3129 file-list (cdr file-list)
3131 (if (file-name-absolute-p file)
3132 (setq found (expand-file-name file))
3133 (let ((dirs path-list))
3134 (while (and dirs (not found))
3135 (if (and (not (string= (car dirs) ""))
3136 (file-exists-p (expand-file-name file (car dirs))))
3137 (setq found (expand-file-name file (car dirs))))
3138 (setq dirs (cdr dirs)))))
3140 (file-exists-p found))
3141 (add-to-list 'found-list (expand-file-name found))
3143 (error "%s No such file %s." error-string file))))
3144 (nreverse found-list)))
3146 ;; Find a certain reference in any of the BibTeX files.
3148 (defun reftex-pop-to-bibtex-entry (key file-list
3149 &optional mark-to-kill highlight)
3150 ;; Find BibTeX KEY in any file in FILE-LIST in another window.
3151 ;; If mark-to-kill is non-nil, mark new buffer to kill."
3153 (let* ((re (concat "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*" (regexp-quote key) "[ \t\n\r,]"))
3154 (window-conf (current-window-configuration))
3157 (switch-to-buffer-other-window (current-buffer))
3159 (setq file (car file-list)
3160 file-list (cdr file-list))
3161 (if (not (setq buf (reftex-get-file-buffer-force file mark-to-kill)))
3162 (error "No such file %s" file))
3163 (switch-to-buffer buf)
3166 (if (re-search-forward re nil t)
3168 (goto-char (match-beginning 0))
3171 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
3172 (throw 'exit (selected-window)))))
3173 (set-window-configuration window-conf)
3175 (message "No BibTeX entry with citation key %s" key))))
3177 ;; Parse bibtex buffers
3179 (defun reftex-extract-bib-entries (buffers &optional get-word)
3180 ;; Extract bib entries which match regexps from BUFFERS.
3181 ;; BUFFERS is a list of buffers or file names.
3182 ;; Return list with entries."
3183 (let* (re-list first-re rest-re
3184 ;; avoid fontification of lookup buffers
3185 (lazy-lock-minimum-size 1)
3186 (buffer-list (if (listp buffers) buffers (list buffers)))
3187 found-list entry buffer1 buffer alist
3188 key-point start-point end-point)
3190 (setq re-list (reftex-split "[ \t]*&&[ \t]*"
3191 (read-string "RegExp [ && RegExp...]: "
3192 nil 'reftex-cite-regexp-hist)))
3194 (setq first-re (car re-list) ; We'll use the first re to find things,
3195 rest-re (cdr re-list)) ; the other to narrow down.
3196 (if (string-match "\\`[ \t]*\\'" first-re)
3197 (error "Empty regular expression"))
3200 (save-window-excursion
3202 ;; walk through all bibtex files
3204 (setq buffer (car buffer-list)
3205 buffer-list (cdr buffer-list))
3206 (if (and (bufferp buffer)
3207 (buffer-live-p buffer))
3208 (setq buffer1 buffer)
3209 (setq buffer1 (reftex-get-file-buffer-force
3210 buffer (not reftex-keep-temporary-buffers))))
3212 (error "Cannot find BibTeX file %s" buffer)
3213 (message "Scanning bibliography database %s" buffer1))
3215 (set-buffer buffer1)
3217 (goto-char (point-min))
3218 (while (re-search-forward first-re nil t)
3219 (catch 'search-again
3220 (setq key-point (point))
3221 (if (not (re-search-backward
3222 "^[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*[{(]" nil t))
3223 (throw 'search-again nil))
3224 (setq start-point (point))
3225 (goto-char (match-end 0))
3228 (error (goto-char key-point)
3229 (throw 'search-again nil)))
3230 (setq end-point (point))
3232 ;; Ignore @string, @comment and @c entries or things
3234 (if (or (string= (downcase (match-string 1)) "string")
3235 (string= (downcase (match-string 1)) "comment")
3236 (string= (downcase (match-string 1)) "c")
3237 (< (point) key-point)) ; this means match not in {}
3239 (goto-char key-point)
3240 (throw 'search-again nil)))
3242 ;; Well, we have got a match
3244 (buffer-substring start-point (point)) "\n"))
3246 ;; Check if other regexp match as well
3247 (setq re-list rest-re)
3249 (if (not (string-match (car re-list) entry))
3251 (throw 'search-again nil))
3252 (setq re-list (cdr re-list)))
3254 (setq alist (reftex-parse-bibtex-entry
3255 nil start-point end-point))
3256 (setq alist (cons (cons "&entry" entry) alist))
3258 ;; check for crossref entries
3259 (if (assoc "crossref" alist)
3262 alist (reftex-get-crossref-alist alist))))
3267 (cons "&formatted" (reftex-format-bib-entry alist))
3270 ;; add it to the list
3271 (setq found-list (cons alist found-list)))))
3272 (reftex-kill-temporary-buffers))))
3273 (setq found-list (nreverse found-list))
3277 ((eq 'author reftex-sort-bibtex-matches)
3278 (sort found-list 'reftex-bib-sort-author))
3279 ((eq 'year reftex-sort-bibtex-matches)
3280 (sort found-list 'reftex-bib-sort-year))
3281 ((eq 'reverse-year reftex-sort-bibtex-matches)
3282 (sort found-list 'reftex-bib-sort-year-reverse))
3285 (defun reftex-bib-sort-author (e1 e2)
3286 (let ((al1 (reftex-get-bib-names "author" e1))
3287 (al2 (reftex-get-bib-names "author" e2)))
3288 (while (and al1 al2 (string= (car al1) (car al2)))
3291 (if (and (stringp (car al1))
3292 (stringp (car al2)))
3293 (string< (car al1) (car al2))
3294 (not (stringp (car al1))))))
3296 (defun reftex-bib-sort-year (e1 e2)
3297 (< (string-to-int (cdr (assoc "year" e1)))
3298 (string-to-int (cdr (assoc "year" e2)))))
3300 (defun reftex-bib-sort-year-reverse (e1 e2)
3301 (> (string-to-int (or (cdr (assoc "year" e1)) "0"))
3302 (string-to-int (or (cdr (assoc "year" e2)) "0"))))
3304 (defun reftex-get-crossref-alist (entry)
3305 ;; return the alist from a crossref entry
3306 (let ((crkey (cdr (assoc "crossref" entry)))
3311 (if (re-search-forward
3312 (concat "@\\w+[{(][ \t\n\r]*" (regexp-quote crkey) "[ \t\n\r]*,") nil t)
3314 (setq start (match-beginning 0))
3318 (reftex-parse-bibtex-entry nil start (point)))
3321 ;; Parse and format individual entries
3323 (defun reftex-get-bib-names (field entry)
3324 ;; Return a list with the author or editor anmes in ENTRY
3325 (let ((names (reftex-get-bib-field field entry)))
3326 (if (equal "" names)
3327 (setq names (reftex-get-bib-field "editor" entry)))
3328 (while (string-match "\\band\\b[ \t]*" names)
3329 (setq names (replace-match "\n" nil t names)))
3330 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
3331 (setq names (replace-match "" nil t names)))
3332 (while (string-match "^[ \t]+\\|[ \t]+$" names)
3333 (setq names (replace-match "" nil t names)))
3334 (while (string-match "[ \t][ \t]+" names)
3335 (setq names (replace-match " " nil t names)))
3336 (reftex-split "\n" names)))
3338 (defun reftex-parse-bibtex-entry (entry &optional from to)
3339 (let (alist key start field)
3344 (switch-to-buffer "*RefTeX-scratch*")
3349 (narrow-to-region from to))
3350 (goto-char (point-min))
3352 (if (re-search-forward
3353 "@\\(\\w+\\)[ \t\n\r]*[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
3356 (cons "&type" (downcase (reftex-no-props (match-string 1))))
3357 (cons "&key" (reftex-no-props (match-string 2))))))
3358 (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
3359 (setq key (reftex-no-props (downcase (match-string 1))))
3361 ((= (following-char) ?{)
3363 (setq start (point))
3367 ((= (following-char) ?\")
3369 (setq start (point))
3370 (while (and (search-forward "\"" nil t)
3371 (= ?\\ (char-after (- (point) 2))))))
3373 (setq start (point))
3374 (re-search-forward "[ \t\n\r,}]" nil 1)))
3375 (setq field (buffer-substring-no-properties start (1- (point))))
3376 ;; remove extra whitesp
3377 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
3378 (setq field (replace-match " " nil t field)))
3379 ;; remove leading garbage
3380 (if (string-match "^[ \t{]+" field)
3381 (setq field (replace-match "" nil t field)))
3382 ;; remove trailing garbage
3383 (if (string-match "[ \t}]+$" field)
3384 (setq field (replace-match "" nil t field)))
3385 (setq alist (cons (cons key field) alist)))
3388 (defun reftex-get-bib-field (fieldname entry)
3389 ;; Extract the field FIELDNAME from an ENTRY
3390 (or (cdr (assoc fieldname entry))
3393 (defun reftex-format-bib-entry (entry)
3394 ;; Format a BibTeX ENTRY so that it is nice to look at
3397 (auth-list (reftex-get-bib-names "author" entry))
3398 (authors (mapconcat '(lambda (x) x) auth-list ", "))
3399 (year (reftex-get-bib-field "year" entry))
3400 (title (reftex-get-bib-field "title" entry))
3401 (type (reftex-get-bib-field "&type" entry))
3402 (key (reftex-get-bib-field "&key" entry))
3405 ((equal type "article")
3406 (concat (reftex-get-bib-field "journal" entry) " "
3407 (reftex-get-bib-field "volume" entry) ", "
3408 (reftex-get-bib-field "pages" entry)))
3409 ((equal type "book")
3410 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
3411 ((equal type "phdthesis")
3412 (concat "PhD: " (reftex-get-bib-field "school" entry)))
3413 ((equal type "mastersthesis")
3414 (concat "Master: " (reftex-get-bib-field "school" entry)))
3415 ((equal type "inbook")
3416 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
3417 ", pp. " (reftex-get-bib-field "pages" entry)))
3418 ((or (equal type "conference")
3419 (equal type "incollection")
3420 (equal type "inproceedings"))
3421 (concat "in: " (reftex-get-bib-field "booktitle" entry)))
3424 (if (> (length authors) 30)
3425 (concat (substring authors 0 27) "...")
3426 (format "%-30s" authors))
3428 (if (> (length title) 70)
3429 (concat (substring title 0 67) "...")
3430 (format "%-70s" title))
3432 (if (> (length extra) 40)
3433 (concat (substring extra 0 37) "...")
3434 (format "%-40s" extra)))
3435 (if (reftex-use-fonts)
3437 (put-text-property 0 (length authors) 'face 'font-lock-keyword-face
3439 (put-text-property 0 (length title) 'face 'font-lock-comment-face
3441 (put-text-property 0 (length extra) 'face 'font-lock-reference-face
3443 (setq rtn (concat key "\n " authors " " year " " extra
3444 "\n " title "\n\n"))
3449 (defun reftex-citation (&optional arg no-insert)
3450 "Make a citation using BibTeX database files.
3451 After asking for a Regular Expression, it scans the buffers with
3452 bibtex entries (taken from the \\bibliography command) and offers the
3453 matching entries for selection. The selected entry is formated according
3454 to `reftex-cite-format' and inserted into the buffer.
3455 If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
3456 The regular expression uses an expanded syntax: && is interpreted as `and'.
3457 Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
3458 When this function is called with point inside the braces of a \\cite
3459 command, it will add another key, ignoring the value of `reftex-cite-format'.
3460 When called with a numeric prefix, that many citations will be made and all
3461 put into the same \\cite command.
3462 When called with just C-u as prefix, enforces rescan of buffer for
3463 bibliography statement (e.g. if it was changed)."
3467 ;; check for recursive edit
3468 (reftex-check-recursive-edit)
3470 ;; if there is just 1 C-u prefix arg, force to rescan buffer
3471 (if (and current-prefix-arg
3472 (listp current-prefix-arg)
3473 (= 4 (prefix-numeric-value arg)))
3474 (reftex-reset-scanning-information))
3476 ;; check if there is already a cite command at point and change cite format
3477 ;; in order to only add another reference in the same cite command.
3478 (let (key format (macro (car (car (reftex-what-macro t)))))
3479 (if (and (stringp macro)
3480 (string-match "\\`\\\\cite\\|cite\\'" macro))
3487 (if (not (or (= (preceding-char) ?{)
3488 (= (preceding-char) ?,)))
3492 (if (not (or (= (following-char) ?})
3493 (= (following-char) ?,)))
3497 (setq format "%l"))))
3498 ;; else: figure out the correct format
3501 ((stringp reftex-cite-format) reftex-cite-format)
3502 ((and (symbolp reftex-cite-format)
3503 (assq reftex-cite-format reftex-cite-format-builtin))
3504 (nth 2 (assq reftex-cite-format reftex-cite-format-builtin)))
3505 (t reftex-cite-format)))
3507 (save-window-excursion
3508 (with-output-to-temp-buffer "*RefTeX Select*"
3509 (princ "SELECT A CITATION FORMAT\n\n")
3512 (function (lambda (x)
3513 (format "[%c] %s %s" (car x)
3514 (if (> (car x) 31) " " "")
3517 (setq key (read-char))
3518 (if (assq key format)
3519 (setq format (cdr (assq key format)))
3520 (error "No citation format associated with key `%c'" key)))))
3522 (let* (entry cnt rtn ins-string re-list re
3523 ;; scan bibtex files
3524 (lazy-lock-minimum-size 1)
3525 (reftex-found-list (reftex-extract-bib-entries
3526 (reftex-get-bibfile-list)))
3528 (if (not reftex-found-list)
3529 (error "Sorry, no matches found"))
3531 ;; remember where we came from
3532 (setq reftex-call-back-to-this-buffer (current-buffer))
3535 (save-window-excursion
3536 (switch-to-buffer-other-window "*RefTeX Select*")
3538 (reftex-insert-bib-matches reftex-found-list)
3539 (if (= 0 (buffer-size))
3540 (error "Sorry, no matches found"))
3541 (setq truncate-lines t)
3547 reftex-citation-prompt
3550 reftex-citation-help
3553 'reftex-bibtex-selection-callback nil))
3556 (if (not key) (throw 'exit nil))
3559 (setq reftex-found-list
3561 (set-buffer reftex-call-back-to-this-buffer)
3562 (reftex-extract-bib-entries
3563 (reftex-get-bibfile-list))))
3565 (reftex-insert-bib-matches reftex-found-list)
3566 (if (= 0 (buffer-size))
3567 (error "Sorry, no matches found"))
3571 ;; restrict with new regular expression
3573 (reftex-split "[ \t]*&&[ \t]*"
3575 "RegExp [ && RegExp...]: "
3576 nil 'reftex-cite-regexp-hist)))
3578 (setq re (car re-list)
3579 re-list (cdr re-list))
3585 re (cdr (assoc "&entry" x)))
3588 reftex-found-list))))
3590 (setq reftex-found-list found-list-r)
3593 (reftex-insert-bib-matches reftex-found-list)
3601 (setq entry (nth cnt reftex-found-list))
3612 (reftex-format-citation entry format))
3613 reftex-found-list "\n"))
3614 (setq ins-string (reftex-format-citation entry format))))
3615 (setq ins-string "")
3617 (kill-buffer "*RefTeX Select*")
3622 (if (string-match "\\?" ins-string)
3624 (search-backward "?")
3628 ;; Check if the prefix arg was numeric, and call recursively
3629 (if (and (integerp arg)
3632 "\\\\\\([a-zA-Z]*cite\\|cite[a-zA-Z]*\\)\\**\\(\\[[^]]*\\]\\)*{\\([^}]*\\)" nil t)) ;;; FIXME this can break with ? in format
3634 (goto-char (match-end 0))
3636 (reftex-citation arg))
3637 (reftex-kill-temporary-buffers))
3638 ;; Return the citation key
3640 (reftex-get-bib-field "&key" entry)))))
3642 (defun reftex-insert-bib-matches (list)
3643 ;; Insert the bib matches and number them correctly
3645 (mapcar '(lambda (x)
3646 (setq tmp (cdr (assoc "&formatted" x))
3648 (put-text-property 0 (length tmp) 'cnt cnt tmp)
3652 (defun reftex-format-names (namelist n)
3654 (let (last (len (length namelist)))
3656 ((= 1 len) (car namelist))
3657 ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
3660 last (nth (1- n) namelist))
3661 (setcdr (nthcdr (- n 2) namelist) nil)
3663 (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
3664 (nth 1 reftex-cite-punctuation)
3667 (defun reftex-format-citation (entry format)
3668 ;; Format a citation from the info in the BibTeX ENTRY
3670 (if (not (stringp format)) (setq format "\\cite{%l}"))
3672 (if (and reftex-comment-citations
3673 (string-match "%l" reftex-cite-comment-format))
3674 (error "reftex-cite-comment-format contains illeagal %%l"))
3676 (while (string-match
3677 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
3679 (let ((n (string-to-int (match-string 4 format)))
3680 (l (string-to-char (match-string 5 format)))
3686 (reftex-get-bib-field "&key" entry)
3687 (if reftex-comment-citations
3688 reftex-cite-comment-format
3690 ((= l ?a) (reftex-format-names
3691 (reftex-get-bib-names "author" entry)
3693 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
3694 ((= l ?b) (reftex-get-bib-field "booktitle" entry))
3695 ((= l ?c) (reftex-get-bib-field "chapter" entry))
3696 ((= l ?d) (reftex-get-bib-field "edition" entry))
3697 ((= l ?e) (reftex-format-names
3698 (reftex-get-bib-names "editor" entry)
3700 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
3701 ((= l ?h) (reftex-get-bib-field "howpublished" entry))
3702 ((= l ?i) (reftex-get-bib-field "institution" entry))
3703 ((= l ?j) (reftex-get-bib-field "journal" entry))
3704 ((= l ?k) (reftex-get-bib-field "key" entry))
3705 ((= l ?m) (reftex-get-bib-field "month" entry))
3706 ((= l ?n) (reftex-get-bib-field "number" entry))
3707 ((= l ?o) (reftex-get-bib-field "organization" entry))
3708 ((= l ?p) (reftex-get-bib-field "pages" entry))
3709 ((= l ?P) (car (reftex-split
3711 (reftex-get-bib-field "pages" entry))))
3712 ((= l ?s) (reftex-get-bib-field "school" entry))
3713 ((= l ?u) (reftex-get-bib-field "publisher" entry))
3714 ((= l ?r) (reftex-get-bib-field "address" entry))
3715 ((= l ?t) (reftex-get-bib-field "title" entry))
3716 ((= l ?v) (reftex-get-bib-field "volume" entry))
3717 ((= l ?y) (reftex-get-bib-field "year" entry)))))
3719 (if (string= rpl "")
3720 (setq b (match-beginning 2) e (match-end 2))
3721 (setq b (match-beginning 3) e (match-end 3)))
3722 (setq format (concat (substring format 0 b) rpl (substring format e)))))
3723 (while (string-match "%%" format)
3724 (setq format (replace-match "%" t t format)))
3725 (while (string-match "[ ,.;:]*%<" format)
3726 (setq format (replace-match "" t t format)))
3729 ;; this is slow and not recommended for follow mode
3730 (defun reftex-bibtex-selection-callback (cnt)
3731 ;; Callback function to be called from the BibTeX selection, in
3732 ;; order to display context. This function is relatively slow and not
3733 ;; recommended for follow mode, just for individual lookups.
3734 (let ((win (selected-window))
3735 (key (reftex-get-bib-field "&key" (nth cnt reftex-found-list)))
3736 (bibfile-list (save-excursion
3737 (set-buffer reftex-call-back-to-this-buffer)
3738 (reftex-get-bibfile-list))))
3739 (reftex-pop-to-bibtex-entry key bibfile-list
3740 (not reftex-keep-temporary-buffers) t)
3741 (select-window win)))
3743 ;;; ===========================================================================
3745 ;;; Here is the routine used for selection
3747 ;; Marker for return point from recursive edit
3748 (defvar reftex-recursive-edit-marker (make-marker))
3750 (defun reftex-check-recursive-edit ()
3751 ;; Check if we are already in a recursive edit. Abort with helpful
3753 (if (marker-position reftex-recursive-edit-marker)
3755 (substitute-command-keys
3756 "In unfinished recursive edit. Finish (\\[exit-recursive-edit]) or abort (\\[abort-recursive-edit])."))))
3758 (defun reftex-select-item (prompt next-re size help-string
3759 event-list &optional offset
3760 call-back cb-flag match-everywhere)
3761 ;; Select an item. Show PROMPT to user, find next item with NEXT-RE
3762 ;; regular expression, return on any of the events listed in
3763 ;; EVENT-LIST. The function returns the event along with an integer
3764 ;; indicating which item was selected. When OFFSET is specified,
3765 ;; starts at that item in the list. When CALL-BACK is given, it is a
3766 ;; function which is called with the index of the element.
3768 (let* (key key-sq b e ev cnt last-cnt cmd skip-callback
3769 (search-str "") tmp search-start matched forward mini-map last-key
3770 (offset1 (or offset 1)))
3772 ;; Set up a minibuffer keymap for the search stuff
3773 (setq mini-map (copy-keymap minibuffer-local-map))
3774 (define-key mini-map "\C-s"
3775 '(lambda () (interactive) (setq forward t) (exit-minibuffer)))
3776 (define-key mini-map "\C-r"
3777 '(lambda () (interactive) (setq forward nil) (exit-minibuffer)))
3778 (define-key mini-map "\C-m" 'exit-minibuffer)
3782 (save-window-excursion
3783 (if (= 0 (buffer-size))
3785 (setq truncate-lines t)
3787 (if (not (re-search-forward next-re nil t offset1))
3788 (progn ; in case the offset is illegal
3790 (if (not (re-search-forward next-re nil t offset1))
3791 (throw 'exit nil))))
3792 (beginning-of-line 1)
3794 (setq last-cnt (or cnt last-cnt))
3795 (setq cnt (get-text-property (point) 'cnt))
3796 (if (and cnt cb-flag call-back (not skip-callback))
3797 (funcall call-back cnt))
3798 (setq skip-callback nil)
3800 (setq b (or (previous-single-property-change
3803 e (or (next-single-property-change
3806 (setq b (point) e (point)))
3807 (reftex-highlight 1 b e)
3808 (if (or (not (pos-visible-in-window-p b))
3809 (not (pos-visible-in-window-p e)))
3810 (recenter (/ (window-height) 2)))
3811 (setq key-sq (read-key-sequence prompt))
3815 ((fboundp 'listify-key-sequence) ; Emacs
3816 (listify-key-sequence key-sq))
3817 ((fboundp 'event-to-character) ; XEmacs
3818 (mapcar 'event-to-character key-sq))
3819 (t (error "Please report this problem to dominik@strw.leidenuniv.nl")))))
3821 (setq cmd (key-binding key-sq))
3823 (reftex-unhighlight 2)
3824 (reftex-unhighlight 0)
3828 ;; Single line motions
3831 (eq cmd 'next-line))
3833 (re-search-forward next-re nil t 1)
3834 (beginning-of-line 1))
3836 (eq cmd 'previous-line))
3837 (re-search-backward next-re nil t))
3840 ((eq cmd 'scroll-up)
3841 (while (and (pos-visible-in-window-p)
3842 (re-search-forward next-re nil t)))
3843 (beginning-of-line 1)
3845 ((eq cmd 'scroll-down)
3846 (while (and (pos-visible-in-window-p)
3847 (re-search-backward next-re nil t)))
3848 (recenter (- (window-height) size 2)))
3850 ;; Begin and end of buffer
3851 ((eq cmd 'beginning-of-buffer)
3852 (goto-char (point-min))
3853 (re-search-forward next-re nil t)
3854 (beginning-of-line 1))
3855 ((eq cmd 'end-of-buffer)
3856 (goto-char (point-max))
3857 (re-search-backward next-re nil t))
3863 (if (or (eq last-key ?\C-s) (eq last-key ?\C-r))
3870 (throw 'exit 'return))
3871 ((memq key event-list)
3875 ((or (eq key ?C) ; backward compatibility
3877 (setq cb-flag (not cb-flag)))
3879 (if cnt (funcall call-back cnt) (ding)))
3883 (with-output-to-temp-buffer "*RefTeX Help*"
3884 (princ help-string))
3885 (setq skip-callback t))
3888 ((or (setq forward (eq key ?\C-s)) (eq key ?\C-r))
3889 (if (or (and (not (eq last-key ?\C-s))
3890 (not (eq last-key ?\C-r)))
3891 (string= search-str ""))
3892 (setq tmp ; get a new string
3893 (read-from-minibuffer
3894 (if (string= search-str "")
3896 (format "Search [%s]:" search-str))
3898 search-str (if (string= tmp "")
3900 (setq search-start (point))
3901 (and (not (string= search-str ""))
3906 (search-forward search-str nil 1)
3907 (search-backward search-str nil 1)))
3908 (or (>= (save-excursion
3909 (goto-char (match-beginning 0))
3912 (not (or (get-text-property (point) 'cnt)
3913 match-everywhere)))))
3915 (reftex-highlight 2 (match-beginning 0)
3918 (goto-char search-start)))))
3922 (set-marker reftex-recursive-edit-marker (point))
3925 (save-window-excursion
3929 (substitute-command-keys
3930 "Recursive edit. Return to selection with \\[exit-recursive-edit]"))
3932 (if (not (equal (marker-buffer
3933 reftex-recursive-edit-marker)
3936 "Cannot continue RefTeX from this buffer."))
3937 (goto-char reftex-recursive-edit-marker))
3938 (set-marker reftex-recursive-edit-marker nil)))
3942 (and (get-buffer "*RefTeX Help*") (kill-buffer "*RefTeX Help*"))
3944 (list ev cnt last-cnt)))
3946 ;;; ===========================================================================
3948 ;;; View cross references
3950 (defun reftex-view-crossref (&optional arg)
3951 "View cross reference of \\ref or \\cite macro at point.
3952 If the macro at point is a \\ref, show the corresponding label definition.
3953 If it is a \\cite, show the BibTeX database entry.
3954 If there is no such macro at point, search forward to find one.
3955 When you call this function several times in direct successtion, point will
3956 move to view subsequent cross references further down in the buffer.
3957 To cope with the plethora of variations in packages, this function
3958 assumes any macro either starting with ending in `ref' or `cite' to contain
3960 With argument, actually select the window showing the cross reference."
3964 ;; See where we are.
3965 (let* ((re "\\\\\\([a-z]*\\(cite\\|ref\\)\\|\\(cite\\|ref\\)[a-z]*\\)\\**\\(\\[[^{}]*\\]\\)?{")
3966 (macro (car (car (reftex-what-macro t))))
3967 (this-word (reftex-this-word "*a-zA-Z\\\\"))
3968 (my-window (get-buffer-window (current-buffer)))
3969 pop-window cmd args label point)
3972 (string-match "\\`\\\\cite\\|\\`\\\\ref\\|cite\\'\\|ref\\'"
3974 (and (setq macro (match-string 0 macro))
3975 (string-match "\\`\\\\" macro)
3976 (setq macro (substring macro 1)))
3979 (if (and macro (eq last-command this-command))
3980 (if (string= macro "cite")
3982 (skip-chars-forward "^},%")
3983 (while (and (eq (following-char) ?%)
3984 (or (beginning-of-line 2) t)
3985 (skip-chars-forward " \t\n")))
3986 (skip-chars-forward ",")
3987 (if (eq (following-char) ?})
3991 (if (and (not macro)
3992 (eq this-command 'reftex-view-crossref)
3993 (or (not (string-match "\\`\\\\" this-word))
3994 (search-backward "\\" nil t)
3996 (re-search-forward re nil t))
3997 (setq macro (or (match-string 2) (match-string 3))))
4000 (error "No cross reference to display"))
4002 ;; Ensure access to scanning info
4003 (reftex-access-scan-info)
4006 ((string= macro "cite")
4007 (setq cmd 'reftex-pop-to-bibtex-entry
4009 (reftex-no-props (reftex-this-word "^{},%\n"))
4010 (reftex-get-bibfile-list) nil t)))
4011 ((string= macro "ref")
4012 (let* ((label (reftex-no-props (reftex-this-word "^{}%\n")))
4013 (entry (assoc label (symbol-value reftex-list-of-labels-symbol))))
4015 (setq cmd 'reftex-pop-to-label
4016 args (list label (list (nth 3 entry)) nil t))
4017 (error "Label %s not known - reparse document might help" label))))
4018 (t (error "This should not happen")))
4019 (setq point (point))
4021 (setq pop-window (selected-window))
4022 (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
4023 (select-window my-window)
4025 (and arg (select-window pop-window))))
4027 (defun reftex-mouse-view-crossref (ev)
4028 "View cross reference of \\ref or \\cite macro where you click.
4029 If the macro at point is a \\ref, show the corresponding label definition.
4030 If it is a \\cite, show the BibTeX database entry.
4031 If there is no such macro at point, search forward to find one.
4032 With argument, actually select the window showing the cross reference."
4034 (mouse-set-point ev)
4035 (setq last-command 'self-insert-command) ;; make sure we do not move!
4036 (reftex-view-crossref current-prefix-arg))
4038 ;;; ===========================================================================
4040 ;;; Functions that check out the surroundings
4042 (defun reftex-what-macro (which &optional bound)
4043 ;; Find out if point is within the arguments of any TeX-macro.
4044 ;; The return value is either ("\\macro" . (point)) or a list of them.
4046 ;; If WHICH is nil, immediately return nil.
4047 ;; If WHICH is t, return list of all macros enclosing point.
4048 ;; If WHICH is a list of macros, look only for those macros and return the
4049 ;; name of the first macro in this list found to enclose point.
4050 ;; If the optional BOUND is an integer, bound backwards directed
4051 ;; searches to this point. If it is nil, limit to nearest \section -
4054 ;; This function is pretty stable, but can be fooled if the text contains
4055 ;; things like \macro{aa}{bb} where \macro is defined to take only one
4056 ;; argument. As RefTeX cannot know this, the string "bb" would still be
4057 ;; considered an argument of macro \macro.
4060 (if (null which) (throw 'exit nil))
4061 (let ((bound (or bound (save-excursion (re-search-backward
4062 reftex-section-regexp nil 1)
4067 (narrow-to-region (max 1 bound) (point-max))
4068 ;; move back out of the current parenthesis
4069 (while (condition-case nil
4070 (progn (up-list -1) t)
4072 ;; move back over any touching sexps
4073 (while (or (= (preceding-char) ?\])
4074 (= (preceding-char) ?\}))
4077 (if (and (or (= (following-char) ?\[)
4078 (= (following-char) ?\{))
4079 (and (re-search-backward "\\(\\\\[*a-zA-Z]+\\)" nil t)
4080 (= (match-end 0) pos)))
4082 (setq cmd (buffer-substring-no-properties
4083 (match-beginning 0) (match-end 0)))
4085 (setq cmd-list (cons (cons cmd (point)) cmd-list))
4086 (if (member cmd which)
4087 (throw 'exit (cons cmd (point)))))))
4089 (nreverse cmd-list)))))
4091 (defun reftex-what-environment (which &optional bound)
4092 ;; Find out if point is inside a LaTeX environment.
4093 ;; The return value is (e.g.) either ("equation" . (point)) or a list of
4096 ;; If WHICH is nil, immediately return nil.
4097 ;; If WHICH is t, return list of all environments enclosing point.
4098 ;; If WHICH is a list of environments, look only for those environments and
4099 ;; return the name of the first environment in this list found to enclose
4102 ;; If the optional BOUND is an integer, bound backwards directed searches to
4103 ;; this point. If it is nil, limit to nearest \section - like statement.
4107 (if (null which) (throw 'exit nil))
4108 (let ((bound (or bound (save-excursion (re-search-backward
4109 reftex-section-regexp nil 1)
4111 env-list end-list env)
4112 (while (re-search-backward "\\\\\\(begin\\|end\\){\\([^}]+\\)}"
4114 (setq env (buffer-substring-no-properties
4115 (match-beginning 2) (match-end 2)))
4117 ((string= (match-string 1) "end")
4118 (add-to-list 'end-list env))
4119 ((member env end-list)
4120 (setq end-list (delete env end-list)))
4122 (setq env-list (cons (cons env (point)) env-list)))
4124 (throw 'exit (cons env (point))))))
4125 (nreverse env-list)))))
4127 (defun reftex-word-before-point ()
4128 ;; Return the word before point. Word means here:
4129 ;; Consists of [a-zA-Z0-9.:] and ends at point or whitespace.
4130 (let ((pos (point)))
4132 (re-search-backward "[^ \t\n\r]" (point-min) 1)
4133 (setq pos (1+ (point)))
4134 (if (re-search-backward "[^a-zA-Z0-9\\\.:]" (point-min) 1)
4136 (buffer-substring-no-properties (point) pos))))
4138 ;; ============================================================================
4140 ;; Some generally useful functions
4142 (defun reftex-no-props (string)
4143 ;; Return STRING with all text properties removed
4144 (and (stringp string)
4145 (set-text-properties 0 (length string) nil string))
4148 (defun reftex-split (regexp string)
4150 (let ((start 0) list)
4151 (while (string-match regexp string start)
4152 (setq list (cons (substring string start (match-beginning 0)) list))
4153 (setq start (match-end 0)))
4154 (setq list (nreverse (cons (substring string start) list)))))
4156 (defun reftex-allow-for-ctrl-m (string)
4157 ;; convert STRING into a regexp, allowing ^M for \n
4159 (setq string (regexp-quote string))
4160 (while (setq start (string-match "[\n\r]" string (+ 3 start)))
4161 (setq string (replace-match "[\n\r]" nil t string)))
4164 (defun reftex-delete-list (elt-list list)
4165 ;; like delete, but with a list of things to delete
4166 ;; (original code from Rory Molinari)
4168 (setq list (delete (car elt-list) list)
4169 elt-list (cdr elt-list)))
4172 (defun reftex-get-buffer-visiting (file)
4173 ;; return a buffer visiting FILE
4175 ((fboundp 'find-buffer-visiting) ; Emacs
4176 (find-buffer-visiting file))
4177 ((boundp 'find-file-compare-truenames) ; XEmacs
4178 (let ((find-file-compare-truenames t))
4179 (get-file-buffer file)))
4180 (t (error "Please report this problem to dominik@strw.leidenuniv.nl"))))
4182 (defun reftex-get-file-buffer-force (file &optional mark-to-kill)
4183 ;; Return a buffer visiting file. Make one, if necessary.
4184 ;; If neither such a buffer no the file exist, return nil.
4185 ;; If MARK-TO-KILL in non-nil, put any new buffers into the kill list."
4187 (let ((buf (reftex-get-buffer-visiting file)))
4190 ((file-exists-p file)
4191 (setq buf (find-file-noselect file))
4193 (add-to-list 'reftex-buffers-to-kill buf))
4197 (defun reftex-splice-symbols-into-list (list alist)
4198 ;; Splice the association in ALIST of any symbols in LIST into the list.
4202 (while (and (not (null (car list)))
4203 (symbolp (car list)))
4204 (setq tmp (car list))
4207 (setq list (append (nth 2 (assoc tmp alist)) (cdr list))))
4209 (error "Cannot treat symbol %s in reftex-label-alist"
4210 (symbol-name tmp)))))
4211 (setq rtn (cons (car list) rtn)
4215 (defun reftex-uniquify (alist &optional keep-list)
4216 ;; Return a list of all elements in ALIST, but each car only once.
4217 ;; Elements of KEEP-LIST are not removed even if duplicate.
4220 (setq elm (car alist)
4222 (if (or (member (car elm) keep-list)
4223 (not (assoc (car elm) new)))
4224 (setq new (cons elm new))))
4225 (setq new (nreverse new))
4228 (defun reftex-use-fonts ()
4229 ;; Return t if we can and want to use fonts.
4232 (boundp 'font-lock-keyword-face)))
4234 ;; Highlighting uses overlays. If this is for XEmacs, we need to load
4235 ;; the overlay library, available in version 19.15
4236 (and (not (fboundp 'make-overlay))
4240 (error "RefTeX needs overlay emulation (available in XEmacs 19.15)"))))
4242 ;; We keep a vector with several different overlays to do our highlighting.
4243 (defvar reftex-highlight-overlays [nil nil nil])
4245 ;; Initialize the overlays
4246 (aset reftex-highlight-overlays 0 (make-overlay 1 1))
4247 (overlay-put (aref reftex-highlight-overlays 0) 'face 'highlight)
4248 (aset reftex-highlight-overlays 1 (make-overlay 1 1))
4249 (overlay-put (aref reftex-highlight-overlays 1) 'face 'highlight)
4250 (aset reftex-highlight-overlays 2 (make-overlay 1 1))
4251 (overlay-put (aref reftex-highlight-overlays 2) 'face
4252 (if (string-match "XEmacs" emacs-version) 'zmacs-region 'region))
4254 ;; Two functions for activating and deactivation highlight overlays
4255 (defun reftex-highlight (index begin end &optional buffer)
4256 "Highlight a region with overlay INDEX."
4257 (move-overlay (aref reftex-highlight-overlays index)
4258 begin end (or buffer (current-buffer))))
4259 (defun reftex-unhighlight (index)
4260 "Detatch overlay INDEX."
4261 (delete-overlay (aref reftex-highlight-overlays index)))
4263 (defun reftex-highlight-shall-die ()
4264 ;; Function used in pre-command-hook to remove highlights.
4265 (remove-hook 'pre-command-hook 'reftex-highlight-shall-die)
4266 (reftex-unhighlight 0))
4268 ;;; ---------------------------------------------------------------------------
4270 ;;; Cursor position after insertion of forms
4272 (defun reftex-position-cursor ()
4273 ;; Search back to question mark, delete it, leave point there
4274 (if (search-backward "\?" (- (point) 100) t)
4277 (defun reftex-item ()
4278 "Insert an \\item and provide a label if the environments supports that."
4281 (reftex-what-environment '("itemize" "enumerate" "eqnarray")))))
4283 (if (and env (not (bolp))) (newline))
4287 ((string= env "eqnarray")
4292 (beginning-of-line 1))
4294 ((string= env "itemize")
4298 ((string= env "enumerate")
4304 (error "\\item command does not make sense here...")))))
4306 ;;; ---------------------------------------------------------------------------
4307 ;;; ---------------------------------------------------------------------------
4308 ;;; ---------------------------------------------------------------------------
4310 ;;; Data Section: Definition of large constants
4312 (defconst reftex-label-alist-builtin
4314 ;; Some aliases, mostly for backward compatibility
4315 (Sideways "Alias for -->rotating" (rotating))
4316 (AMSTeX "Alias for -->amsmath" (amsmath))
4318 ;; Here come the individual packages of the LaTeX distribution
4319 (amsmath "AMS math environments"
4320 (("align" ?e "eq:" "~\\eqref{%s}" "\\\\begin{align}\\|\\\\\\\\")
4321 ("gather" ?e "eq:" nil "\\\\begin{gather}\\|\\\\\\\\")
4322 ("multline" ?e "eq:" nil t)
4323 ("flalign" ?e "eq:" nil "\\\\begin{flalign}\\|\\\\\\\\")
4324 ("alignat" ?e "eq:" nil "\\\\begin{alignat}{[0-9]*}\\|\\\\\\\\")
4325 ("xalignat" ?e "eq:" nil "\\\\begin{xalignat}{[0-9]*}\\|\\\\\\\\")
4326 ("xxalignat" ?e "eq:" nil "\\\\begin{xxalignat}{[0-9]*}\\|\\\\\\\\")))
4328 (longtable "The longtable environment"
4329 (("longtable" ?t nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")))
4331 (rotating "Sidewaysfigure and table"
4332 (("sidewaysfigure" ?f nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")
4333 ("sidewaystable" ?t nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")))
4335 (subfigure "Subfigure environments/macro"
4336 (("subfigure" ?f nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")
4337 ("subfigure*" ?f nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")
4338 ("\\subfigure" ?f nil nil "\\\\subfigure[[{]")))
4340 (LaTeX "LaTeX default environments"
4341 (("section" ?s "sec:" "~\\ref{%s}" (nil . t)
4342 ("Part" "Chapter" "Chap." "Section" "Sec." "Sect." "Paragraph" "Par."
4343 "\\S" "Teil" "Kapitel" "Kap." "Abschnitt" ))
4345 ("enumerate" ?n "item:" "~\\ref{%s}" "\\\\item\\(\\[[^]]*\\]\\)?"
4348 ("equation" ?e "eq:" "~(\\ref{%s})" t
4349 ("Equation" "Eq." "Eqn." "Gleichung" "Gl."))
4350 ("eqnarray" ?e "eq:" nil "\\\\begin{eqnarray}\\|\\\\\\\\")
4352 ("figure" ?f "fig:" "~\\ref{%s}" "\\\\caption\\(\\[[^]]*\\]\\)?{"
4353 ("Figure" "Fig." "Abbildung" "Abb."))
4354 ("figure*" ?f nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")
4356 ("table" ?t "tab:" "~\\ref{%s}" "\\\\caption\\(\\[[^]]*\\]\\)?{"
4357 ("Table" "Tab." "Tabelle"))
4358 ("table*" ?t nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")
4360 ("any" ?\ " " "\\ref{%s}" nil)))
4363 "The default label environment descriptions.
4364 Lower-case symbols correspond to a style file of the same name in the LaTeX
4365 distribution. Mixed-case symbols are convenience aliases.")
4367 (defconst reftex-cite-format-builtin
4369 (default "Default macro \\cite{%l}"
4371 (harvard "P. William's and T. Schnier's Harvard package"
4372 ((?\C-m . "\\cite{%l}")
4374 (?t . "\\citeasnoun{%l}")
4375 (?n . "\\citeasnoun{%l}")
4376 (?s . "\\possessivecite{%l}")
4377 (?e . "\\citeaffixed{%l}{?}")
4378 (?y . "\\citeyear{%l}")
4379 (?a . "\\citename{%l}")))
4380 (natbib "Patrick W. Daly's Natbib package"
4381 ((?\C-m . "\\cite{%l}")
4382 (?t . "\\citet{%l}")
4383 (?T . "\\citet*{%l}")
4384 (?p . "\\citep{%l}")
4385 (?P . "\\citep*{%l}")
4386 (?e . "\\citep[e.g.][]{%l}")
4387 (?a . "\\citeauthor{%l}")
4388 (?y . "\\citeyear{%l}")))
4389 (astron "S. Hogeveen's Astron package"
4390 ((?\C-m . "\\cite{%l}")
4391 (?p . "\\cite{%l}" )
4392 (?t . "%2a (\\cite{%l})")))
4393 (author-year "Do-it-yourself Author year citation"
4394 ((?\C-m . "\\cite{%l}")
4395 (?t . "%2a (%y)\\nocite{%l}")
4396 (?p . "(%2a %y\\nocite{%l})")))
4397 (locally "Put full info in parenthesis"
4398 "(%2a %y, %j %v, %P, %e: %b, %u, %s %<)")
4399 ;; undocumented feature: `%<' kills white space and punctuation locally.
4401 "Builtin versions of for the citation format.
4402 The following conventions are valid for all alist entries:
4403 `?\C-m' should always point to a straight \\cite{%l} macro.
4404 `?t' should point to a textual citation (citation as a noun).
4405 `?p' should point to a parenthetical citation.")
4407 ;;; ---------------------------------------------------------------------------
4409 ;;; Functions to compile the tables, reset the mode etc.
4411 (defun reftex-reset-mode ()
4412 "Reset RefTeX Mode. Required to implement changes to some list variables.
4413 This function will compile the information in `reftex-label-alist' and similar
4414 variables. It is called when RefTeX is first used, and after changes to
4415 these variables via `reftex-add-to-label-alist'."
4418 ;; Record that we have done this
4419 (setq reftex-tables-dirty nil)
4421 ;; Kill temporary buffers associated with RefTeX - just in case they
4422 ;; were not cleaned up properly
4423 (let ((buffer-list '("*RefTeX Master*" "*RefTeX Help*" "*RefTeX Select*"
4424 "*Duplicate Labels*" "*toc*" "*RefTeX-scratch*")))
4426 (if (get-buffer (car buffer-list))
4427 (kill-buffer (car buffer-list)))
4428 (setq buffer-list (cdr buffer-list))))
4430 (reftex-reset-scanning-information)
4432 ;; Plug functions into AUCTeX if the user option says so
4433 (reftex-plug-into-AUCTeX)
4435 ;; To update buffer-local variables
4436 (hack-local-variables)
4437 (message "updating internal tables...")
4438 (reftex-compute-ref-cite-tables)
4439 (message "updating internal tables... done"))
4441 (defun reftex-reset-scanning-information ()
4442 "Reset the symbols containing information from buffer scanning.
4443 This enforces rescanning the buffer on next use."
4444 (if (string= reftex-last-toc-master (reftex-TeX-master-file))
4445 (reftex-empty-toc-buffer))
4446 (let ((symlist reftex-multifile-symbols)
4449 (setq symbol (car symlist)
4450 symlist (cdr symlist))
4451 (if (and (symbolp (symbol-value symbol))
4452 (not (null (symbol-value symbol))))
4453 (set (symbol-value symbol) nil)))))
4455 (defun reftex-compute-ref-cite-tables ()
4456 ;; Update ref and cite tables
4460 ;; Compile information in reftex-label-alist
4461 (let ((tmp (reftex-uniquify (reftex-splice-symbols-into-list
4464 reftex-label-alist-external-add-ons
4465 reftex-default-label-alist-entries)
4466 reftex-label-alist-builtin)
4468 entry env-or-mac typekeychar typekey prefix context
4469 fmt reffmt labelfmt wordlist qh-list)
4471 (setq reftex-words-to-typekey-alist nil
4472 reftex-typekey-list nil
4473 reftex-typekey-to-format-alist nil
4474 reftex-typekey-to-prefix-alist nil
4475 reftex-env-or-mac-alist nil
4476 reftex-label-env-list nil
4477 reftex-label-mac-list nil)
4480 (setq entry (car tmp)
4481 env-or-mac (car entry)
4484 (if (null env-or-mac)
4485 (setq env-or-mac ""))
4486 (if (stringp (car entry))
4487 ;; This is before version 2.00 - convert entry to new format
4488 ;; This is just to keep old users happy
4489 (setq entry (cons (string-to-char (car entry))
4490 (cons (concat (car entry) ":")
4492 (setq typekeychar (nth 0 entry)
4493 typekey (char-to-string typekeychar)
4494 prefix (nth 1 entry)
4496 context (nth 3 entry)
4497 wordlist (nth 4 entry))
4498 (if (stringp wordlist)
4499 ;; This is before version 2.04 - convert to new format
4500 (setq wordlist (nthcdr 4 entry)))
4502 (if (and (stringp fmt)
4503 (string-match "@" fmt))
4504 ;; special syntax for specifying a label format
4505 (setq fmt (reftex-split "@+" fmt))
4506 (setq fmt (list "\\label{%s}" fmt)))
4507 (setq labelfmt (car fmt)
4510 (add-to-list 'reftex-typekey-list typekey))
4511 (if (and typekey prefix
4512 (not (assoc typekey reftex-typekey-to-prefix-alist)))
4513 (add-to-list 'reftex-typekey-to-prefix-alist (cons typekey prefix)))
4515 ((string-match "\\`\\\\" env-or-mac)
4517 (add-to-list 'reftex-label-mac-list env-or-mac))
4519 (cond ((string= env-or-mac "any"))
4520 ((string= env-or-mac ""))
4521 ((string= env-or-mac "section"))
4523 (add-to-list 'reftex-label-env-list env-or-mac)
4524 ;; if context is t, translate to skip many parens pairs
4525 (if (eq t context) (setq context 100))))))
4527 (not (assoc typekey reftex-typekey-to-format-alist))
4528 (setq reftex-typekey-to-format-alist
4529 (cons (cons typekey reffmt)
4530 reftex-typekey-to-format-alist)))
4531 (and (not (string= env-or-mac "any"))
4532 (not (string= env-or-mac ""))
4533 (not (assoc env-or-mac reftex-env-or-mac-alist))
4534 (setq reftex-env-or-mac-alist
4535 (cons (list env-or-mac typekey context labelfmt)
4536 reftex-env-or-mac-alist)))
4537 (while (and wordlist (stringp (car wordlist)))
4538 (or (assoc (car wordlist) reftex-words-to-typekey-alist)
4539 (setq reftex-words-to-typekey-alist
4540 (cons (cons (downcase (car wordlist)) typekey)
4541 reftex-words-to-typekey-alist)))
4542 (setq wordlist (cdr wordlist)))
4544 ((string= "" env-or-mac) nil)
4545 ((assoc typekey qh-list)
4546 (setcdr (assoc typekey qh-list)
4547 (concat (cdr (assoc typekey qh-list)) " " env-or-mac)))
4549 (setq qh-list (cons (cons typekey env-or-mac) qh-list))))))
4551 (setq qh-list (nreverse qh-list))
4552 (setq reftex-typekey-to-prefix-alist
4553 (nreverse reftex-typekey-to-prefix-alist))
4554 (setq reftex-type-query-prompt
4555 (concat "Label type: "
4556 (mapconcat '(lambda(x)
4557 (format "[%s]" (car x)))
4560 (setq reftex-type-query-help
4561 (concat "SELECT A LABEL TYPE:\n--------------------\n"
4562 (mapconcat '(lambda(x)
4567 ;; Calculate the section regexp
4568 (setq reftex-section-regexp
4569 (concat "^[ ]*\\\\\\("
4570 (mapconcat 'car reftex-section-levels "\\|")
4571 "\\)\\*?\\(\\[[^]]*\\]\\)?{"))
4574 ;;; Keybindings --------------------------------------------------------------
4576 (define-key reftex-mode-map "\C-c-" 'reftex-item)
4577 (define-key reftex-mode-map "\C-c=" 'reftex-toc)
4578 (define-key reftex-mode-map "\C-c(" 'reftex-label)
4579 (define-key reftex-mode-map "\C-c)" 'reftex-reference)
4580 (define-key reftex-mode-map "\C-c[" 'reftex-citation)
4581 (define-key reftex-mode-map "\C-c&" 'reftex-view-crossref)
4583 ;; If the user requests so, she can have a few more bindings:
4585 (reftex-extra-bindings
4586 (define-key reftex-mode-map "\C-ct" 'reftex-toc)
4587 (define-key reftex-mode-map "\C-cl" 'reftex-label)
4588 (define-key reftex-mode-map "\C-cr" 'reftex-reference)
4589 (define-key reftex-mode-map "\C-cc" 'reftex-citation)
4590 (define-key reftex-mode-map "\C-cv" 'reftex-view-crossref)
4591 (define-key reftex-mode-map "\C-cg" 'reftex-grep-document)
4592 (define-key reftex-mode-map "\C-cs" 'reftex-search-document)))
4594 ;;; Menus --------------------------------------------------------------------
4596 ;; Define a menu for the menu bar if Emacs is running under X
4601 reftex-mode-menu reftex-mode-map
4602 "Menu used in RefTeX mode"
4604 ["Table of Contents" reftex-toc t]
4606 ["\\label" reftex-label t]
4607 ["\\ref" reftex-reference t]
4608 ["\\cite" reftex-citation t]
4609 ["View crossref" reftex-view-crossref t]
4611 ("Search and Replace"
4612 ["Search whole document" reftex-search-document t]
4613 ["Replace in document" reftex-query-replace-document t]
4614 ["Grep on document" reftex-grep-document t]
4616 ["Find duplicate labels" reftex-find-duplicate-labels t]
4617 ["Change label and refs" reftex-change-label t]
4619 ["Create TAGS file" reftex-create-tags-file t])
4621 ["Parse document" reftex-parse-document t]
4622 ["Reset RefTeX Mode" reftex-reset-mode t]
4623 ["Show documentation" reftex-show-commentary t]
4624 ["Customize RefTeX" reftex-customize t]))
4626 ;;; Run Hook ------------------------------------------------------------------
4628 (run-hooks 'reftex-load-hook)
4630 ;;; That's it! ----------------------------------------------------------------
4632 ; Make sure tabels are compiled
4633 (message "updating internal tables...")
4634 (reftex-compute-ref-cite-tables)
4635 (message "updating internal tables...done")
4636 (setq reftex-tables-dirty nil)
4640 ;;;============================================================================
4642 ;;; reftex.el ends here