1 ;; reftex.el --- Minor mode for doing \label, \ref and \cite in LaTeX
2 ;; Copyright (c) 1997, 1998 Free Software Foundation, Inc.
4 ;; Author: Carsten Dominik <dominik@strw.LeidenUniv.nl>
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to the
21 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
22 ;; Boston, MA 02111-1307, USA.
24 ;;---------------------------------------------------------------------------
28 ;; RefTeX is a minor mode with distinct support for \ref, \label and
29 ;; \cite commands in (multi-file) LaTeX documents.
30 ;; Labels are created semi-automatically. Definition context of labels is
31 ;; provided when creating a reference. Citations are simplified with
32 ;; efficient database lookup. A table of contents buffer provides easy
33 ;; access to any part of a document.
36 ;; To turn RefTeX Minor Mode on and off in a particular buffer, use
39 ;; To turn on RefTeX Minor Mode for all LaTeX files, add one of the
40 ;; following lines to your .emacs file:
42 ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
43 ;; (add-hook 'latex-mode-hook 'turn-on-reftex) ; with Emacs latex mode
49 ;; There is an extensive texinfo document describing RefTeX in detail.
50 ;; When you are getting reftex.el with the Emacs distribution, the
51 ;; info files should already be installed. To view this
52 ;; documentation, use `M-x reftex-info RET'.
54 ;; The documentation is also available at
56 ;; http://www.strw.leidenuniv.nl/~dominik/Tools/
58 ;;---------------------------------------------------------------------------
60 ;; RefTeX in a Nutshell
61 ;; ====================
63 ;; 1. Labels and References
64 ;; RefTeX distinguishes labels for different environments. It always
65 ;; knows if a certain label references a figure, table etc.. You can
66 ;; configure RefTeX to recognize any additional labeled environments
67 ;; you have defined yourself (variable REFTEX-LABEL-ALIST).
69 ;; Type `C-c (' (`reftex-label') to insert a label at point.
71 ;; - derive a label from context (default for section labels)
73 ;; - insert a simple label consisting of a prefix and a number
74 ;; (default for equations, enumerate items, and footnotes)
77 ;; - prompt for a label string (figures and tables).
79 ;; Which labels are created how is configurable (variable
80 ;; REFTEX-INSERT-LABEL-FLAGS).
82 ;; - Referencing Labels
83 ;; Referencing labels is a snap and I promise you'll love it.
84 ;; In order to make a reference, type `C-c )'
85 ;; (`reftex-reference'). This shows an outline of the document
86 ;; with all labels of a certain type (figure, equation,...) and
87 ;; context of the label definition. Selecting one of the labels
88 ;; inserts a `\ref' macro into the original buffer. Online help
89 ;; during the selection is available with `?'.
92 ;; After typing `C-c [' (`reftex-citation'), RefTeX will let you
93 ;; specify a regular expression to search in current BibTeX database
94 ;; files (as specified in the `\bibliography' command) and pull out a
95 ;; formatted list of matches for you to choose from. The list is
96 ;; *formatted* and sorted, thus much easier to read than the raw
97 ;; database entries. The text inserted into the buffer is by default
98 ;; just `\cite{KEY}', but can also contain author names and the year
99 ;; in a configurable way (variable REFTEX-CITE-FORMAT).
101 ;; 3. Viewing Cross References
102 ;; With point on or anywhere before a `\ref' or `\cite' macro, press
103 ;; `C-c &' (`reftex-view-crossref'). This will display the
104 ;; corresponding label definition or BibTeX database entry in another
107 ;; 4. Table of Contents
108 ;; Typing `C-c =' (`reftex-toc') will show a table of contents of the
109 ;; document. From that buffer, you can jump quickly to every part of
112 ;; 5. Multifile Documents
113 ;; Multifile Domuments are fully supported. RefTeX will provide cross
114 ;; referencing information from all files which are part of the
115 ;; document. You may also use it to reference labels in external
116 ;; documents (in cooperation with the LaTeX package `xr').
118 ;; 6. Document Parsing
119 ;; RefTeX needs to parse the document in order to find labels and
120 ;; other information. It will do it automatically once, when you
121 ;; start working with a document. Re-parsing should not be necessary
122 ;; too often since RefTeX updates its lists internally when you make
123 ;; a new label with `reftex-label'. To enforce reparsing, call any
124 ;; of the commands described above with a raw `C-u' prefix, or press
125 ;; the `r' key in the label selection buffer or the table of contents
128 ;;---------------------------------------------------------------------------
133 ;; Carsten Dominik <dominik@strw.LeidenUniv.nl>
135 ;; with contributions from Stephen Eglen
137 ;; The newest version of RefTeX can be found at
139 ;; http://www.strw.leidenuniv.nl/~dominik/Tools/
140 ;; ftp://strw.leidenuniv.nl/pub/dominik/
142 ;; The version at this site is compatible with Emacs 19 - the version
143 ;; distributed with Emacs 20 is not.
147 ;; Thanks to the people on the Net who have used RefTeX and helped
148 ;; developing it with their reports. In particular thanks to
150 ;; F. Burstall, Alastair Burt, Soren Dayton, Stephen Eglen,
151 ;; Karl Eichwalder, Peter Galbraith, Dieter Kraft, Adrian Lanz,
152 ;; Rory Molinari, Laurent Mugnier, Sudeep Kumar Palat, Daniel Polani,
153 ;; Robin Socha, Richard Stanton, Allan Strand, Jan Vroonhof,
156 ;; The view crossref feature was inspired by the similar function in
157 ;; Peter Galbraith's bib-cite.el.
159 ;; Finally thanks to Uwe Bolick who first got me (some years ago) into
160 ;; supporting LaTeX labels and references with an Editor (which was
161 ;; MicroEmacs at the time).
163 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
168 (eval-when-compile (require 'cl))
170 ;; Stuff that needs to be there when we use defcustom
171 ;; --------------------------------------------------
175 (defvar reftex-tables-dirty t
176 "Flag showing if tables need to be re-computed.")
179 (defun reftex-set-dirty (symbol value)
180 (setq reftex-tables-dirty t)
184 (defmacro reftex-fp (n)
185 (if (fboundp 'forward-point)
186 (list 'forward-point n)
187 (list '+ '(point) n))))
189 ;;; Begin of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
191 ;; Define the two constants which are needed during compilation
194 (defconst reftex-label-alist-builtin
196 ;; Some aliases, mostly for backward compatibility
197 (Sideways "Alias for -->rotating" (rotating))
198 (AMSTeX "amsmath with eqref macro"
199 ((nil ?e nil "~\\eqref{%s}")
202 ;; Individual package defaults
203 (amsmath "AMS-LaTeX math environments"
204 (("align" ?e nil nil eqnarray-like)
205 ("gather" ?e nil nil eqnarray-like)
206 ("multline" ?e nil nil t)
207 ("flalign" ?e nil nil eqnarray-like)
208 ("alignat" ?e nil nil alignat-like)
209 ("xalignat" ?e nil nil alignat-like)
210 ("xxalignat" ?e nil nil alignat-like)
211 ("subequations" ?e nil nil t)))
213 (endnotes "The \\endnote macro"
214 (("\\endnote[]{}" ?n nil nil 2 (regexp "Endnotes?"))))
216 (fancybox "The Beqnarray environment"
217 (("Beqnarray" ?e nil nil eqnarray-like)))
219 (floatfig "The floatingfigure environment"
220 (("floatingfigure" ?f nil nil caption)))
222 (longtable "The longtable environment"
223 (("longtable" ?t nil nil caption)))
225 (picinpar "The figwindow and tabwindow environments"
226 (("figwindow" ?f nil nil 1)
227 ("tabwindow" ?f nil nil 1)))
229 (rotating "Sidewaysfigure and table"
230 (("sidewaysfigure" ?f nil nil caption)
231 ("sidewaystable" ?t nil nil caption)))
233 (sidecap "CSfigure and SCtable"
234 (("SCfigure" ?f nil nil caption)
235 ("SCtable" ?t nil nil caption)))
237 (subfigure "Subfigure environments/macro"
238 (("subfigure" ?f nil nil caption)
239 ("subfigure*" ?f nil nil caption)
240 ("\\subfigure[]{}" ?f nil nil 1)))
242 (supertab "Supertabular environment"
243 (("supertabular" ?t nil nil "\\tablecaption{")))
245 (wrapfig "The wrapfigure environment"
246 (("wrapfigure" ?f nil nil caption)))
248 ;; The LaTeX core stuff
249 (LaTeX "LaTeX default environments"
250 (("section" ?s "sec:" "~\\ref{%s}" (nil . t)
251 (regexp "Parts?" "Chapters?" "Chap\\." "Sections?" "Sect?\\."
252 "Paragraphs?" "Par\\."
253 "\\\\S" "\247" "Teile?" "Kapitel" "Kap\\." "Abschnitte?"
254 "Appendi\\(x\\|ces\\)" "App\\." "Anh\"?ange?" "Anh\\."))
256 ("enumerate" ?i "item:" "~\\ref{%s}" item
257 (regexp "Items?" "Punkte?"))
259 ("equation" ?e "eq:" "~(\\ref{%s})" t
260 (regexp "Equations?" "Eqs?\\." "Eqn\\." "Gleichung\\(en\\)?" "Gl\\."))
261 ("eqnarray" ?e "eq:" nil eqnarray-like)
263 ("figure" ?f "fig:" "~\\ref{%s}" caption
264 (regexp "Figure[sn]?" "Figs?\\." "Abbildung\\(en\\)?" "Abb\\."))
265 ("figure*" ?f nil nil caption)
267 ("table" ?t "tab:" "~\\ref{%s}" caption
268 (regexp "Tables?" "Tab\\." "Tabellen?"))
269 ("table*" ?t nil nil caption)
271 ("\\footnote[]{}" ?n "note:" "~\\ref{%s}" 2
272 (regexp "Footnotes?" "Notes?"))
274 ("any" ?\ " " "~\\ref{%s}" nil)))
277 "The default label environment descriptions.
278 Lower-case symbols correspond to a style file of the same name in the LaTeX
279 distribution. Mixed-case symbols are convenience aliases.")
281 (defconst reftex-cite-format-builtin
283 (default "Default macro \\cite{%l}"
285 (natbib "The Natbib package"
286 ((?\C-m . "\\cite{%l}")
288 (?T . "\\citet*{%l}")
290 (?P . "\\citep*{%l}")
291 (?e . "\\citep[e.g.][]{%l}")
292 (?a . "\\citeauthor{%l}")
293 (?y . "\\citeyear{%l}")))
294 (harvard "The Harvard package"
295 ((?\C-m . "\\cite{%l}")
297 (?t . "\\citeasnoun{%l}")
298 (?n . "\\citeasnoun{%l}")
299 (?s . "\\possessivecite{%l}")
300 (?e . "\\citeaffixed{%l}{?}")
301 (?y . "\\citeyear{%l}")
302 (?a . "\\citename{%l}")))
303 (chicago "The Chicago package"
304 ((?\C-m . "\\cite{%l}")
306 (?T . "\\shortciteN{%l}")
308 (?P . "\\shortcite{%l}")
310 (?A . "\\shortciteA{%l}")
311 (?y . "\\citeyear{%l}")))
312 (astron "The Astron package"
313 ((?\C-m . "\\cite{%l}")
315 (?t . "%2a (\\cite{%l})")))
316 (author-year "Do-it-yourself Author-year"
317 ((?\C-m . "\\cite{%l}")
318 (?t . "%2a (%y)\\nocite{%l}")
319 (?p . "(%2a %y\\nocite{%l})")))
320 (locally "Full info in parenthesis"
321 "(%2a %y, %j %v, %P, %e: %b, %u, %s %<)")
322 ;; undocumented feature: `%<' kills white space and punctuation locally.
324 "Builtin versions of for the citation format.
325 The following conventions are valid for all alist entries:
326 `?\C-m' should always point to a straight \\cite{%l} macro.
327 `?t' should point to a textual citation (citation as a noun).
328 `?p' should point to a parenthetical citation.")
331 ;; Configuration Variables and User Options for RefTeX ------------------
334 "LaTeX label and citation support."
336 :link '(url-link :tag "Home Page"
337 "http://strw.leidenuniv.nl/~dominik/Tools/")
338 :link '(emacs-commentary-link :tag "Commentary in reftex.el" "reftex.el")
342 (defun reftex-customize ()
343 "Call the customize function with reftex as argument."
345 ;; Depending on the customize version we can call different functions.
347 ((fboundp 'customize-browse)
348 (customize-browse 'reftex))
349 ((fboundp 'customize-group)
350 (customize-group 'reftex))
351 ((fboundp 'customize)
353 (t (error "Custom.el not available"))))
355 (defun reftex-create-customize-menu ()
356 "Create a full customization menu for RefTeX."
358 (if (fboundp 'customize-menu-create)
362 `(["Browse RefTeX group" reftex-customize t]
364 ,(customize-menu-create 'reftex)
366 ["Save" Custom-save t]
367 ["Reset to Current" Custom-reset-current t]
368 ["Reset to Saved" Custom-reset-saved t]
369 ["Reset to Standard Settings" Custom-reset-standard t]))
370 (message "\"Ref\"-menu now contains full customization menu"))
371 (error "Cannot expand menu (outdated version of cus-edit.el)")))
373 (defun reftex-show-commentary ()
374 "Use the finder to view the file documentation from `reftex.el'."
377 (finder-commentary "reftex.el"))
379 (defun reftex-info ()
380 "Read documentation for RefTeX in the info system."
383 (Info-goto-node "(reftex)"))
385 ;; Support for \label and \ref --------------------------------------
387 (defgroup reftex-label-support nil
388 "Support for creation, insertion and referencing of labels in LaTeX."
391 (defgroup reftex-defining-label-environments nil
392 "Definition of environments and macros to do with label."
393 :group 'reftex-label-support)
395 ;; Make a constant for the customization stuff
398 '((const :tag "Default position" t)
399 (const :tag "After label" nil)
400 (number :tag "Macro arg nr" 1)
401 (regexp :tag "Regexp" "")
402 (const :tag "Caption in float" caption)
403 (const :tag "Item in list" item)
404 (const :tag "Eqnarray-like" eqnarray-like)
405 (const :tag "Alignat-like" alignat-like)
406 (symbol :tag "Function" my-func))))
408 (defcustom reftex-default-label-alist-entries
409 '(amsmath endnotes fancybox floatfig longtable picinpar
410 rotating sidecap subfigure supertab wrapfig LaTeX)
411 "Default label alist specifications. LaTeX should be the last entry.
412 This list describes the default label environments RefTeX should always use.
413 It is probably a mistake to remove the LaTeX symbol from this list.
416 LaTeX The standard LaTeX environments.
417 Sideways The sidewaysfigure and sidewaystable environments.
418 AMSTeX The math environments in the AMS-LaTeX amsmath package.
420 For the full list of options, try
422 M-x customize-variable RET reftex-default-label-alist-entries RET."
423 :group 'reftex-defining-label-environments
424 :set 'reftex-set-dirty
432 (list 'const ':tag (concat (symbol-name (nth 0 x))
435 reftex-label-alist-builtin)))
437 (defcustom reftex-label-alist nil
438 "Alist with information on environments for \\label-\\ref use.
440 This docstring is easier to understand after reading the configuration
441 examples in `reftex.el'. Looking at the builtin defaults in the constant
442 `reftex-label-alist-builtin' may also be instructive.
444 Set this variable to define additions and changes to the default. The only
445 things you MUST NOT change is that `?s' is the type indicator for section
446 labels, and SPC for the `any' label type. These are hard-coded at other
449 Each list entry describes either an environment carrying a counter for use
450 with \\label and \\ref, or a LaTeX macro defining a label as (or inside)
451 one of its arguments. The elements of each list entry are:
453 0. Name of the environment (like \"table\") or macro (like \"\\\\myfig\").
454 For macros, indicate the macro arguments for best results, as in
455 \"\\\\myfig[]{}{}{*}{}\". Use square brackets for optional arguments,
456 a star to mark the label argument, if any. The macro does not have to
457 have a label argument - you could also use \\label{..} inside one of
459 Special names: `section' for section labels, `any' to define a group
460 which contains all labels.
461 This may also be nil if the entry is only meant to change some settings
462 associated with the type indicator character (see below).
464 1. Type indicator character, like `?t', must be a printable ASCII character.
465 The type indicator is a single character which defines a label type.
466 Any label inside the environment or macro is assumed to belong to this
467 type. The same character may occur several times in this list, to cover
468 cases in which different environments carry the same label type (like
469 `equation' and `eqnarray').
471 2. Label prefix string, like \"tab:\".
472 The prefix is a short string used as the start of a label. It may be the
473 empty string. The prefix may contain the following `%' escapes:
474 %f Current file name with directory and extension stripped.
475 %F Current file name relative to directory of master file.
476 %u User login name, on systems which support this.
478 Example: In a file `intro.tex', \"eq:%f:\" will become \"eq:intro:\").
480 3. Format string for reference insert in buffer. `%s' will be replaced by
482 When the format starts with `~', the `~' will only be inserted if
483 there is not already a whitespace before point.
485 4. Indication on how to find the short context.
486 - If nil, use the text following the \\label{...} macro.
488 - the section heading for section labels.
489 - text following the \\begin{...} statement of environments.
490 (not a good choice for environments like eqnarray or enumerate,
491 where one has several labels in a single environment).
492 - text after the macro name (starting with the first arg) for macros.
493 - If an integer, use the nth argument of the macro. As a special case,
494 1000 means to get text after the last macro argument.
495 - If a string, use as regexp to search *backward* from the label. Context
496 is then the text following the end of the match. E.g. putting this to
497 \"\\\\\\\\caption[[{]\" will use the caption in a figure or table
499 \"\\\\\\\\begin{eqnarray}\\\\|\\\\\\\\\\\\\\\\\" works for eqnarrays.
500 - If any of `caption', `item', `eqnarray-like', `alignat-like', this
501 symbol will internally be translated into an appropriate regexp
502 (see also the variable `reftex-default-context-regexps').
503 - If a function, call this function with the name of the environment/macro
504 as argument. On call, point will be just after the \\label macro. The
505 function is expected to return a suitable context string. It should
506 throw an exception (error) when failing to find context.
507 As an example, here is a function returning the 10 chars following
508 the label macro as context:
510 (defun my-context-function (env-or-mac)
511 (if (> (point-max) (+ 10 (point)))
512 (buffer-substring (point) (+ 10 (point)))
513 (error \"Buffer too small\")))
515 Label context is used in two ways by RefTeX: For display in the label
516 menu, and to derive a label string. If you want to use a different
517 method for each of these, specify them as a dotted pair.
518 E.g. `(nil . t)' uses the text after the label (nil) for display, and
519 text from the default position (t) to derive a label string. This is
520 actually used for section labels.
522 Setting the variable `reftex-use-text-after-label-as-context' to t
523 overrides the setting here.
525 5. List of magic words which identify a reference to be of this type.
526 If the word before point is equal to one of these words when calling
527 `reftex-reference', the label list offered will be automatically
528 restricted to labels of the correct type.
529 If the first element of this wordlist is the symbol `regexp', the
530 strings are interpreted as regular expressions. RefTeX will add
531 a \"\\\\W\" to the beginning and other stuff to the end of the regexp.
533 If the type indicator characters of two or more entries are the same, RefTeX
535 - the first non-nil format and prefix
536 - the magic words of all involved entries.
538 Any list entry may also be a symbol. If that has an association in
539 `reftex-label-alist-builtin', the cddr of that association is spliced into the
540 list. However, builtin defaults should normally be set with the variable
541 `reftex-default-label-alist-entries."
542 :group 'reftex-defining-label-environments
543 :set 'reftex-set-dirty
547 :value ("" ?a nil nil nil nil)
548 (list :tag "Detailed label alist entry"
549 :value ("" ?a nil nil nil nil)
550 (choice :tag "Environment or \\macro "
551 (const :tag "Ignore, just use typekey" nil)
553 (character :tag "Typekey character " ?a)
554 (choice :tag "Label prefix string "
555 (const :tag "Default" nil)
556 (string :tag "String" "lab:"))
557 (choice :tag "Label reference format"
558 (const :tag "Default" nil)
559 (string :tag "String" "~\\ref{%s}"))
560 (choice :tag "Context"
564 (cons :tag "Split methods"
566 :tag " Display context "
569 :tag " Derive label context"
571 (repeat :tag "List of Magic Words" (string)))
578 (list 'const ':tag (concat (symbol-name (nth 0 x)))
580 reftex-label-alist-builtin)))))
582 ;; LaTeX section commands and level numbers
583 (defcustom reftex-section-levels
589 ("subsubsection" . 4)
592 ("subsubparagraph" . 7)
594 "Commands and levels used for defining sections in the document.
595 The car of each cons cell is the name of the section macro. The cdr is a
596 number indicating its level."
597 :group 'reftex-defining-label-environments
598 :set 'reftex-set-dirty
600 (cons (string :tag "sectioning macro" "")
601 (number :tag "level " 0))))
603 (defcustom reftex-default-context-regexps
604 '((caption . "\\\\\\(rot\\)?caption\\*?[[{]")
605 (item . "\\\\item\\(\\[[^]]*\\]\\)?")
606 (eqnarray-like . "\\\\begin{%s}\\|\\\\\\\\")
607 (alignat-like . "\\\\begin{%s}{[0-9]*}\\|\\\\\\\\"))
608 "Alist with default regular expressions for finding context.
609 The form (format regexp (regexp-quote environment)) is used to calculate
610 the final regular expression - so %s will be replaced with the environment
612 :group 'reftex-defining-label-environments
613 :type '(repeat (cons (symbol) (regexp))))
615 (defcustom reftex-use-text-after-label-as-context nil
616 "*t means, grab context from directly after the \\label{..} macro.
617 This is the fastest method for obtaining context of the label definition, but
618 requires discipline when placing labels. Setting this variable to t takes
619 precedence over the individual settings in `reftex-label-alist'.
620 This variable may be set to t, nil, or a string of label type letters
621 indicating the label types for which it should be true."
622 :group 'reftex-defining-label-environments
623 :set 'reftex-set-dirty
625 (const :tag "on" t) (const :tag "off" nil)
626 (string :tag "Selected label types")))
630 (defgroup reftex-making-and-inserting-labels nil
631 "Options on how to create new labels."
632 :group 'reftex-label-support)
634 (defcustom reftex-insert-label-flags '("s" "sft")
635 "Flags governing label insertion. First flag DERIVE, second flag PROMPT.
637 If DERIVE is t, RefTeX will try to derive a sensible label from context.
638 A section label for example will be derived from the section heading.
639 The conversion of the context to a legal label is governed by the
640 specifications given in `reftex-derive-label-parameters'.
641 If RefTeX fails to derive a label, it will prompt the user.
642 If DERIVE is nil, the label generated will consist of the prefix and a
643 unique number, like `eq:23'.
645 If PROMPT is t, the user will be prompted for a label string. The prompt will
646 already contain the prefix, and (if DERIVE is t) a default label derived from
647 context. When PROMPT is nil, the default label will be inserted without
650 So the combination of DERIVE and PROMPT controls label insertion. Here is a
651 table describing all four possibilities:
654 -------------------------------------------------------------------------
655 nil nil Insert simple label, like eq:22 or sec:13. No query.
656 nil t Prompt for label.
657 t nil Derive a label from context and insert without query.
658 t t Derive a label from context and prompt for confirmation.
660 Each flag may be set to t, nil, or a string of label type letters
661 indicating the label types for which it should be true. The strings work
662 like character classes.
663 Thus, the combination may be set differently for each label type. The
664 default settings \"s\" and \"sft\" mean: Derive section labels from headings
665 (with confirmation). Prompt for figure and table labels. Use simple labels
666 without confirmation for everything else.
667 The available label types are: s (section), f (figure), t (table), i (item),
668 e (equation), n (footnote), plus any definitions in `reftex-label-alist'."
669 :group 'reftex-making-and-inserting-labels
670 :type '(list (choice :tag "Derive label from context"
671 (const :tag "always" t)
672 (const :tag "never" nil)
673 (string :tag "selected label types" ""))
674 (choice :tag "Prompt for label string "
675 :entry-format " %b %v"
676 (const :tag "always" t)
677 (const :tag "never" nil)
678 (string :tag "selected label types" ""))))
680 (defcustom reftex-derive-label-parameters '(3 20 t 1 "-"
681 ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is"))
682 "Parameters for converting a string into a label.
683 NWORDS Number of words to use.
684 MAXCHAR Maximum number of characters in a label string.
685 ILLEGAL nil: Throw away any words containing characters illegal in labels.
686 t: Throw away only the illegal characters, not the whole word.
687 ABBREV nil: Never abbreviate words.
688 t: Always abbreviate words (see `reftex-abbrev-parameters').
689 not t and not nil: Abbreviate words if necessary to shorten
690 label string below MAXCHAR.
691 SEPARATOR String separating different words in the label.
692 IGNOREWORDS List of words which should not be part of labels."
693 :group 'reftex-making-and-inserting-labels
694 :type '(list (integer :tag "Number of words " 3)
695 (integer :tag "Maximum label length " 20)
696 (choice :tag "Illegal characters in words"
697 (const :tag "throw away entire word" nil)
698 (const :tag "throw away single chars" t))
699 (choice :tag "Abbreviate words "
700 (const :tag "never" nil)
701 (const :tag "always" t)
702 (const :tag "when label is too long" 1))
703 (string :tag "Separator between words " "-")
704 (repeat :tag "Ignore words"
705 :entry-format " %i %d %v"
708 (defcustom reftex-label-illegal-re "[\000-\040\177-\377\\\\#$%&~^_{}]"
709 "Regexp matching characters not legal in labels.
710 For historic reasons, this character class comes *with* the [] brackets."
711 :group 'reftex-making-and-inserting-labels
712 :type '(regexp :tag "Character class"))
714 (defcustom reftex-abbrev-parameters '(4 2 "^saeiou" "aeiou")
715 "Parameters for abbreviation of words.
716 MIN-CHARS Minimum number of characters remaining after abbreviation.
717 MIN-KILL Minimum number of characters to remove when abbreviating words.
718 BEFORE Character class before abbrev point in word.
719 AFTER Character class after abbrev point in word."
720 :group 'reftex-making-and-inserting-labels
722 (integer :tag "Minimum chars per word" 4)
723 (integer :tag "Shorten by at least " 2)
724 (string :tag "cut before char class " "^saeiou")
725 (string :tag "cut after char class " "aeiou")))
727 (defcustom reftex-format-label-function nil
728 "Function which produces the string to insert as a label definition.
729 Normally should be nil, unless you want to do something fancy.
730 The function will be called with two arguments, the LABEL and the DEFAULT
731 FORMAT, which usually is `\label{%s}'. The function should return the
732 string to insert into the buffer."
733 :group 'reftex-making-and-inserting-labels
738 (defgroup reftex-referencing-labels nil
739 "Options on how to reference labels."
740 :group 'reftex-label-support)
744 '((const :tag "on" t)
745 (const :tag "off" nil)
746 (string :tag "Selected label types"))))
748 (defcustom reftex-label-menu-flags '(t t nil nil nil nil t nil)
749 "List of flags governing the label menu makeup.
752 TABLE-OF-CONTENTS Show the labels embedded in a table of context.
753 SECTION-NUMBERS Include section numbers (like 4.1.3) in table of contents.
754 COUNTERS Show counters. This just numbers the labels in the menu.
755 NO-CONTEXT Non-nil means do NOT show the short context.
756 FOLLOW Follow full context in other window.
757 SHOW-COMMENTED Show labels from regions which are commented out.
758 MATCH-IN-TOC Obsolete flag.
759 SHOW FILES Show begin and end of included files.
761 Each of these flags can be set to t or nil, or to a string of type letters
762 indicating the label types for which it should be true. These strings work
763 like character classes in regular expressions. Thus, setting one of the
764 flags to \"sf\" makes the flag true for section and figure labels, nil
765 for everything else. Setting it to \"^sf\" makes it the other way round.
766 The available label types are: s (section), f (figure), t (table), i (item),
767 e (equation), n (footnote), plus any definitions in `reftex-label-alist'.
769 Most options can also be switched from the label menu itself - so if you
770 decide here to not have a table of contents in the label menu, you can still
771 get one interactively during selection from the label menu."
772 :group 'reftex-referencing-labels
775 (choice :tag "Embed in table of contents " ,@reftex-tmp)
776 (choice :tag "Show section numbers " ,@reftex-tmp)
777 (choice :tag "Show individual counters " ,@reftex-tmp)
778 (choice :tag "Hide short context " ,@reftex-tmp)
779 (choice :tag "Follow context in other window " ,@reftex-tmp)
780 (choice :tag "Show commented labels " ,@reftex-tmp)
781 (choice :tag "Obsolete flag, Don't use. " ,@reftex-tmp)
782 (choice :tag "Show begin/end of included files" ,@reftex-tmp)))
784 (defcustom reftex-vref-is-default nil
785 "*Non-nil means, the varioref macro \\vref is used as default.
786 In the selection buffer, the `v' key toggles the reference macro between
787 `\\ref' and `\\vref'. The value of this variable determines the default
788 which is active when entering the selection process.
789 Instead of nil or t, this may also be a string of type letters indicating
790 the label types for which it should be true."
791 :group 'reftex-referencing-labels
792 :type `(choice :tag "\\vref is default macro" ,@reftex-tmp))
794 (defcustom reftex-level-indent 2
795 "*Number of spaces to be used for indentation per section level."
796 :group 'reftex-referencing-labels
799 (defcustom reftex-guess-label-type t
800 "*Non-nil means, `reftex-reference' will try to guess the label type.
801 To do that, RefTeX will look at the word before the cursor and compare it with
802 the words given in `reftex-label-alist'. When it finds a match, RefTeX will
803 immediately offer the correct label menu - otherwise it will prompt you for
804 a label type. If you set this variable to nil, RefTeX will always prompt."
805 :group 'reftex-referencing-labels
808 (defcustom reftex-format-ref-function nil
809 "Function which produces the string to insert as a reference.
810 Normally should be nil, because the format to insert a reference can
811 already be specified in `reftex-label-alist'.
812 The function will be called with two arguments, the LABEL and the DEFAULT
813 FORMAT, which normally is `~\ref{%s}'. The function should return the
814 string to insert into the buffer."
815 :group 'reftex-referencing-labels
818 ;; BibteX citation configuration ----------------------------------------
820 (defgroup reftex-citation-support nil
821 "Support for referencing bibliographic data with BibTeX."
824 (defcustom reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB")
825 "*List of env vars which might contain the path to BibTeX database files."
826 :group 'reftex-citation-support
827 :set 'reftex-set-dirty
828 :type '(repeat (string :tag "Environment variable")))
830 (defcustom reftex-bibfile-ignore-list nil
831 "*List of files in \\bibliography{..} RefTeX should *not* parse.
832 The file names have to be in the exact same form as in the bibliography
833 macro - i.e. without the `.bib' extension.
834 Intended for files which contain only `@string' macro definitions and the
835 like, which are ignored by RefTeX anyway."
836 :group 'reftex-citation-support
837 :set 'reftex-set-dirty
838 :type '(repeat (string :tag "File name")))
840 (defcustom reftex-default-bibliography nil
841 "*List of BibTeX database file which should be used if none are specified.
842 When `reftex-citation' is called from a document which has neither a
843 `\bibliography{..}' statement nor a `thebibliography' environment,
844 RefTeX will scan these files instead. Intended for using
845 `reftex-citation' in non-LaTeX files."
846 :group 'reftex-citation-support
847 :type '(repeat (file)))
849 (defcustom reftex-sort-bibtex-matches 'reverse-year
850 "*Sorting of the entries found in BibTeX databases by reftex-citation.
852 nil Do not sort entries.
853 'author Sort entries by author name.
854 'year Sort entries by increasing year.
855 'reverse-year Sort entries by decreasing year."
856 :group 'reftex-citation-support
857 :type '(choice (const :tag "not" nil)
858 (const :tag "by author" author)
859 (const :tag "by year" year)
860 (const :tag "by year, reversed" reverse-year)))
862 (defcustom reftex-cite-format 'default
863 "*The format of citations to be inserted into the buffer.
864 It can be a string or an alist. In the simplest case this is just
865 the string \"\\cite{%l}\", which is also the default. See the
866 definition of `reftex-cite-format-builtin' for more complex examples.
868 If `reftex-cite-format' is a string, it will be used as the format.
869 In the format, the following percent escapes will be expanded.
871 %l The BibTeX label of the citation.
872 %a List of author names, see also `reftex-cite-punctuation.
873 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
874 %A First author name only.
875 %e Works like %a, but on list of editor names. (%2e and %E work a well)
877 It is also possible to access all other BibTeX database fields:
878 %b booktitle %c chapter %d edition %h howpublished
879 %i institution %j journal %k key %m month
880 %n number %o organization %p pages %P first page
881 %r address %s school %u publisher %t title
884 Usually, only %l is needed. Try, however, (setq reftex-comment-citations t).
886 Beware that all this only works when using BibTeX database files. When
887 citations are made from the \\bibitems in an explicit thebibliography
888 environment, only %l is available.
890 If `reftex-cite-format' is an alist of characters and strings, the user
891 will be prompted for a character to select one of the possible format
893 In order to configure this variable, you can either set
894 `reftex-cite-format' directly yourself or set it to the SYMBOL of one of
895 the predefined styles (see `reftex-cite-format-builtin'). E.g.:
896 (setq reftex-cite-format 'harvard)"
897 :group 'reftex-citation-support
900 :format "%{%t%}: \n%[Value Menu%] %v"
901 (radio :tag "Symbolic Builtins"
907 (list 'const ':tag (concat (symbol-name (nth 0 x))
910 reftex-cite-format-builtin))
911 (string :tag "format string" "\\cite{%l}")
912 (repeat :tag "key-ed format strings"
913 :value ((?\r . "\\cite{%l}")
914 (?t . "\\cite{%l}") (?p . "\\cite{%l}"))
915 (cons (character :tag "Key character" ?\r)
916 (string :tag "Format string" "")))))
918 (defcustom reftex-comment-citations nil
919 "*Non-nil means add a comment for each citation describing the full entry.
920 The comment is formatted according to `reftex-cite-comment-format'."
921 :group 'reftex-citation-support
924 (defcustom reftex-cite-comment-format
925 "%% %2a %y, %j %v, %P, %e: %b, %u, %s %<\n"
926 "Citation format used for commented citations. Must NOT contain %l."
927 :group 'reftex-citation-support
930 (defcustom reftex-cite-punctuation '(", " " \\& " " {\\it et al.}")
931 "Punctuation for formatting of name lists in citations.
932 This is a list of 3 strings.
933 1. normal names separator, like \", \" in Jones, Brown and Miller
934 2. final names separator, like \" and \" in Jones, Brown and Miller
935 3. The \"et al\" string, like \" {\\it et al.}\" in Jones {\\it et al.}"
936 :group 'reftex-citation-support
938 (string :tag "Separator for names ")
939 (string :tag "Separator for last name in list")
940 (string :tag "string used as et al. ")))
942 (defcustom reftex-format-cite-function nil
943 "Function which produces the string to insert as a citation.
944 Normally should be nil, because the format to insert a reference can
945 already be specified in `reftex-cite-format'.
946 The function will be called with two arguments, the CITATION KEY and the
947 DEFAULT FORMAT, which is taken from `reftex-cite-format'. The function
948 should return the string to insert into the buffer."
949 :group 'reftex-citation-support
952 ;; Table of contents configuration --------------------------------------
954 (defgroup reftex-table-of-contents-browser nil
955 "A multifile table of contents browser."
958 (defcustom reftex-toc-follow-mode nil
959 "*Non-nil means, point in *toc* buffer will cause other window to follow.
960 The other window will show the corresponding part of the document.
961 This flag can be toggled from within the *toc* buffer with the `f' key."
962 :group 'reftex-table-of-contents-browser
965 ;; Tuning the parser ----------------------------------------------------
967 (defgroup reftex-optimizations-for-large-documents nil
968 "Configuration of parser speed and memory usage."
971 (defcustom reftex-keep-temporary-buffers 1
972 "*Non-nil means, keep buffers created for parsing and lookup.
973 RefTeX sometimes needs to visit files related to the current document.
974 We distinguish files visited for
975 PARSING: Parts of a multifile document loaded when (re)-parsing the document.
976 LOOKUP: BibTeX database files and TeX files loaded to find a reference,
977 to display label context, etc.
978 The created buffers can be kept for later use, or be thrown away immediately
979 after use, depending on the value of this variable:
981 nil Throw away as much as possible.
983 1 Throw away buffers created for parsing, but keep the ones created
986 If a buffer is to be kept, the file is visited normally (which is potentially
987 slow but will happen only once).
988 If a buffer is to be thrown away, the initialization of the buffer depends
989 upon the variable `reftex-initialize-temporary-buffers'."
990 :group 'reftex-miscellaneous-configurations
992 (const :tag "Throw away everything" nil)
993 (const :tag "Keep everything" t)
994 (const :tag "Keep lookup buffers only" 1)))
996 (defcustom reftex-initialize-temporary-buffers nil
997 "*Non-nil means do initializations even when visiting file temporarily.
998 When nil, RefTeX may turn off find-file hooks and other stuff to briefly
1000 When t, the full default initializations are done (find-file-hook etc.).
1001 Instead of t or nil, this variable may also be a list of hook functions to
1002 do a minimal initialization."
1003 :group 'reftex-miscellaneous-configurations
1005 (const :tag "Read files literally" nil)
1006 (const :tag "Fully initialize buffers" t)
1007 (repeat :tag "Hook functions" :value (nil)
1010 (defcustom reftex-no-include-regexps '("\\.pstex_t\\'") ; default for x-symbol
1011 "*List of regular expressions to exclude certain input files from parsing.
1012 If the name of a file included via \\include or \\input is matched by any
1013 of the regular expressions in this list, that file is not parsed by RefTeX."
1014 :group 'reftex-optimizations-for-large-documents
1015 :type '(repeat (regexp)))
1017 (defcustom reftex-enable-partial-scans nil
1018 "*Non-nil means, re-parse only 1 file when asked to re-parse.
1019 Re-parsing is normally requested with a `C-u' prefix to many RefTeX commands,
1020 or with the `r' key in menus. When this option is t in a multifile document,
1021 we will only parse the current buffer, or the file associated with the label
1022 or section heading near point in a menu. Requesting re-parsing of an entire
1023 multifile document then requires a `C-u C-u' prefix or the capital `R' key
1025 :group 'reftex-optimizations-for-large-documents
1028 (defcustom reftex-allow-automatic-rescan t
1029 "*Non-nil means, RefTeX may rescan the document when this seems necessary.
1030 Currently this applies only to rescanning after label insertion, when
1031 the new label cannot be inserted correctly into the internal label
1033 :group 'reftex-optimizations-for-large-documents
1036 (defcustom reftex-save-parse-info nil
1037 "*Non-nil means, save information gathered with parsing in a file.
1038 The file MASTER.rel in the same directory as MASTER.tex is used to save the
1039 information. When this variable is t,
1040 - accessing the parsing information for the first time in an editing session
1041 will read that file (if available) instead of parsing the document.
1042 - each time (part of) the document is rescanned, a new version of the file
1044 :group 'reftex-optimizations-for-large-documents
1047 (defcustom reftex-use-multiple-selection-buffers nil
1048 "*Non-nil means use a separate selection buffer for each label type.
1049 These buffers are kept from one selection to the next and need not to be
1050 created for each use - so the menu generally comes up faster. The
1051 selection buffers will be erased (and therefore updated) automatically
1052 when new labels in its category are added. See the variable
1053 `reftex-auto-update-selection-buffers'."
1054 :group 'reftex-optimizations-for-large-documents
1057 (defcustom reftex-auto-update-selection-buffers t
1058 "*Non-nil means, selection buffers will be updated automatically.
1059 When a new label is defined with `reftex-label', all selection buffers
1060 associated with that label category are emptied, in order to force an
1061 update upon next use. When nil, the buffers are left alone and have to be
1062 updated by hand, with the `g' key from the label selection process.
1063 The value of this variable will only have any effect when
1064 `reftex-use-multiple-selection-buffers' is non-nil."
1065 :group 'reftex-optimizations-for-large-documents
1068 ;; Fontification and Faces ----------------------------------------------
1070 (defgroup reftex-fontification-configurations nil
1071 "Options concerning the faces used in RefTeX."
1074 (defcustom reftex-use-fonts t
1075 "*Non-nil means, use fonts in *toc* and selection buffers.
1076 Font-lock must be loaded as well to actually get fontified display."
1077 :group 'reftex-fontification-configurations
1080 (defcustom reftex-refontify-context 1
1081 "*Non-nil means, re-fontify the context in the label menu with font-lock.
1082 This slightly slows down the creation of the label menu. It is only necessary
1083 when you definitely want the context fontified.
1085 This option may have 3 different values:
1086 nil Never refontify.
1088 1 Refontify when absolutely necessary, e.g. when with the x-symbol package.
1089 The option is ignored when `reftex-use-fonts' is nil."
1090 :group 'reftex-fontification-configurations
1092 (const :tag "Never" nil)
1093 (const :tag "Always" t)
1094 (const :tag "When necessary" 1)))
1096 (defcustom reftex-highlight-selection 'cursor
1097 "*Non-nil mean, highlight selected text in selection and *toc* buffers.
1098 Normally, the text near the cursor is the selected text, and it is
1099 highlighted. This is the entry most keys in the selction and *toc*
1100 buffers act on. However, if you mainly use the mouse to select an
1101 item, you may find it nice to have mouse-triggered highlighting
1102 instead or as well. The variable may have one of these values:
1104 nil No highlighting.
1105 cursor Highlighting is cursor driven.
1106 mouse Highlighting is mouse driven.
1107 both Both cursor and mouse trigger highlighting."
1108 :group 'reftex-fontification-configurations
1110 (const :tag "Never" nil)
1111 (const :tag "Cursor driven" cursor)
1112 (const :tag "Mouse driven" mouse)
1113 (const :tag "Mouse and Cursor driven." both)))
1115 (defcustom reftex-cursor-selected-face 'highlight
1116 "Face name to highlight cursor selected item in toc and selection buffers.
1117 See also the variable `reftex-highlight-selection'."
1118 :group 'reftex-fontification-configurations
1120 (defcustom reftex-mouse-selected-face 'secondary-selection
1121 "Face name to highlight mouse selected item in toc and selection buffers.
1122 See also the variable `reftex-highlight-selection'."
1123 :group 'reftex-fontification-configurations
1125 (defcustom reftex-file-boundary-face 'font-lock-comment-face
1126 "Face name for file boundaries in selection buffer."
1127 :group 'reftex-fontification-configurations
1129 (defcustom reftex-label-face 'font-lock-constant-face
1130 "Face name for labels in selection buffer."
1131 :group 'reftex-fontification-configurations
1133 (defcustom reftex-section-heading-face 'font-lock-function-name-face
1134 "Face name for section headings in toc and selection buffers."
1135 :group 'reftex-fontification-configurations
1137 (defcustom reftex-toc-header-face 'font-lock-comment-face
1138 "Face name for the header of a toc buffer."
1139 :group 'reftex-fontification-configurations
1141 (defcustom reftex-bib-author-face 'font-lock-keyword-face
1142 "Face name for author names in bib selection buffer."
1143 :group 'reftex-fontification-configurations
1145 (defcustom reftex-bib-year-face 'font-lock-comment-face
1146 "Face name for year in bib selection buffer."
1147 :group 'reftex-fontification-configurations
1149 (defcustom reftex-bib-title-face 'font-lock-function-name-face
1150 "Face name for article title in bib selection buffer."
1151 :group 'reftex-fontification-configurations
1153 (defcustom reftex-bib-extra-face 'font-lock-comment-face
1154 "Face name for bibliographic information in bib selection buffer."
1155 :group 'reftex-fontification-configurations
1158 ;; Miscellaneous configurations -----------------------------------------
1160 (defgroup reftex-miscellaneous-configurations nil
1161 "Collection of further configurations."
1164 (defcustom reftex-extra-bindings nil
1165 "Non-nil means, make additional key bindings on startup.
1166 These extra bindings are located in the users `C-c letter' map."
1167 :group 'reftex-miscellaneous-configurations
1170 (defcustom reftex-plug-into-AUCTeX nil
1171 "*Plug-in flags for AUCTeX interface.
1172 This variable is a list of 4 boolean flags. When a flag is non-nil, it
1175 Flag 1: use `reftex-label' as `LaTeX-label-function'.
1176 Flag 2: use `reftex-arg-label' as `TeX-arg-label'
1177 Flag 3: use `reftex-arg-ref' as `TeX-arg-ref'
1178 Flag 4: use `reftex-arg-cite' as `TeX-arg-cite'
1180 You may also set the variable itself to t or nil in order to turn all
1181 plug-ins on or off, respectively.
1182 \\<LaTeX-mode-map>`LaTeX-label-function' is the function used for label insertion when you
1183 enter a new environment in AUCTeX with \\[LaTeX-environment].
1184 The `TeX-arg-label' etc. functions are for entering macro arguments during
1185 macro insertion with \\[TeX-insert-macro].
1186 See the AUCTeX documentation for more information.
1187 RefTeX uses `fset' to take over the function calls. Changing the variable
1188 may require a restart of Emacs in order to become effective."
1189 :group 'reftex-miscellaneous-configurations
1190 :type '(choice (const :tag "No plug-ins" nil)
1191 (const :tag "All possible plug-ins" t)
1193 :tag "Individual choice"
1194 :value (nil nil nil nil)
1195 (boolean :tag "Use reftex-label as LaTeX-label-function")
1196 (boolean :tag "Use reftex-arg-label as TeX-arg-label ")
1197 (boolean :tag "Use reftex-arg-ref as TeX-arg-ref ")
1198 (boolean :tag "Use reftex-arg-cite as TeX-arg-cite ")
1201 (defcustom reftex-auto-show-entry 'copy
1202 "*Non-nil means, do something when context in other window is hidden.
1203 Some modes like `outline-mode' or `folding-mode' hide parts of buffers.
1204 When RefTeX is asked to show context for a label definition, and the context
1205 is invisible, it can unhide that section permanently (value t), or copy the
1206 context to a temporary buffer (value 'copy)."
1207 :group 'reftex-miscellaneous-configurations
1208 :type '(radio :value copy
1210 (const :tag "Do nothing" nil)
1211 (const :tag "Unhide section permanently" t)
1212 (const :tag "Copy context to show" copy)))
1214 (defcustom reftex-revisit-to-follow t
1215 "*Non-nil means, follow-mode will revisit files if necessary.
1216 When nil, follow-mode will be suspended for stuff in unvisited files."
1217 :group 'reftex-miscellaneous-configurations
1220 (defcustom reftex-load-hook nil
1221 "Hook which is being run when loading reftex.el."
1222 :group 'reftex-miscellaneous-configurations
1225 (defcustom reftex-mode-hook nil
1226 "Hook which is being run when turning on RefTeX mode."
1227 :group 'reftex-miscellaneous-configurations
1230 ;;; End of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1232 ;;;===========================================================================
1234 ;;; Define the formal stuff for a minor mode named RefTeX.
1237 ;; This file corresponds to RefTeX version 3.22
1239 (defvar reftex-mode nil
1240 "Determines if RefTeX minor mode is active.")
1241 (make-variable-buffer-local 'reftex-mode)
1243 (defvar reftex-mode-map (make-sparse-keymap)
1244 "Keymap for RefTeX minor mode.")
1246 (defvar reftex-mode-menu nil)
1249 (defun turn-on-reftex ()
1250 "Turn on RefTeX minor mode."
1254 (defun reftex-mode (&optional arg)
1255 "Minor mode with distinct support for \\label, \\ref and \\cite in LaTeX.
1257 Labels can be created with `\\[reftex-label]' and referenced with `\\[reftex-reference]'.
1258 When referencing, you get a menu with all labels of a given type and
1259 context of the label definition. The selected label is inserted as a
1262 Citations can be made with `\\[reftex-citation]' which will use a regular expression
1263 to pull out a *formatted* list of articles from your BibTeX
1264 database. The selected citation is inserted as a \\cite macro.
1266 A Table of Contents of the entire (multifile) document with browsing
1267 capabilities is available with `\\[reftex-toc]'.
1269 Most command have help available on the fly. This help is accessed by
1270 pressing `?' to any prompt mentioning this feature.
1272 Extensive documentation about RefTeX is in the file header of `reftex.el'.
1273 You can view this information with `\\[reftex-show-commentary]'.
1276 Under X, these and other functions will also be available as `Ref' menu
1279 ------------------------------------------------------------------------------"
1282 (setq reftex-mode (not (or (and (null arg) reftex-mode)
1283 (<= (prefix-numeric-value arg) 0))))
1285 ; Add or remove the menu, and run the hook
1288 (easy-menu-add reftex-mode-menu)
1289 (reftex-plug-into-AUCTeX)
1290 (run-hooks 'reftex-mode-hook))
1291 (easy-menu-remove reftex-mode-menu)))
1293 (or (assoc 'reftex-mode minor-mode-alist)
1294 (push '(reftex-mode " Ref") minor-mode-alist))
1296 (or (assoc 'reftex-mode minor-mode-map-alist)
1297 (push (cons 'reftex-mode reftex-mode-map) minor-mode-map-alist))
1299 ;;; ===========================================================================
1301 ;;; Silence warnings about variables in other packages.
1303 (defvar LaTeX-label-function)
1304 (defvar tex-main-file)
1305 (defvar outline-minor-mode)
1306 (defvar font-lock-fontify-region-function)
1307 (defvar font-lock-syntactic-keywords)
1309 ;;; ===========================================================================
1311 ;;; Interfaces for other packages
1312 ;;; -----------------------------
1317 (defun reftex-arg-label (optional &optional prompt definition)
1318 "Use `reftex-label' to create label. Insert it with `TeX-argument-insert'.
1319 This function is intended for AUCTeX macro support."
1320 (let ((label (reftex-label nil t)))
1321 (if (and definition (not (string-equal "" label)))
1322 (LaTeX-add-labels label))
1323 (TeX-argument-insert label optional optional)))
1325 (defun reftex-arg-ref (optional &optional prompt definition)
1326 "Use `reftex-reference' to select label. Insert with `TeX-argument-insert'.
1327 This function is intended for AUCTeX macro support."
1328 (let ((label (reftex-reference nil t)))
1329 (if (and definition (not (string-equal "" label)))
1330 (LaTeX-add-labels label))
1331 (TeX-argument-insert label optional optional)))
1333 (defun reftex-arg-cite (optional &optional prompt definition)
1334 "Use reftex-citation to select a key. Insert with `TeX-argument-insert'.
1335 This function is intended for AUCTeX macro support."
1336 (let ((key (reftex-citation t)))
1337 (TeX-argument-insert (or key "") optional optional)))
1339 (defun reftex-plug-into-AUCTeX ()
1340 ;; Replace AUCTeX functions with RefTeX functions.
1341 ;; Which functions are replaced is controlled by the variable
1342 ;; `reftex-plug-into-AUCTeX'.
1344 (cond ((eq reftex-plug-into-AUCTeX t) '(t t t t))
1345 ((eq reftex-plug-into-AUCTeX nil) '(nil nil nil nil))
1346 (t reftex-plug-into-AUCTeX))))
1349 (boundp 'LaTeX-label-function)
1350 (setq LaTeX-label-function 'reftex-label))
1353 (fboundp 'TeX-arg-label)
1354 (fset 'TeX-arg-label 'reftex-arg-label))
1357 (fboundp 'TeX-arg-ref)
1358 (fset 'TeX-arg-ref 'reftex-arg-ref))
1361 (fboundp 'TeX-arg-cite)
1362 (fset 'TeX-arg-cite 'reftex-arg-cite))))
1365 (defvar reftex-label-alist-external-add-ons nil
1366 "List of label alist entries added with reftex-add-to-label-alist.")
1368 (defun reftex-add-to-label-alist (entry-list)
1369 "Add label environment descriptions to `reftex-label-alist-external-add-ons'.
1370 The format of ENTRY-LIST is exactly like `reftex-label-alist'. See there
1372 This function makes it possible to support RefTeX from AUCTeX style files.
1373 The entries in ENTRY-LIST will be processed after the user settings in
1374 `reftex-label-alist', and before the defaults (specified in
1375 `reftex-default-label-alist-entries'). Any changes made to
1376 `reftex-label-alist-external-add-ons' will raise a flag to the effect that a
1377 mode reset is done on the next occasion."
1380 (setq entry (car entry-list)
1381 entry-list (cdr entry-list))
1382 (unless (member entry reftex-label-alist-external-add-ons)
1383 (setq reftex-tables-dirty t)
1384 (push entry reftex-label-alist-external-add-ons)))))
1386 ;;; ===========================================================================
1388 ;;; Multifile support
1390 ;;; Technical notes: Multifile works as follows: We keep just one list
1391 ;;; of labels for each master file - this can save a lot of memory.
1392 ;;; `reftex-master-index-list' is an alist which connects the true file name
1393 ;;; of each master file with the symbols holding the information on that
1394 ;;; document. Each buffer has local variables which point to these symbols.
1396 ;; List of variables which handle the multifile stuff.
1397 ;; This list is used to tie, untie, and reset these symbols.
1398 (defconst reftex-multifile-symbols
1399 '(reftex-docstruct-symbol))
1401 ;; Alist connecting master file names with the corresponding lisp symbols.
1402 (defvar reftex-master-index-list nil)
1404 ;; Last index used for a master file.
1405 (defvar reftex-multifile-index 0)
1407 ;; Variable holding the symbol with the label list of the document.
1408 (defvar reftex-docstruct-symbol nil)
1409 (make-variable-buffer-local 'reftex-docstruct-symbol)
1411 (defun reftex-next-multifile-index ()
1412 ;; Return the next free index for multifile symbols.
1413 (incf reftex-multifile-index))
1415 (defun reftex-tie-multifile-symbols ()
1416 ;; Tie the buffer-local symbols to globals connected with the master file.
1417 ;; If the symbols for the current master file do not exist, they are created.
1419 (let* ((master (file-truename (reftex-TeX-master-file)))
1420 (index (assoc master reftex-master-index-list))
1421 (symlist reftex-multifile-symbols)
1425 ;; Find the correct index.
1428 (setq index (cdr index))
1429 ;; Get a new index and add info to the alist.
1430 (setq index (reftex-next-multifile-index)
1432 (push (cons master index) reftex-master-index-list))
1434 ;; Get/create symbols and tie them.
1436 (setq symbol (car symlist)
1437 symlist (cdr symlist)
1438 symname (symbol-name symbol))
1439 (set symbol (intern (concat symname "-" (int-to-string index))))
1440 (put (symbol-value symbol) ':master-index index)
1441 ;; Initialize if new symbols.
1442 (if newflag (set (symbol-value symbol) nil)))
1444 ;; Return t if the symbols did already exist, nil when we've made them.
1447 (defun reftex-untie-multifile-symbols ()
1448 ;; Remove ties from multifile symbols, so that next use makes new ones.
1449 (let ((symlist reftex-multifile-symbols)
1452 (setq symbol (car symlist)
1453 symlist (cdr symlist))
1456 (defun reftex-TeX-master-file ()
1457 ;; Return the name of the master file associated with the current buffer.
1458 ;; When AUCTeX is loaded, we will use it's more sophisticated method.
1459 ;; We also support the default TeX and LaTeX modes by checking for a
1460 ;; variable tex-main-file.
1464 ((fboundp 'TeX-master-file) ; AUCTeX is loaded. Use its mechanism.
1465 (TeX-master-file t))
1466 ((boundp 'TeX-master) ; The variable is defined - lets use it.
1470 ((eq TeX-master 'shared)
1471 (setq TeX-master (read-file-name "Master file: "
1475 (setq TeX-master (read-file-name "Master file: "
1477 ((boundp 'tex-main-file)
1478 ;; This is the variable from the default TeX modes.
1480 ((stringp tex-main-file)
1481 ;; ok, this must be it
1484 ;; In this case, the buffer is its own master.
1485 (buffer-file-name))))
1487 ;; Know nothing about master file. Assume this is a master file.
1488 (buffer-file-name)))))
1491 (error "Need a filename for this buffer. Please save it first."))
1492 ((or (file-exists-p master)
1493 (reftex-get-buffer-visiting master))
1494 ;; We either see the file, or have a buffer on it. OK.
1496 ((or (file-exists-p (concat master ".tex"))
1497 (reftex-get-buffer-visiting (concat master ".tex")))
1498 ;; Ahh, an extra .tex was missing...
1499 (setq master (concat master ".tex")))
1501 ;; Something is wrong here. Throw an exception.
1502 (buffer-file-name)))
1503 ; (error "No such master file %s" master)))
1504 (expand-file-name master)))
1506 (defun reftex-parse-one ()
1507 "Re-parse this file."
1509 (let ((reftex-enable-partial-scans t))
1510 (reftex-access-scan-info '(4))))
1512 (defun reftex-parse-all ()
1513 "Re-parse entire document."
1515 (reftex-access-scan-info '(16)))
1517 (defun reftex-all-document-files (&optional relative)
1518 ;; Return a list of all files belonging to the current document.
1519 ;; When RELATIVE is non-nil, give file names relative to directory
1521 (let* ((all (symbol-value reftex-docstruct-symbol))
1522 (master-dir (file-name-directory (reftex-TeX-master-file)))
1523 (re (concat "\\`" (regexp-quote master-dir)))
1525 (while (setq tmp (assoc 'bof all))
1526 (setq file (nth 1 tmp)
1527 all (cdr (memq tmp all)))
1529 (string-match re file)
1530 (setq file (substring file (match-end 0))))
1531 (push file file-list))
1532 (nreverse file-list)))
1534 (defun reftex-create-tags-file ()
1535 "Create TAGS file by running `etags' on the current document.
1536 The TAGS file is also immediately visited with `visit-tags-table'."
1538 (reftex-access-scan-info current-prefix-arg)
1539 (let* ((master (reftex-TeX-master-file))
1540 (files (reftex-all-document-files))
1541 (cmd (format "etags %s" (mapconcat 'identity files " "))))
1543 (set-buffer (reftex-get-buffer-visiting master))
1544 (message "Running etags to create TAGS file...")
1546 (visit-tags-table "TAGS"))))
1548 ;; History of grep commands.
1549 (defvar reftex-grep-history nil)
1550 (defvar reftex-grep-command "grep -n "
1551 "Last grep command used in \\[reftex-grep-document]; default for next grep.")
1553 (defun reftex-grep-document (grep-cmd)
1554 "Run grep query through all files related to this document.
1555 With prefix arg, force to rescan document.
1556 This works also without an active TAGS table."
1559 (list (read-from-minibuffer "Run grep on document (like this): "
1560 reftex-grep-command nil nil
1561 'reftex-grep-history)))
1562 (reftex-access-scan-info current-prefix-arg)
1563 (let* ((files (reftex-all-document-files t))
1566 (mapconcat 'identity files " "))))
1569 (defun reftex-search-document (&optional regexp)
1570 "Regexp search through all files of the current TeX document.
1571 Starts always in the master file. Stops when a match is found.
1572 To continue searching for next match, use command \\[tags-loop-continue].
1573 This works also without an active TAGS table."
1575 (let ((default (reftex-this-word)))
1577 (setq regexp (read-string (format "Search regexp in document [%s]: "
1579 (if (string= regexp "") (setq regexp (regexp-quote default)))
1581 (reftex-access-scan-info current-prefix-arg)
1582 (tags-search regexp (list 'reftex-all-document-files))))
1584 (defun reftex-query-replace-document (&optional from to delimited)
1585 "Run a query-replace-regexp of FROM with TO over the entire TeX document.
1586 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
1587 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1588 with the command \\[tags-loop-continue].
1589 This works also without an active TAGS table."
1591 (let ((default (reftex-this-word)))
1593 (setq from (read-string (format "Replace regexp in document [%s]: "
1595 (if (string= from "") (setq from (regexp-quote default))))
1597 (setq to (read-string (format "Replace regexp %s with: " from))))
1598 (reftex-access-scan-info current-prefix-arg)
1599 (tags-query-replace from to (or delimited current-prefix-arg)
1600 (list 'reftex-all-document-files))))
1602 (defun reftex-change-label (&optional from to)
1603 "Query replace FROM with TO in all \\label and \\ref commands.
1604 Works on the entire multifile document.
1605 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1606 with the command \\[tags-loop-continue].
1607 This works also without an active TAGS table."
1609 (let ((default (reftex-this-word "-a-zA-Z0-9_*.:")))
1611 (setq from (read-string (format "Replace label globally [%s]: "
1613 (if (string= from "") (setq from default))
1615 (setq to (read-string (format "Replace label %s with: "
1617 (reftex-query-replace-document
1618 (concat "\\\\\\(label\\|[a-z]*ref\\){" (regexp-quote from) "}")
1619 (format "\\\\\\1{%s}" to))))
1621 (defun reftex-save-all-document-buffers ()
1622 "Save all documents associated with the current document.
1623 The function is useful after a global action like replacing or renumbering
1626 (let ((files (reftex-all-document-files))
1629 (while (setq file (pop files))
1630 (setq buffer (reftex-get-buffer-visiting file))
1635 ;;; ===========================================================================
1637 ;;; Functions to create and reference automatic labels.
1639 ;; The following constants are derived from `reftex-label-alist'.
1641 ;; Prompt used for label type queries directed to the user.
1642 (defconst reftex-type-query-prompt nil)
1644 ;; Help string for label type queries.
1645 (defconst reftex-type-query-help nil)
1647 ;; Alist relating label type to reference format.
1648 (defconst reftex-typekey-to-format-alist nil)
1650 ;; Alist relating label type to label affix.
1651 (defconst reftex-typekey-to-prefix-alist nil)
1653 ;; Alist relating environments or macros to label type and context regexp.
1654 (defconst reftex-env-or-mac-alist nil)
1656 ;; List of macros carrying a label.
1657 (defconst reftex-label-mac-list nil)
1659 ;; List of environments carrying a label.
1660 (defconst reftex-label-env-list nil)
1662 ;; List of all typekey letters in use.
1663 (defconst reftex-typekey-list nil)
1665 ;; Alist relating magic words to a label type.
1666 (defconst reftex-words-to-typekey-alist nil)
1668 ;; The last list-of-labels entry used in a reference.
1669 (defvar reftex-last-used-reference (list nil nil nil nil))
1671 ;; The regular expression used to abbreviate words.
1672 (defconst reftex-abbrev-regexp
1675 (make-string (nth 0 reftex-abbrev-parameters) ?.)
1676 "[" (nth 2 reftex-abbrev-parameters) "]*"
1678 "[" (nth 3 reftex-abbrev-parameters) "]"
1679 (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
1681 ;; Global variables used for communication between functions.
1682 (defvar reftex-default-context-position nil)
1683 (defvar reftex-location-start nil)
1684 (defvar reftex-call-back-to-this-buffer nil)
1685 (defvar reftex-select-return-marker (make-marker))
1686 (defvar reftex-active-toc nil)
1687 (defvar reftex-tex-path nil)
1688 (defvar reftex-bib-path nil)
1689 (defvar reftex-last-follow-point nil)
1690 (defvar reftex-prefix)
1692 ;; List of buffers created temporarily for lookup, which should be killed.
1693 (defvar reftex-buffers-to-kill nil)
1695 ;; Regexp to find section statements. Computed from reftex-section-levels.
1696 (defvar reftex-section-regexp nil)
1697 (defvar reftex-section-or-include-regexp nil)
1698 (defvar reftex-everything-regexp nil)
1699 (defvar reftex-find-label-regexp-format nil)
1700 (defvar reftex-find-label-regexp-format2 nil)
1702 ;; The parser functions ----------------------------------
1704 (defvar reftex-memory nil
1705 "Memorizes old variable values to indicate changes in these variables.")
1707 (defun reftex-access-scan-info (&optional rescan file)
1708 ;; Access the scanning info. When the multifile symbols are not yet tied,
1709 ;; tie them. When they are empty or RESCAN is non-nil, scan the document.
1710 ;; When FILE is non-nil, parse only from that file.
1712 ;; Reset the mode if we had changes to important variables.
1713 (when (or reftex-tables-dirty
1714 (not (eq reftex-label-alist (nth 0 reftex-memory)))
1715 (not (eq reftex-label-alist-external-add-ons
1716 (nth 1 reftex-memory)))
1717 (not (eq reftex-default-label-alist-entries
1718 (nth 2 reftex-memory))))
1719 (reftex-reset-mode))
1721 (if (eq reftex-docstruct-symbol nil)
1722 ;; Symbols are not yet tied: Tie them.
1723 (reftex-tie-multifile-symbols))
1725 (when (or (null (symbol-value reftex-docstruct-symbol))
1726 (member rescan '(t 1 (4) (16))))
1727 ;; The docstruct will change: Remove selection buffers.
1729 (reftex-erase-all-selection-buffers)))
1731 (if (and (null (symbol-value reftex-docstruct-symbol))
1732 reftex-save-parse-info)
1733 ;; Try to read the stuff from a file
1734 (reftex-access-parse-file 'read))
1737 ((not (symbol-value reftex-docstruct-symbol))
1738 (reftex-do-parse 1 file))
1739 ((member rescan '(t 1 (4) (16)))
1740 (reftex-do-parse rescan file))))
1742 (defun reftex-do-parse (rescan &optional file)
1743 ;; Do a rescan. When allowed, do only a partial scan from FILE.
1745 ;; Normalize the rescan argument
1746 (setq rescan (cond ((eq rescan t) t)
1748 ((equal rescan '(4)) t)
1749 ((equal rescan '(16)) 1)
1752 ;; Partial scans only when allowed
1753 (unless reftex-enable-partial-scans
1758 (let* ((old-list (symbol-value reftex-docstruct-symbol))
1759 (master (reftex-TeX-master-file))
1760 (master-dir (file-name-as-directory (file-name-directory master)))
1761 (file (or file (buffer-file-name)))
1762 from-file appendix docstruct tmp)
1764 ;; Make sure replacement is really an option here
1765 (when (and (eq rescan t)
1766 (not (and (member (list 'bof file) old-list)
1767 (member (list 'eof file) old-list))))
1768 (message "Scanning whole document (no file section %s)" file)
1770 (when (string= file master)
1771 (message "Scanning whole document (%s is master)" file)
1774 ;; From which file do we start?
1776 (cond ((eq rescan t) (or file master))
1777 ((eq rescan 1) master)
1778 (t (error "horrible!!"))))
1780 ;; Find active toc entry and initialize section-numbers
1781 (setq reftex-active-toc (reftex-last-assoc-before-elt
1782 'toc (list 'bof from-file) old-list)
1783 appendix (reftex-last-assoc-before-elt
1784 'appendix (list 'bof from-file) old-list))
1786 (reftex-init-section-numbers reftex-active-toc appendix)
1789 (message "Scanning entire document...")
1790 (message "Scanning document from %s..." from-file))
1792 (save-window-excursion
1796 (reftex-parse-from-file
1797 from-file docstruct master-dir))
1798 (reftex-kill-temporary-buffers))))
1800 (message "Scanning document... done")
1802 ;; Turn the list around.
1803 (setq docstruct (nreverse docstruct))
1806 (setq docstruct (reftex-replace-label-list-segment
1807 old-list docstruct (eq rescan 1)))
1809 ;; Add all missing information
1810 (unless (assq 'label-numbers docstruct)
1811 (push (cons 'label-numbers nil) docstruct))
1812 (unless (assq 'master-dir docstruct)
1813 (push (cons 'master-dir master-dir) docstruct))
1814 (let* ((bof1 (memq (assq 'bof docstruct) docstruct))
1815 (bof2 (assq 'bof (cdr bof1)))
1816 (is-multi (not (not (and bof1 bof2))))
1817 (entry (or (assq 'is-multi docstruct)
1818 (car (push (list 'is-multi is-multi) docstruct)))))
1819 (setcdr entry (cons is-multi nil)))
1820 (unless (assq 'xr docstruct)
1821 (let* ((allxr (reftex-all-assq 'xr-doc docstruct))
1825 (if (setq tmp (reftex-find-tex-file (nth 2 x)
1827 (cons (nth 1 x) tmp)
1828 (message "Can't find external document %s"
1832 (alist (delete nil alist))
1833 (allprefix (delete nil (mapcar 'car alist)))
1834 (regexp (if allprefix
1836 (mapconcat 'identity allprefix "\\|")
1838 "\\\\\\\\\\\\"))) ; this will never match
1839 (push (list 'xr alist regexp) docstruct)))
1841 (set reftex-docstruct-symbol docstruct)
1843 ;; Save the parsing information into a file?
1844 (if reftex-save-parse-info
1845 (reftex-access-parse-file 'write))))
1847 (defun reftex-is-multi ()
1848 ;; Tell if this is a multifile document. When not sure, say yes.
1849 (let ((entry (assq 'is-multi (symbol-value reftex-docstruct-symbol))))
1854 (defun reftex-parse-from-file (file docstruct master-dir)
1855 ;; Scan the buffer for labels and save them in a list.
1856 (let ((regexp reftex-everything-regexp)
1858 file-found tmp include-file
1864 (setq file-found (reftex-find-tex-file file master-dir))
1866 (push (list 'file-error file) docstruct)
1871 (message "Scanning file %s" file)
1874 (reftex-get-file-buffer-force
1876 (not (eq t reftex-keep-temporary-buffers)))))
1878 ;; Begin of file mark
1879 (setq file (buffer-file-name))
1880 (push (list 'bof file) docstruct)
1887 (while (re-search-forward regexp nil t)
1893 (push (reftex-label-info (reftex-match-string 1) file bound)
1898 (setq bound (point))
1901 (setq toc-entry (reftex-section-info file))
1902 (setq level (nth 5 toc-entry))
1903 (setq highest-level (min highest-level level))
1904 (if (= level highest-level)
1906 "Scanning %s %s ..."
1907 (car (nth level reftex-section-levels))
1910 (push toc-entry docstruct)
1911 (setq reftex-active-toc toc-entry))
1914 ;; It's an include or input
1915 (setq include-file (reftex-match-string 7))
1916 (if (delq nil (mapcar
1917 (lambda (x) (string-match x include-file))
1918 reftex-no-include-regexps))
1921 (push (list 'bof include-file) docstruct)
1922 (push (list 'eof include-file) docstruct))
1925 (reftex-parse-from-file
1927 docstruct master-dir))))
1930 ;; Appendix starts here
1931 (reftex-init-section-numbers nil t)
1932 (push (cons 'appendix t) docstruct))
1935 ;; A macro with label
1937 (let* ((mac (reftex-match-string 10))
1938 (label (progn (goto-char (match-end 10))
1941 (reftex-nth-arg-wrapper
1943 (entry (progn (goto-char (match-end 0))
1945 label file bound mac))))
1946 (push entry docstruct))))
1947 (t (error "This should not happen (reftex-parse-from-file)")))
1951 ;; Find bibliography statement
1952 (when (setq tmp (reftex-locate-bibliography-files master-dir))
1953 (push (cons 'bib tmp) docstruct))
1956 (when (re-search-forward
1957 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
1958 (push (cons 'thebib file) docstruct))
1960 ;; Find external document specifications
1962 (while (re-search-forward "[\n\r][ \t]*\\\\externaldocument\\(\\[\\([^]]*\\)\\]\\)?{\\([^}]+\\)}" nil t)
1963 (push (list 'xr-doc (reftex-match-string 2)
1964 (reftex-match-string 3))
1968 (push (list 'eof file) docstruct))))
1970 ;; Kill the scanned buffer
1971 (reftex-kill-temporary-buffers next-buf))
1976 (defun reftex-locate-bibliography-files (master-dir)
1977 ;; Scan buffer for bibliography macro and return file list.
1980 (goto-char (point-min))
1981 (if (re-search-forward
1982 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\bibliography{[ \t]*\\([^}]+\\)" nil t)
1984 (mapcar (function (lambda (x) (concat x ".bib")))
1986 reftex-bibfile-ignore-list
1988 (reftex-match-string 2)
1989 "[ \t\n\r]*,[ \t\n\r]*")))))
1994 (reftex-find-bib-file file master-dir)))
1997 (defun reftex-last-assoc-before-elt (key elt list)
1998 ;; Find the last association of KEY in LIST before or at ELT
1999 ;; ELT is found in LIST with equal, not eq.
2000 ;; Returns nil when either KEY or elt are not found in LIST.
2001 ;; On success, returns the association.
2002 (let* ((elt (car (member elt list))) ass last-ass)
2004 (while (and (setq ass (assoc key list))
2005 (setq list (memq ass list))
2011 (defun reftex-replace-label-list-segment (old insert &optional entirely)
2012 ;; Replace the segment in OLD which corresponds to INSERT.
2013 ;; Works with side effects, directly changes old.
2014 ;; If entirely is t, just return INSERT.
2015 ;; This function also makes sure the old toc markers do not point anywhere.
2019 (reftex-silence-toc-markers old (length old))
2022 (file (nth 1 (car insert)))
2023 (eof-list (member (list 'eof file) old))
2024 (bof-list (member (list 'bof file) old))
2026 (if (not (and bof-list eof-list))
2027 (error "Cannot splice")
2029 (reftex-silence-toc-markers bof-list (- (length bof-list)
2031 (setq n (- (length old) (length bof-list)))
2032 (setcdr (nthcdr n new) (cdr insert))
2033 (setcdr (nthcdr (1- (length new)) new) (cdr eof-list)))
2036 (defun reftex-silence-toc-markers (list n)
2037 ;; Set all markers in list to nil
2038 (while (and list (> (decf n) -1))
2039 (and (eq (car (car list)) 'toc)
2040 (markerp (nth 4 (car list)))
2041 (set-marker (nth 4 (car list)) nil))
2044 (defun reftex-access-parse-file (action)
2045 (let* ((list (symbol-value reftex-docstruct-symbol))
2046 (master (reftex-TeX-master-file))
2047 (enable-local-variables nil)
2048 (file (if (string-match "\\.[a-zA-Z]+\\'" master)
2049 (concat (substring master 0 (match-beginning 0)) ".rel")
2050 (concat master ".rel"))))
2052 ((eq action 'readable)
2053 (file-readable-p file))
2054 ((eq action 'restore)
2055 (if (eq reftex-docstruct-symbol nil)
2056 ;; Symbols are not yet tied: Tie them.
2057 (reftex-tie-multifile-symbols))
2058 (if (file-exists-p file)
2059 ;; load the file and return t for success
2060 (progn (load-file file) t)
2061 ;; throw an exception
2062 (error "No restore file %s" file)))
2064 (if (file-exists-p file)
2065 ;; load the file and return t for success
2066 (progn (load-file file) t)
2067 ;; return nil for failure, but no exception
2071 (if (file-writable-p file)
2073 (message "Writing parse file %s" (abbreviate-file-name file))
2076 (insert (format ";; RefTeX parse info file\n"))
2077 (insert (format ";; File: %s\n" master))
2078 (insert (format ";; Date: %s\n"
2079 (format-time-string "%D %T"
2081 (insert (format ";; User: %s (%s)\n\n"
2082 (user-login-name) (user-full-name)))
2083 (insert "(set reftex-docstruct-symbol '(\n\n")
2084 (let ((standard-output (current-buffer)))
2088 (cond ((eq (car x) 'toc)
2089 ;; A toc entry. Do not save the marker.
2090 ;; Save the markers position at position 8
2091 (print (list 'toc "toc" (nth 2 x) (nth 3 x)
2092 nil (nth 5 x) (nth 6 x) (nth 7 x)
2093 (or (and (markerp (nth 4 x))
2094 (marker-position (nth 4 x)))
2100 (kill-buffer (current-buffer)))
2101 (error "Cannot write to file %s" file)))
2104 ;; Creating labels --------------
2106 (defun reftex-label (&optional environment no-insert)
2107 "Insert a unique label. Return the label.
2108 If ENVIRONMENT is given, don't bother to find out yourself.
2109 If NO-INSERT is non-nil, do not insert label into buffer.
2110 With prefix arg, force to rescan document first.
2111 When you are prompted to enter or confirm a label, and you reply with
2112 just the prefix or an empty string, no label at all will be inserted.
2113 A new label is also recorded into the label list.
2114 This function is controlled by the settings of reftex-insert-label-flags."
2118 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4).
2119 (reftex-access-scan-info current-prefix-arg)
2121 ;; Find out what kind of environment this is and abort if necessary.
2122 (if (or (not environment)
2123 (not (assoc environment reftex-env-or-mac-alist)))
2124 (setq environment (reftex-label-location)))
2126 (error "Can't figure out what kind of label should be inserted"))
2130 (let* ((entry (assoc environment reftex-env-or-mac-alist))
2131 (typekey (nth 1 entry))
2132 (format (nth 3 entry))
2133 label prefix valid default force-prompt rescan-is-useful)
2134 (when (and (eq (string-to-char environment) ?\\)
2136 (memq (preceding-char) '(?\[ ?\{)))
2139 (setq prefix (or (cdr (assoc typekey reftex-typekey-to-prefix-alist))
2140 (concat typekey "-")))
2141 ;; Replace any escapes in the prefix
2142 (setq prefix (reftex-replace-prefix-escapes prefix))
2144 ;; Make a default label.
2147 ((reftex-typekey-check typekey (nth 0 reftex-insert-label-flags))
2148 ;; Derive a label from context.
2149 (setq reftex-active-toc (reftex-last-assoc-before-elt
2150 'toc (car (reftex-where-am-I))
2151 (symbol-value reftex-docstruct-symbol)))
2152 (setq default (reftex-no-props
2153 (nth 2 (reftex-label-info " " nil nil t))))
2154 ;; Catch the cases where the is actually no context available.
2155 (if (or (string-match "NO MATCH FOR CONTEXT REGEXP" default)
2156 (string-match "ILLEGAL VALUE OF PARSE" default)
2157 (string-match "SECTION HEADING NOT FOUND" default)
2158 (string-match "HOOK ERROR" default)
2159 (string-match "^[ \t]*$" default))
2160 (setq default prefix
2161 force-prompt t) ; need to prompt
2162 (setq default (concat prefix (reftex-string-to-label default)))
2165 (setq default (reftex-uniquify-label default nil "-"))))
2167 ((reftex-typekey-check typekey (nth 1 reftex-insert-label-flags))
2168 ;; Minimal default: the user will be prompted.
2169 (setq default prefix))
2172 ;; Make an automatic label.
2173 (setq default (reftex-uniquify-label prefix t))))
2175 ;; Should we ask the user?
2176 (if (or (reftex-typekey-check typekey
2177 (nth 1 reftex-insert-label-flags)) ; prompt
2181 ;; iterate until we get a legal label
2183 (setq label (read-string
2184 (if (string= format "%s") "Naked Label: " "Label: ")
2187 ;; Lets make sure that this is a legal label
2190 ((string-match (concat "\\`\\(" (regexp-quote prefix)
2193 ;; No label at all, please
2194 (message "No label inserted.")
2197 ;; Test if label contains strange characters
2198 ((string-match reftex-label-illegal-re label)
2199 (message "Label \"%s\" contains illegal characters" label)
2203 ;; Look it up in the label list
2204 ((setq entry (assoc label
2205 (symbol-value reftex-docstruct-symbol)))
2208 (format "Label '%s' exists. Use anyway? " label))
2214 (setq label default))
2216 ;; Insert the label into the label list
2217 (let* ((here-I-am-info (reftex-where-am-I))
2218 (here-I-am (car here-I-am-info))
2219 (note (if (cdr here-I-am-info)
2221 "POSITION UNCERTAIN. RESCAN TO FIX."))
2222 (file (buffer-file-name))
2224 (tail (memq here-I-am (symbol-value reftex-docstruct-symbol))))
2226 (or (cdr here-I-am-info) (setq rescan-is-useful t))
2229 (setcdr tail (cons (list label typekey text file note)
2232 ;; Insert the label into the buffer
2235 (if reftex-format-label-function
2236 (funcall reftex-format-label-function label format)
2237 (format format label))))
2239 ;; Delete the corresponding selection buffers to force update on next use.
2240 (when reftex-auto-update-selection-buffers
2241 (reftex-erase-buffer (reftex-make-selection-buffer-name typekey))
2242 (reftex-erase-buffer (reftex-make-selection-buffer-name " ")))
2244 (when (and rescan-is-useful reftex-allow-automatic-rescan)
2247 ;; return value of the function is the label
2250 (defun reftex-string-to-label (string)
2251 ;; Convert a string (a sentence) to a label.
2253 ;; Uses reftex-derive-label-parameters and reftex-abbrev-parameters
2256 (let* ((words0 (split-string string "[- \t\n\r]+"))
2257 (ignore-words (nth 5 reftex-derive-label-parameters))
2260 ;; remove words from the ignore list or with funny characters
2261 (while (setq word (pop words0))
2263 ((member (downcase word) ignore-words))
2264 ((string-match reftex-label-illegal-re word)
2265 (when (nth 2 reftex-derive-label-parameters)
2266 (while (string-match reftex-label-illegal-re word)
2267 (setq word (replace-match "" nil nil word)))
2270 (push word words))))
2271 (setq words (nreverse words))
2273 ;; restrict number of words
2274 (if (> (length words) (nth 0 reftex-derive-label-parameters))
2275 (setcdr (nthcdr (1- (nth 0 reftex-derive-label-parameters)) words) nil))
2277 ;; First, try to use all words
2278 (setq string (mapconcat 'identity words
2279 (nth 4 reftex-derive-label-parameters)))
2281 ;; Abbreviate words if enforced by user settings or string length
2282 (if (or (eq t (nth 3 reftex-derive-label-parameters))
2283 (and (nth 3 reftex-derive-label-parameters)
2284 (> (length string) (nth 1 reftex-derive-label-parameters))))
2288 (lambda (w) (if (string-match reftex-abbrev-regexp w)
2292 string (mapconcat 'identity words
2293 (nth 4 reftex-derive-label-parameters))))
2295 ;; Shorten if still to long
2297 (if (> (length string) (nth 1 reftex-derive-label-parameters))
2298 (substring string 0 (nth 1 reftex-derive-label-parameters))
2301 ;; Delete the final punctuation, if any
2302 (if (string-match "[^a-zA-Z0-9]+\\'" string)
2303 (setq string (replace-match "" nil nil string)))
2306 (defun reftex-replace-prefix-escapes (prefix)
2307 ;; Replace %escapes in a label prefix
2309 (let (letter (num 0) replace)
2310 (while (string-match "\\%\\([a-zA-Z]\\)" prefix num)
2311 (setq letter (match-string 1 prefix))
2315 (file-name-sans-extension
2316 (file-name-nondirectory (buffer-file-name))))
2318 (let ((masterdir (file-name-directory (reftex-TeX-master-file)))
2319 (file (file-name-sans-extension (buffer-file-name))))
2320 (if (string-match (concat "\\`" (regexp-quote masterdir))
2322 (substring file (length masterdir))
2325 (or (user-login-name) ""))
2327 (setq num (1- (+ (match-beginning 1) (length replace)))
2328 prefix (replace-match replace nil nil prefix)))
2331 (defun reftex-label-location (&optional bound)
2332 ;; Return the environment or macro which determines the label type at point.
2333 ;; If optional BOUND is an integer, limit backward searches to that point.
2335 (let* ((loc1 (reftex-what-macro reftex-label-mac-list bound))
2336 (loc2 (reftex-what-environment reftex-label-env-list bound))
2337 (p1 (or (cdr loc1) 0))
2338 (p2 (or (cdr loc2) 0)))
2340 (setq reftex-location-start (max p1 p2))
2343 (setq reftex-default-context-position (+ p1 (length (car loc1))))
2344 (or (car loc1) "section"))
2345 (setq reftex-default-context-position (+ p2 8 (length (car loc2))))
2346 (or (car loc2) "section"))))
2348 (defun reftex-uniquify-label (label &optional force separator)
2349 ;; Make label unique by appending a number.
2350 ;; Optional FORCE means, force appending a number, even if label is unique.
2351 ;; Optional SEPARATOR is a string to stick between label and number.
2353 ;; Ensure access to scanning info
2354 (reftex-access-scan-info)
2358 (not (assoc label (symbol-value reftex-docstruct-symbol))))
2361 (let* ((label-numbers (assq 'label-numbers
2362 (symbol-value reftex-docstruct-symbol)))
2363 (label-numbers-alist (cdr label-numbers))
2364 (cell (or (assoc label label-numbers-alist)
2365 (car (setcdr label-numbers
2366 (cons (cons label 0)
2367 label-numbers-alist)))))
2368 (num (1+ (cdr cell)))
2369 (sep (or separator "")))
2370 (while (assoc (concat label sep (int-to-string num))
2371 (symbol-value reftex-docstruct-symbol))
2374 (concat label sep (int-to-string num))))))
2376 ;; Help string for the reference label menu
2377 (defconst reftex-select-label-prompt
2378 "Select: [n]ext [p]revious [r]escan [ ]context e[x]tern [q]uit RET [?]HELP+more")
2380 (defconst reftex-select-label-help
2381 " n / p Go to next/previous label (Cursor motion works as well)
2382 C-c C-n/p Go to next/previous section heading.
2383 b / l Jump back to previous selection / Reuse last referenced label
2384 C-s / C-r Search forward/backward. Use repeated C-s/C-r as in isearch.
2385 g / s Update menu / Switch label type
2386 r / R Reparse document / Reparse entire document
2387 x Switch to label menu of external document (with LaTeX package `xr')
2388 t i c # % Toggle: [i]ncl. file borders, [t]able of contents, [c]ontext
2389 [#] label counters, [%] labels in comments
2390 SPC / f Show full context in other window / Toggle follow mode
2391 v / . Toggle \\ref <-> \\vref / Show insertion point in other window
2392 TAB Enter a label with completion
2393 q / RET Quit without referencing / Accept current label (also on mouse-2)")
2395 (defvar reftex-select-label-map nil
2396 "Keymap used for *RefTeX Select* buffer, when selecting a label.
2397 This keymap can be used to configure the label selection process which is
2398 started with the command \\[reftex-reference].")
2400 (defun reftex-select-label-mode ()
2401 "Major mode for selecting a label in a LaTeX document.
2402 This buffer was created with RefTeX.
2403 It only has a meaningful keymap when you are in the middle of a
2405 To select a label, move the cursor to it and press RET.
2406 Press `?' for a summary of important key bindings.
2408 During a selection process, these are the local bindings.
2410 \\{reftex-select-label-map}"
2413 (kill-all-local-variables)
2414 (make-local-hook 'pre-command-hook)
2415 (make-local-hook 'post-command-hook)
2416 (setq major-mode 'reftex-select-label-mode
2417 mode-name "RefTeX Select Label")
2418 ;; We do not set a local map - reftex-select-item does this.
2419 (run-hooks 'reftex-select-label-mode-hook))
2421 (defun reftex-reference (&optional type no-insert cut)
2422 "Make a LaTeX reference. Look only for labels of a certain TYPE.
2423 With prefix arg, force to rescan buffer for labels. This should only be
2424 necessary if you have recently entered labels yourself without using
2425 reftex-label. Rescanning of the buffer can also be requested from the
2426 label selection menu.
2427 The function returns the selected label or nil.
2428 If NO-INSERT is non-nil, do not insert \\ref command, just return label.
2429 When called with 2 C-u prefix args, disable magic word recognition."
2433 ;; check for active recursive edits
2434 (reftex-check-recursive-edit)
2436 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
2437 (reftex-access-scan-info current-prefix-arg)
2440 ;; guess type from context
2441 (if (and reftex-guess-label-type
2442 (setq type (reftex-guess-label-type)))
2443 (setq cut (cdr type)
2445 (setq type (reftex-query-label-type))))
2447 (let* ((varioref (if (reftex-typekey-check
2448 type reftex-vref-is-default)
2453 ;; Have the user select a label
2454 (set-marker reftex-select-return-marker (point))
2455 (setq pair (save-excursion
2456 (reftex-offer-label-menu type)))
2457 (set-marker reftex-select-return-marker nil)
2458 (setq label (car pair)
2460 form (or (cdr (assoc type reftex-typekey-to-format-alist))
2466 (if cut (backward-delete-char cut))
2468 ;; remove ~ if we do already have a space
2469 (when (and (= ?~ (string-to-char form))
2470 (= ?\ (preceding-char)))
2471 (setq form (substring form 1)))
2472 ;; do we need to switch from \ref to \vref?
2473 (when (string= varioref "\\vref")
2474 (while (string-match "\\\\ref{" form)
2475 (setq form (replace-match "\\vref{" t t form))))
2476 ;; ok, insert the reference
2478 (if reftex-format-ref-function
2479 (funcall reftex-format-ref-function label form)
2480 (format form label label)))
2486 (defun reftex-guess-label-type ()
2487 (let ((words reftex-words-to-typekey-alist)
2488 (case-fold-search t)
2489 (bound (max (point-min) (- (point) 35)))
2492 (while (and (setq cell (pop words))
2494 (re-search-backward (car cell) bound t))))))
2496 (cons (cdr cell) (- (match-end 0) (match-end 1)))
2499 (defun reftex-offer-label-menu (typekey)
2500 ;; Offer a menu with the appropriate labels. Return (label . typekey).
2501 (let* ((buf (current-buffer))
2502 (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
2503 (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
2505 (here-I-am (car (reftex-where-am-I)))
2506 (here-I-am1 here-I-am)
2507 (toc (reftex-typekey-check typekey reftex-label-menu-flags 0))
2508 (files (reftex-typekey-check typekey reftex-label-menu-flags 7))
2509 (context (not (reftex-typekey-check
2510 typekey reftex-label-menu-flags 3)))
2511 (counter (reftex-typekey-check
2512 typekey reftex-label-menu-flags 2))
2513 (follow (reftex-typekey-check
2514 typekey reftex-label-menu-flags 4))
2515 (commented (nth 5 reftex-label-menu-flags))
2518 offset rtn key data last-data entry)
2520 (setq entry (cons nil nil))
2522 ;; The following unwind-protect kills temporary buffers after use
2526 (save-window-excursion
2527 (delete-other-windows)
2528 (setq reftex-call-back-to-this-buffer buf)
2529 (let ((default-major-mode 'reftex-select-label-mode))
2530 (if reftex-use-multiple-selection-buffers
2531 (switch-to-buffer-other-window
2534 (reftex-make-selection-buffer-name typekey)))
2535 (switch-to-buffer-other-window "*RefTeX Select*")
2536 (reftex-erase-buffer)))
2537 (unless (eq major-mode 'reftex-select-label-mode)
2538 (reftex-select-label-mode))
2539 (add-to-list 'selection-buffers (current-buffer))
2540 (setq truncate-lines t)
2541 (setq mode-line-format
2542 (list "---- " 'mode-line-buffer-identification
2544 " " (abbreviate-file-name
2545 (buffer-file-name buf))
2548 ((= 0 (buffer-size))
2549 (let ((buffer-read-only nil))
2550 (setq offset (reftex-make-and-insert-label-list
2551 typekey buf toc files context counter commented
2552 (or here-I-am offset) prefix))))
2554 (setq offset (reftex-get-offset buf here-I-am typekey)))
2555 (t (setq offset t)))
2556 (setq buffer-read-only t)
2557 (setq offset (or offset t))
2559 (setq here-I-am nil) ; turn off determination of offset
2562 reftex-select-label-prompt
2563 reftex-select-label-help
2564 reftex-select-label-map
2566 'reftex-select-label-callback follow))
2569 last-data (nth 2 rtn)
2571 (unless key (throw 'exit nil))
2575 (reftex-erase-buffer))
2579 (reftex-erase-buffer)
2580 (reftex-parse-document buf last-data key))
2582 ;; toggle context mode
2583 (reftex-erase-buffer)
2584 (setq context (not context)))
2587 (setq here-I-am here-I-am1)
2588 (setq typekey (reftex-query-label-type)))
2590 ;; toggle table of contents display
2591 (reftex-erase-buffer)
2592 (setq toc (not toc)))
2594 ;; toggle display of included file borders
2595 (reftex-erase-buffer)
2596 (setq files (not files)))
2598 ;; toggle counter display
2599 (reftex-erase-buffer)
2600 (setq counter (not counter)))
2602 ;; toggle display of commented labels
2603 (reftex-erase-buffer)
2604 (setq commented (not commented)))
2606 ;; reuse the last referenced label again
2607 (setq entry reftex-last-used-reference)
2610 ;; select an external document
2611 (setq xr-index (reftex-select-external-document
2613 (setq buf (or (reftex-get-file-buffer-force
2614 (cdr (nth xr-index xr-alist)))
2615 (error "Cannot switch document"))
2616 prefix (or (car (nth xr-index xr-alist)) ""))
2618 (reftex-access-scan-info))
2621 (or (assoc key (symbol-value reftex-docstruct-symbol))
2622 (list key typekey)))
2629 (setq reftex-last-used-reference entry))
2631 (throw 'exit t))))))
2632 (mapcar (function (lambda (buf)
2633 (and (buffer-live-p buf)
2634 (bury-buffer buf))))
2636 (reftex-kill-buffer "*RefTeX Context Copy*")
2637 (reftex-kill-temporary-buffers))
2638 (cons (if (nth 0 entry) (concat prefix (nth 0 entry)) nil)
2641 (defun reftex-select-external-document (xr-alist xr-index)
2642 ;; Return index of an external document.
2643 (let* ((len (length xr-alist)) (highest (1- (+ ?0 len)))
2644 (prompt (format "[%c-%c] Select SPC/DEL: Scroll TAB: Read prefix with completion" ?0 highest))
2648 (message "No external documents available")
2654 (save-window-excursion
2655 (let* ((length (apply 'max (mapcar
2656 (lambda(x) (length (car x))) xr-alist)))
2657 (fmt (format " [%%c] %%-%ds %%s\n" length))
2659 (with-output-to-temp-buffer "*RefTeX Select*"
2660 (princ "SELECT EXTERNAL DOCUMENT\n------------------------\n")
2665 (format fmt (incf n) (or (car x) "")
2666 (abbreviate-file-name (cdr x)))))
2668 (reftex-enlarge-to-fit "*RefTeX Select*")
2669 (select-window (get-buffer-window "*RefTeX Select*"))
2670 (setq truncate-lines t)
2674 (setq key (read-char-exclusive))
2676 ((= key ?\C-?) (condition-case nil (scroll-down) (error nil)))
2677 ((= key ?\ ) (condition-case nil (scroll-up) (error nil)))
2678 ((and (>= key ?0) (<= key highest))
2679 (throw 'exit (- key ?0)))
2681 (setq prefix (completing-read "Prefix: " xr-alist nil t))
2682 (throw 'exit (- len (length (memq (assoc prefix xr-alist)
2684 (t (error "Illegal document selection [%c]" key)))))))))))
2686 (defun reftex-make-selection-buffer-name (type &optional index)
2687 ;; Make unique name for a selection buffer.
2688 (format "*RefTeX[%s][%d]*"
2689 type (or index (get reftex-docstruct-symbol ':master-index) 0)))
2691 (defun reftex-get-offset (buf here-am-I typekey)
2692 ;; Find the correct offset data, like make-and-insert would, but faster.
2695 (reftex-access-scan-info)
2696 (let* ((rest (memq here-am-I (symbol-value reftex-docstruct-symbol)))
2698 (while (and (setq entry (pop rest))
2699 (not (and (stringp (car entry))
2700 (equal typekey (nth 1 entry))))))
2703 (defun reftex-make-and-insert-label-list
2704 (typekey0 buf toc files context counter show-commented here-I-am xr-prefix)
2705 ;; Insert a menu of all labels in buffer BUF into current buffer.
2706 ;; Return the data property of the entry corresponding to HERE-I-AM.
2707 (let* ((font (reftex-use-fonts))
2713 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
2716 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
2718 (if (memq reftex-highlight-selection '(mouse both))
2719 reftex-mouse-selected-face
2721 all cell text label typekey note comment master-dir-re
2722 offset from to docstruct-symbol)
2724 (message "Creating Selection Buffer...")
2726 ;; Pop to buffer buf to get the correct buffer-local variables
2730 ;; Ensure access to scanning info
2731 (reftex-access-scan-info)
2733 (setq docstruct-symbol reftex-docstruct-symbol
2734 all (symbol-value reftex-docstruct-symbol)
2735 reftex-active-toc nil
2737 (concat "\\`" (regexp-quote
2738 (file-name-directory (reftex-TeX-master-file))))))
2740 (set (make-local-variable 'reftex-docstruct-symbol) docstruct-symbol)
2741 (set (make-local-variable 'reftex-prefix)
2742 (cdr (assoc typekey0 reftex-typekey-to-prefix-alist)))
2743 (if (equal reftex-prefix " ") (setq reftex-prefix nil))
2745 ;; Walk the docstruct and insert the appropriate stuff
2746 (while (setq cell (pop all))
2751 (if (eq cell here-I-am) (setq offset 'attention))
2755 ((memq (car cell) '(bib thebib label-numbers appendix
2756 master-dir is-multi xr xr-doc)))
2757 ;; These are currently ignored
2759 ((memq (car cell) '(bof eof file-error))
2760 ;; Beginning or end of a file
2763 " File " (if (string-match master-dir-re (nth 1 cell))
2764 (substring (nth 1 cell) (match-end 0))
2766 (cond ((eq (car cell) 'bof) " starts here\n")
2767 ((eq (car cell) 'eof) " ends here\n")
2768 ((eq (car cell) 'file-error) " was not found\n")))
2770 (put-text-property from (point)
2771 'face reftex-file-boundary-face))))
2773 ((eq (car cell) 'toc)
2774 ;; a table of contents entry
2776 (setq reftex-active-toc cell)
2777 (insert (concat toc-indent (nth 2 cell) "\n"))))
2779 ((stringp (car cell))
2781 (when (null (nth 2 cell))
2782 ;; No context yet. Quick update.
2783 (setcdr cell (cdr (reftex-label-info-update cell))))
2785 (setq label (car cell)
2786 typekey (nth 1 cell)
2789 comment (get-text-property 0 'in-comment text))
2791 (when (and (or (string= typekey typekey0) (string= typekey0 " "))
2792 (or show-commented (null comment)))
2794 ;; Yes we want this one
2796 (if (eq offset 'attention) (setq offset cell))
2798 (setq label (concat xr-prefix label))
2799 (when comment (setq label (concat "% " label)))
2800 (insert label-indent label)
2803 (- (point) (length label)) (point)
2805 'font-lock-comment-face
2806 reftex-label-face)))
2808 (insert (if counter (format " (%d) " cnt) "")
2809 (if comment " LABEL IS COMMENTED OUT " "")
2810 (if note (concat " " note) "")
2815 (insert context-indent text "\n")
2817 (put-text-property from to ':data cell)
2819 (put-text-property from (1- to)
2820 'mouse-face mouse-face))
2823 (when (reftex-refontify)
2824 (reftex-fontify-select-label-buffer))
2827 (defun reftex-parse-document (&optional buffer data key)
2828 "Rescan the document."
2830 (save-window-excursion
2833 (if (not (bufferp buffer))
2834 (error "No such buffer %s" (buffer-name buffer))
2835 (set-buffer buffer)))
2836 (let ((arg (if (eq key ?R) '(16) '(4)))
2837 (file (nth 3 data)))
2838 (reftex-access-scan-info arg file)))))
2840 (defun reftex-query-label-type ()
2841 ;; Ask for label type
2842 (message reftex-type-query-prompt)
2843 (let ((key (read-char)))
2845 (save-window-excursion
2846 (with-output-to-temp-buffer "*RefTeX Help*"
2847 (princ reftex-type-query-help))
2848 (reftex-enlarge-to-fit "*RefTeX Help*")
2849 (setq key (read-char))
2850 (kill-buffer "*RefTeX Help*")))
2851 (unless (member (char-to-string key) reftex-typekey-list)
2852 (error "No such label type: %s" (char-to-string key)))
2853 (char-to-string key)))
2855 ;; Variable holding the vector with section numbers
2856 (defvar reftex-section-numbers [0 0 0 0 0 0 0 0])
2858 (defun reftex-section-info (file)
2859 ;; Return a section entry for the current match.
2860 ;; Carefull: This function expects the match-data to be still in place!
2861 (let* ((marker (set-marker (make-marker) (1- (match-beginning 3))))
2862 (macro (reftex-match-string 3))
2863 (star (= ?* (char-after (match-end 3))))
2864 (level (cdr (assoc macro reftex-section-levels)))
2865 (section-number (reftex-section-number level star))
2866 (text1 (save-match-data (save-excursion (reftex-context-substring))))
2867 (literal (buffer-substring-no-properties
2868 (1- (match-beginning 3))
2869 (min (point-max) (+ (match-end 0) (length text1) 1))))
2870 ;; Literal can be too short since text1 too short. No big problem.
2871 (text (reftex-nicify-text text1)))
2873 ;; Add section number and indentation
2876 (make-string (* reftex-level-indent level) ?\ )
2877 (if (nth 1 reftex-label-menu-flags) ; section number flag
2878 (concat section-number " "))
2881 (if (reftex-use-fonts)
2882 (put-text-property 0 (length text)
2883 'face reftex-section-heading-face text))
2884 (list 'toc "toc" text file marker level section-number
2885 literal (marker-position marker))))
2887 (defun reftex-label-info-update (cell)
2888 ;; Update information about just one label in a different file.
2889 ;; CELL contains the old info list
2890 (let* ((label (nth 0 cell))
2891 (typekey (nth 1 cell))
2892 ;; (text (nth 2 cell))
2895 (buf (reftex-get-file-buffer-force
2896 file (not (eq t reftex-keep-temporary-buffers)))))
2898 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")
2905 (if (or (re-search-forward
2906 (format reftex-find-label-regexp-format
2907 (regexp-quote label)) nil t)
2909 (format reftex-find-label-regexp-format2
2910 (regexp-quote label)) nil t))
2914 (append (reftex-label-info label file) (list note)))
2915 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")))))))
2917 (defun reftex-label-info (label &optional file bound derive env-or-mac)
2918 ;; Return info list on LABEL at point.
2919 (let* ((env-or-mac (or env-or-mac (reftex-label-location bound)))
2920 (typekey (nth 1 (assoc env-or-mac reftex-env-or-mac-alist)))
2921 (file (or file (buffer-file-name)))
2922 (parse (if (reftex-typekey-check
2923 typekey reftex-use-text-after-label-as-context)
2925 (nth 2 (assoc env-or-mac reftex-env-or-mac-alist))))
2926 (text (reftex-short-context env-or-mac parse reftex-location-start
2928 (if (reftex-in-comment)
2929 (put-text-property 0 1 'in-comment t text))
2930 (list label typekey text file)))
2932 (defun reftex-in-comment ()
2934 (skip-chars-backward "^%\n\r")
2935 (eq (preceding-char) ?%)))
2937 (defun reftex-short-context (env parse &optional bound derive)
2938 ;; Get about one line of useful context for the label definition at point.
2941 (setq parse (if derive (cdr parse) (car parse))))
2949 (reftex-context-substring)))
2952 (if (string= env "section")
2953 ;; special treatment for section labels
2955 (if (and (re-search-backward reftex-section-or-include-regexp
2959 (goto-char (match-end 0))
2960 (reftex-context-substring))
2961 (if reftex-active-toc
2963 (string-match "{\\([^}]*\\)" (nth 7 reftex-active-toc))
2964 (match-string 1 (nth 7 reftex-active-toc)))
2965 "SECTION HEADING NOT FOUND")))
2967 (goto-char reftex-default-context-position)
2968 (unless (eq (string-to-char env) ?\\)
2969 (reftex-move-over-touching-args))
2970 (reftex-context-substring))))
2974 (if (re-search-backward parse bound t)
2976 (goto-char (match-end 0))
2977 (reftex-context-substring))
2978 "NO MATCH FOR CONTEXT REGEXP")))
2982 (goto-char reftex-default-context-position)
2985 (nth 6 (assoc env reftex-env-or-mac-alist))))
2989 ;; A hook function. Call it.
2991 (condition-case error-var
2993 (error (format "HOOK ERROR: %s" (cdr error-var))))))
2995 "ILLEGAL VALUE OF PARSE"))))
2997 (defun reftex-where-am-I ()
2998 ;; Return the docstruct entry above point. Actually returns a cons
2999 ;; cell in which the cdr is a flag indicating if the information is
3000 ;; exact (t) or approximate (nil).
3002 (let ((docstruct (symbol-value reftex-docstruct-symbol))
3008 (setq found (re-search-backward reftex-everything-regexp nil t))
3014 (car (member (list 'bof (buffer-file-name)) docstruct))
3016 (assq 'bof docstruct) ;; for safety reasons
3020 (assoc (reftex-match-string 1)
3021 (symbol-value reftex-docstruct-symbol)))
3024 (goto-char (1- (match-beginning 3)))
3025 (let* ((list (member (list 'bof (buffer-file-name))
3027 (endelt (car (member (list 'eof (buffer-file-name))
3030 (while (and list (not (eq endelt (car list))))
3031 (if (and (eq (car (car list)) 'toc)
3032 (string= (buffer-file-name)
3033 (nth 3 (car list))))
3036 (or (and (markerp (nth 4 (car list)))
3037 (marker-position (nth 4 (car list))))
3038 (nth 8 (car list))))
3039 ;; Fits with marker position or recorded position
3040 (setq rtn1 (car list) list nil))
3041 ((looking-at (reftex-make-regexp-allow-for-ctrl-m
3042 (nth 7 (car list))))
3044 (setq rtn1 (car list) list nil cnt 2))))
3048 ;; Input or include...
3050 (member (list 'eof (reftex-find-tex-file
3051 (reftex-match-string 7)
3052 (cdr (assq 'master-dir docstruct))))
3055 (assq 'appendix (symbol-value reftex-docstruct-symbol)))
3058 (goto-char (match-end 10))
3059 (assoc (reftex-no-props
3060 (reftex-nth-arg-wrapper
3061 (reftex-match-string 10)))
3062 (symbol-value reftex-docstruct-symbol))))
3064 (error "This should not happen (reftex-where-am-I)"))))))
3065 (cons rtn (eq cnt 1))))
3067 (defun reftex-parse-args (macro)
3068 ;; Return a list of macro name, nargs, arg-nr which is label and a list of
3069 ;; optional argument indices.
3070 (if (string-match "[[{]\\*?[]}]" macro)
3072 (let ((must-match (substring macro 0 (match-beginning 0)))
3073 (args (substring macro (match-beginning 0)))
3074 opt-list nlabel (cnt 0))
3075 (while (string-match "\\`[[{]\\(\\*\\)?[]}]" args)
3077 (when (eq ?\[ (string-to-char args))
3078 (push cnt opt-list))
3079 (when (and (match-end 1)
3082 (setq args (substring args (match-end 0))))
3083 (list must-match cnt nlabel opt-list)))
3086 (defsubst reftex-move-to-next-arg (&optional ignore)
3087 ;; Assuming that we are at the end of a macro name or a macro argument,
3088 ;; move forward to the opening parenthesis of the next argument.
3089 ;; This function understands the splitting of macros over several lines
3092 ;; Just to be quick:
3093 ((memq (following-char) '(?\[ ?\{)))
3095 ((looking-at "[ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*[[{]")
3096 (goto-char (1- (match-end 0)))
3100 (defsubst reftex-move-to-previous-arg (&optional bound)
3101 ;; Assuming that we are in front of a macro argument,
3102 ;; move backward to the closing parenthesis of the previous argument.
3103 ;; This function understands the splitting of macros over several lines
3106 ;; Just to be quick:
3107 ((memq (preceding-char) '(?\] ?\})))
3109 ((re-search-backward
3110 "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\=" bound t)
3111 (goto-char (1+ (match-beginning 0)))
3115 (defun reftex-nth-arg-wrapper (key)
3116 (let ((entry (assoc key reftex-env-or-mac-alist)))
3117 (reftex-nth-arg (nth 5 entry) (nth 6 entry))))
3119 (defun reftex-nth-arg (n &optional opt-args)
3120 ;; Return the nth following {} or [] parentheses content.
3121 ;; OPT-ARGS is a list of argument numbers which are optional.
3123 ;; If we are sitting at a macro start, skip to end of macro name.
3124 (and (eq (following-char) ?\\) (skip-chars-forward "a-zA-Z*\\\\"))
3127 ;; Special case: Skip all touching arguments
3129 (reftex-move-over-touching-args)
3130 (reftex-context-substring))
3132 ;; Do the real thing.
3135 (when (reftex-move-to-next-arg)
3138 (while (and (member cnt opt-args)
3139 (eq (following-char) ?\{))
3142 (unless (and (condition-case nil
3143 (or (forward-list 1) t)
3145 (reftex-move-to-next-arg)
3149 (while (and (memq cnt opt-args)
3150 (eq (following-char) ?\{))
3153 (> (skip-chars-forward "{\\[") 0))
3154 (reftex-context-substring)
3157 (defun reftex-move-over-touching-args ()
3159 (while (memq (following-char) '(?\[ ?\{))
3163 (defun reftex-context-substring ()
3164 ;; Return up to 100 chars from point
3165 ;; When point is just after a { or [, limit string to matching parenthesis
3167 ((or (= (preceding-char) ?\{)
3168 (= (preceding-char) ?\[))
3169 ;; Inside a list - get only the list.
3170 (buffer-substring-no-properties
3172 (min (reftex-fp 150)
3178 (error (point-max))))))
3180 ;; no list - just grab 100 characters
3181 (buffer-substring-no-properties (point) (min (reftex-fp 150) (point-max))))))
3183 (defun reftex-init-section-numbers (&optional toc-entry appendix)
3184 ;; Initialize the section numbers with zeros or with what is found
3185 ;; in the toc entry.
3186 (let* ((level (or (nth 5 toc-entry) -1))
3187 (numbers (nreverse (split-string (or (nth 6 toc-entry) "") "\\.")))
3188 (depth (1- (length reftex-section-numbers)))
3189 (i depth) number-string)
3192 (aset reftex-section-numbers i 0)
3193 (setq number-string (or (car numbers) "0"))
3194 (if (string-match "\\`[A-Z]\\'" number-string)
3195 (aset reftex-section-numbers i
3196 (- (string-to-char number-string) ?A -1))
3197 (aset reftex-section-numbers i (string-to-int number-string)))
3200 (put 'reftex-section-numbers 'appendix appendix))
3202 (defun reftex-section-number (&optional level star)
3203 ;; Return a string with the current section number.
3204 ;; When LEVEL is non-nil, increase section numbers on that level.
3205 (let* ((depth (1- (length reftex-section-numbers))) idx n (string "")
3206 (appendix (get 'reftex-section-numbers 'appendix)))
3208 (when (and (> level -1) (not star))
3209 (aset reftex-section-numbers
3210 level (1+ (aref reftex-section-numbers level))))
3211 (setq idx (1+ level))
3212 (while (<= idx depth)
3213 (aset reftex-section-numbers idx 0)
3216 (while (<= idx depth)
3217 (setq n (aref reftex-section-numbers idx))
3218 (setq string (concat string (if (not (string= string "")) "." "")
3222 (if (string-match "\\`\\([@0]\\.\\)+" string)
3223 (setq string (replace-match "" nil nil string)))
3224 (if (string-match "\\(\\.0\\)+\\'" string)
3225 (setq string (replace-match "" nil nil string)))
3227 (string-match "\\`[0-9]+" string))
3228 (setq string (concat (char-to-string (1- (+ ?A (string-to-int (match-string 0 string))))) (substring string (match-end 0))))))
3231 (concat (make-string (1- (length string)) ?\ ) "*")
3234 (defun reftex-select-label-callback (data forward no-revisit)
3235 ;; Callback function called from the label selection in order to
3236 ;; show context in another window
3237 (let* ((this-window (selected-window))
3238 label file buffer re found)
3239 ;; pop to original buffer in order to get correct variables
3241 (setq label (nth 0 data)
3244 ;; goto the file in another window
3247 (get-file-buffer file)
3248 (reftex-get-file-buffer-force
3249 file (not reftex-keep-temporary-buffers))))
3251 ;; good - the file is available
3252 (switch-to-buffer-other-window buffer)
3253 ;; we have got a problem here. The file does not exist.
3254 ;; Let' get out of here..
3258 ;; search for that label
3259 (setq re (format reftex-find-label-regexp-format (regexp-quote label)))
3262 (re-search-forward re nil t)
3263 (re-search-backward re nil t)))
3265 (goto-char (point-min))
3266 (unless (re-search-forward re nil t)
3267 ;; Ooops. Must be in a macro with distributed args.
3268 (re-search-forward (format reftex-find-label-regexp-format2
3269 (regexp-quote label)) nil t)))
3271 (reftex-highlight 0 (match-beginning 3) (match-end 3))
3272 (reftex-show-entry (- (point) (match-beginning 3))
3273 (- (point) (match-end 3)))
3274 (recenter (/ (window-height) 2)))
3275 (select-window this-window))))
3277 (defun reftex-pop-to-label (label file-list &optional mark-to-kill highlight)
3278 ;; Find LABEL in any file in FILE-LIST in another window.
3279 ;; If mark-to-kill is non-nil, mark new buffer for killing.
3280 ;; If HIGHLIGHT is non-nil, highlight the label definition.
3281 (let* ((re1 (format reftex-find-label-regexp-format (regexp-quote label)))
3282 (re2 (format reftex-find-label-regexp-format2 (regexp-quote label)))
3283 (re-list (list re1 re2)) re
3284 (file-list-1 file-list)
3287 (while (setq re (pop re-list))
3288 (setq file-list file-list-1)
3289 (while (setq file (pop file-list))
3290 (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
3291 (error "No such file %s" file))
3294 (goto-char (point-min))
3295 (when (re-search-forward re nil t)
3296 (switch-to-buffer-other-window buf)
3297 (goto-char (match-beginning 0))
3298 (recenter (/ (window-height) 2))
3300 (reftex-highlight 0 (match-beginning 3) (match-end 3)))
3301 (throw 'exit (selected-window)))))
3302 (error "Label %s not found" label))))
3304 (defun reftex-find-duplicate-labels ()
3305 "Produce a list of all duplicate labels in the document."
3309 ;; Rescan the document to make sure
3310 (reftex-access-scan-info t)
3312 (let ((master (reftex-TeX-master-file))
3321 '(toc bof eof bib thebib label-numbers xr xr-doc
3322 master-dir file-error appendix is-multi))
3325 (setq x1 (reftex-all-assoc-string
3326 (car x) (symbol-value reftex-docstruct-symbol)))
3327 (if (< 1 (length x1))
3328 (append (list (car x))
3331 (abbreviate-file-name (nth 3 x))))
3334 (reftex-uniquify (symbol-value reftex-docstruct-symbol)))))
3336 (setq dlist (reftex-uniquify dlist))
3337 (if (null dlist) (error "No duplicate labels in document"))
3338 (switch-to-buffer-other-window "*Duplicate Labels*")
3339 (make-local-variable 'TeX-master)
3340 (setq TeX-master master)
3342 (insert " MULTIPLE LABELS IN CURRENT DOCUMENT:\n")
3344 " Move point to label and type `r' to run a query-replace on the label\n"
3345 " and its references. Type `q' to exit this buffer.\n\n")
3346 (insert " LABEL FILE\n")
3347 (insert " -------------------------------------------------------------\n")
3348 (use-local-map (make-sparse-keymap))
3349 (local-set-key [?q] (function
3350 (lambda () (interactive)
3351 (kill-buffer (current-buffer)) (delete-window))))
3352 (local-set-key [?r] 'reftex-change-label)
3354 (when (and (car (car dlist))
3357 (insert (mapconcat 'identity (car dlist) "\n ") "\n"))
3359 (goto-char (point-min))
3361 (kill-buffer (current-buffer))
3363 (message "Document does not contain duplicate labels."))))
3365 (defun reftex-all-assq (key list)
3366 ;; Return a list of all associations of KEY in LIST. Comparison with string=
3368 (while (setq list (memq (assq key list) list))
3369 (push (car list) rtn)
3373 (defun reftex-all-assoc-string (key list)
3374 ;; Return a list of all associations of KEY in LIST. Comparison with string=
3377 (if (string= (car (car list)) key)
3378 (push (car list) rtn))
3382 (defun reftex-kill-temporary-buffers (&optional buffer)
3383 ;; Kill all buffers in the list reftex-kill-temporary-buffers.
3386 (when (member buffer reftex-buffers-to-kill)
3387 (kill-buffer buffer)
3388 (setq reftex-buffers-to-kill
3389 (delete buffer reftex-buffers-to-kill))))
3391 (while (setq buffer (pop reftex-buffers-to-kill))
3392 (when (bufferp buffer)
3393 (and (buffer-modified-p buffer)
3394 (y-or-n-p (format "Save file %s? "
3395 (buffer-file-name buffer)))
3399 (kill-buffer buffer))
3400 (pop reftex-buffers-to-kill)))))
3402 (defun reftex-show-entry (beg-hlt end-hlt)
3403 ;; Show entry if point is hidden by outline mode
3404 (let* ((pos (point))
3405 (n (/ (window-height) 2))
3406 (beg (save-excursion
3407 (re-search-backward "[\n\r]" nil 1 n) (point)))
3408 (end (save-excursion
3409 (re-search-forward "[\n\r]" nil 1 n) (point))))
3410 (if (and reftex-auto-show-entry
3412 "\r" (buffer-substring beg end)))
3414 ((eq t reftex-auto-show-entry)
3415 (subst-char-in-region
3416 (save-excursion (search-backward "\n" nil t) (point))
3417 (save-excursion (search-forward "\n" nil t) (point))
3419 ((eq reftex-auto-show-entry 'copy)
3420 (let ((string (buffer-substring beg end)))
3421 (switch-to-buffer "*RefTeX Context Copy*")
3422 (setq buffer-read-only nil)
3425 (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
3426 (goto-char (- pos beg))
3427 (reftex-highlight 0 (1+ (- (point) beg-hlt))
3428 (1+ (- (point) end-hlt)))
3429 (when (reftex-refontify)
3430 (set (make-local-variable 'font-lock-defaults) nil)
3431 (let ((major-mode 'latex-mode))
3432 (font-lock-mode 1)))
3433 (setq buffer-read-only t)))
3436 (defun reftex-nicify-text (text)
3437 ;; Make TEXT nice for inclusion as context into label menu
3438 ;; remove line breaks and extra white space
3439 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
3440 (setq text (replace-match " " nil t text)))
3441 ;; cut before the next `\end{' or `\item' or `\\'
3442 (if (string-match "\\(\\\\end{\\|\\\\item\\|\\\\\\\\\\).*" text)
3443 (setq text (replace-match "" nil t text)))
3444 ;; kill the embedded label
3445 (if (string-match "\\\\label{[^}]*}" text)
3446 (setq text (replace-match "" nil t text)))
3447 ;; remove leading garbage
3448 (if (string-match "\\`[ }]+" text)
3449 (setq text (replace-match "" nil t text)))
3452 ((> (length text) 100) (substring text 0 100))
3453 ((= (length text) 0) (make-string 1 ?\ ))
3456 (defun reftex-typekey-check (typekey conf-variable &optional n)
3457 ;; Check if CONF-VARIABLE is true or contains TYPEKEY
3458 (and n (setq conf-variable (nth n conf-variable)))
3459 (or (eq conf-variable t)
3460 (and (stringp conf-variable)
3461 (string-match (concat "[" conf-variable "]") typekey))))
3463 ;;; ===========================================================================
3465 ;;; Table of contents
3467 ;; We keep at most one *toc* buffer - it is easy to make them
3469 (defvar reftex-toc-map (make-sparse-keymap)
3470 "Keymap used for *toc* buffer.")
3472 (defun reftex-toc-mode ()
3473 "Major mode for managing Table of Contents for LaTeX files.
3474 This buffer was created with RefTeX.
3475 Press `?' for a summary of important key bindings.
3477 Here are all local bindings.
3481 (kill-all-local-variables)
3482 (setq major-mode 'reftex-toc-mode
3483 mode-name "RefTeX Table of Contents")
3484 (use-local-map reftex-toc-map)
3485 (set (make-local-variable 'revert-buffer-function) 'reftex-toc-revert)
3486 (setq truncate-lines t)
3487 (make-local-hook 'post-command-hook)
3488 (make-local-hook 'pre-command-hook)
3489 (make-local-variable 'reftex-last-follow-point)
3490 (add-hook 'post-command-hook 'reftex-toc-post-command-hook nil t)
3491 (add-hook 'pre-command-hook 'reftex-toc-pre-command-hook nil t)
3492 (run-hooks 'reftex-toc-mode-hook))
3494 (defvar reftex-last-toc-master nil
3495 "Stores the name of the tex file that `reftex-toc' was last run on.")
3497 (defvar reftex-last-toc-file nil
3498 "Stores the file name from which `reftex-toc' was called. For redo command.")
3500 (defvar reftex-last-window-height nil)
3502 (defvar reftex-toc-return-marker (make-marker)
3503 "Marker which makes it possible to return from toc to old position.")
3505 (defconst reftex-toc-help
3506 " AVAILABLE KEYS IN TOC BUFFER
3507 ============================
3508 n / p next-line / previous-line
3509 SPC Show the corresponding section of the LaTeX document.
3510 TAB Goto the section.
3511 RET Goto the section and hide the *toc* buffer (also on mouse-2).
3512 q / Q Hide/Kill *toc* buffer, return to position of last reftex-toc command.
3513 f / g Toggle follow mode on and off / Refresh *toc* buffer.
3514 r / R Reparse the LaTeX document / Reparse entire LaTeX document.
3515 x Switch to TOC of external document (with LaTeX package `xr').")
3517 (defun reftex-toc ()
3518 "Show the table of contents for the current document.
3519 When called with a raw C-u prefix, rescan the document first."
3523 (if (or (not (string= reftex-last-toc-master (reftex-TeX-master-file)))
3525 (reftex-erase-buffer "*toc*"))
3527 (setq reftex-last-toc-file (buffer-file-name))
3528 (setq reftex-last-toc-master (reftex-TeX-master-file))
3530 (set-marker reftex-toc-return-marker (point))
3532 ;; If follow mode is active, arrange to delay it one command
3533 (if reftex-toc-follow-mode
3534 (setq reftex-toc-follow-mode 1))
3536 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
3537 (reftex-access-scan-info current-prefix-arg)
3539 (let* ((all (symbol-value reftex-docstruct-symbol))
3540 (xr-data (assq 'xr all))
3541 (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
3542 (where (reftex-nearest-section))
3544 (if (memq reftex-highlight-selection '(mouse both))
3545 reftex-mouse-selected-face
3549 (if (get-buffer-window "*toc*")
3550 (select-window (get-buffer-window "*toc*"))
3551 (when (< (window-height) (* 2 window-min-height))
3552 (delete-other-windows))
3553 (setq reftex-last-window-height (window-height)) ; remember
3555 (let ((default-major-mode 'reftex-toc-mode))
3556 (switch-to-buffer "*toc*")))
3558 (or (eq major-mode 'reftex-toc-mode) (reftex-toc-mode))
3561 ;; buffer is empty - fill it with the table of contents
3562 ((= (buffer-size) 0)
3563 (message "Building *toc* buffer...")
3565 (setq buffer-read-only nil)
3567 "TABLE-OF-CONTENTS on %s
3568 SPC=view TAB=goto RET=goto+hide [q]uit [r]escan [f]ollow-mode e[x]tern [?]Help
3569 -------------------------------------------------------------------------------
3570 " (abbreviate-file-name reftex-last-toc-master)))
3571 (setq startpos (point))
3573 (if (reftex-use-fonts)
3574 (put-text-property 1 (point) 'face reftex-toc-header-face))
3575 (put-text-property 1 (point) 'intangible t)
3576 (put-text-property 1 2 'xr-alist xr-alist)
3579 (setq cell (car all)
3581 (when (eq (car cell) 'toc)
3582 (setq toc1 (concat (nth 2 cell) "\n"))
3583 (put-text-property 0 (length toc1) 'toc cell toc1)
3585 (put-text-property 0 (1- (length toc1))
3586 'mouse-face mouse-face toc1))
3589 (backward-delete-char 1)
3591 (message "Building *toc* buffer...done.")
3592 (setq buffer-read-only t))
3596 (setq startpos (point))))
3598 ;; Find the correct section
3599 (goto-char (point-max))
3601 (while (and (> (point) startpos)
3602 (not (eq (get-text-property (point) 'toc) where)))
3603 (beginning-of-line 0))
3604 (setq reftex-last-follow-point (point))))
3606 (defun reftex-nearest-section ()
3607 ;; Return (file . find) of nearest section command
3608 (let* ((here-I-am (car (reftex-where-am-I))))
3609 (reftex-last-assoc-before-elt
3610 'toc here-I-am (symbol-value reftex-docstruct-symbol))))
3612 (defun reftex-toc-pre-command-hook ()
3613 ;; used as pre command hook in *toc* buffer
3614 (reftex-unhighlight 0)
3615 (reftex-unhighlight 1))
3617 (defun reftex-toc-post-command-hook ()
3618 ;; used in the post-command-hook for the *toc* buffer
3620 (memq reftex-highlight-selection '(cursor both))
3623 (progn (beginning-of-line) (point))
3624 (progn (end-of-line) (point)))))
3626 ((integerp reftex-toc-follow-mode)
3627 ;; remove delayed action
3628 (setq reftex-toc-follow-mode t))
3629 ((and reftex-toc-follow-mode
3630 (not (equal reftex-last-follow-point (point))))
3631 ;; show context in other window
3632 (setq reftex-last-follow-point (point))
3634 (reftex-toc-visit-line nil (not reftex-revisit-to-follow))
3637 (defun reftex-re-enlarge ()
3639 (max 0 (- (or reftex-last-window-height (window-height))
3642 (defun reftex-toc-show-help ()
3644 (with-output-to-temp-buffer "*RefTeX Help*"
3645 (princ reftex-toc-help))
3646 ;; If follow mode is active, arrange to delay it one command
3647 (if reftex-toc-follow-mode
3648 (setq reftex-toc-follow-mode 1)))
3650 (defun reftex-toc-toggle-follow ()
3651 "Toggle toc-follow mode.
3652 (It is not really a mode, just a flag)."
3654 (setq reftex-toc-follow-mode (not reftex-toc-follow-mode)))
3655 (defun reftex-toc-view-line ()
3656 "View document location in other window."
3658 (reftex-toc-visit-line))
3659 (defun reftex-toc-mouse-view-line (ev)
3660 "View document location in other window."
3662 (mouse-set-point ev)
3663 (reftex-toc-visit-line))
3664 (defun reftex-toc-goto-line-and-hide ()
3665 "Go to document location in other window. Hide the *toc* window."
3667 (reftex-toc-visit-line 'hide))
3668 (defun reftex-toc-goto-line ()
3669 "Go to document location in other window. Hide the *toc* window."
3671 (reftex-toc-visit-line t))
3672 (defun reftex-toc-mouse-goto-line-and-hide (ev)
3673 "Go to document location in other window. Hide the *toc* window."
3675 (mouse-set-point ev)
3676 (reftex-toc-visit-line 'hide))
3677 (defun reftex-toc-quit ()
3678 "Hide the *toc* window and do not move point."
3680 (or (one-window-p) (delete-window))
3681 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
3683 (goto-char (or (marker-position reftex-toc-return-marker) (point))))
3684 (defun reftex-toc-quit-and-kill ()
3685 "Kill the *toc* buffer."
3687 (kill-buffer "*toc*")
3688 (or (one-window-p) (delete-window))
3689 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
3691 (goto-char (marker-position reftex-toc-return-marker)))
3692 (defun reftex-toc-rescan (&rest ignore)
3693 "Regenerate the *toc* buffer by reparsing file of section at point."
3695 (if reftex-enable-partial-scans
3696 (let ((file (nth 3 (get-text-property (point) 'toc))))
3698 (error "Don't know which file to rescan. Try `R'.")
3699 (switch-to-buffer-other-window
3700 (reftex-get-file-buffer-force file))
3701 (setq current-prefix-arg '(4))
3703 (reftex-toc-Rescan))
3704 (reftex-kill-temporary-buffers))
3705 (defun reftex-toc-Rescan (&rest ignore)
3706 "Regenerate the *toc* buffer by reparsing the entire document."
3708 (switch-to-buffer-other-window
3709 (reftex-get-file-buffer-force reftex-last-toc-file))
3710 (setq current-prefix-arg '(16))
3712 (defun reftex-toc-revert (&rest ignore)
3713 "Regenerate the *toc* from the internal lists."
3715 (switch-to-buffer-other-window
3716 (reftex-get-file-buffer-force reftex-last-toc-file))
3717 (reftex-erase-buffer "*toc*")
3718 (setq current-prefix-arg nil)
3720 (defun reftex-toc-external (&rest ignore)
3721 "Switch to table of contents of an external document."
3723 (let* ((old-buf (current-buffer))
3724 (xr-alist (get-text-property 1 'xr-alist))
3725 (xr-index (reftex-select-external-document
3727 (switch-to-buffer-other-window (or (reftex-get-file-buffer-force
3728 (cdr (nth xr-index xr-alist)))
3729 (error "Cannot switch document")))
3731 (if (equal old-buf (current-buffer))
3733 (message "Switched document"))))
3735 (defun reftex-toc-visit-line (&optional final no-revisit)
3736 ;; Visit the tex file corresponding to the toc entry on the current line.
3737 ;; If FINAL is t, stay there
3738 ;; If FINAL is 'hide, hide the *toc* window.
3739 ;; Otherwise, move cursor back into *toc* window.
3740 ;; This function is pretty clever about finding back a section heading,
3741 ;; even if the buffer is not live, or things like outline, x-symbol etc.
3742 ;; have been active.
3744 (let* ((toc (get-text-property (point) 'toc))
3746 (marker (nth 4 toc))
3748 (literal (nth 7 toc))
3749 (emergency-point (nth 8 toc))
3750 (toc-window (selected-window))
3751 show-window show-buffer match)
3753 (unless toc (error "Don't know which toc line to visit"))
3757 ((and (markerp marker) (marker-buffer marker))
3758 ;; Buffer is still live and we have the marker. Should be easy.
3759 (switch-to-buffer-other-window (marker-buffer marker))
3760 (goto-char (marker-position marker))
3761 (or (looking-at (regexp-quote literal))
3762 (looking-at (reftex-make-regexp-allow-for-ctrl-m literal))
3763 (looking-at (reftex-make-desperate-section-regexp literal))
3764 (looking-at (concat "\\\\"
3766 (car (rassq level reftex-section-levels)))
3768 ((or (not no-revisit)
3769 (get-file-buffer file))
3770 ;; Marker is lost. Use the backup method.
3771 (switch-to-buffer-other-window
3772 (reftex-get-file-buffer-force file nil))
3773 (goto-char (or emergency-point (point-min)))
3774 (or (looking-at (regexp-quote literal))
3775 (let ((pos (point)))
3776 (re-search-backward "\\`\\|[\r\n][ \t]*[\r\n]" nil t)
3777 (or (reftex-nearest-match (regexp-quote literal) pos)
3778 (reftex-nearest-match
3779 (reftex-make-regexp-allow-for-ctrl-m literal) pos)
3780 (reftex-nearest-match
3781 (reftex-make-desperate-section-regexp literal) pos)))))
3784 (setq show-window (selected-window)
3785 show-buffer (current-buffer))
3788 (select-window toc-window)
3789 (error "Cannot find line"))
3791 (goto-char (match-beginning 0))
3793 (reftex-highlight 0 (match-beginning 0) (match-end 0) (current-buffer))
3795 (select-window toc-window)
3797 ;; use the `final' parameter to decide what to do next
3800 (reftex-unhighlight 0)
3801 (select-window show-window))
3803 (reftex-unhighlight 0)
3804 (or (one-window-p) (delete-window))
3805 (switch-to-buffer show-buffer)
3806 (reftex-re-enlarge))
3809 ;;; ===========================================================================
3811 ;;; BibTeX citations.
3813 ;; Variables and constants
3815 ;; Define variable to silence compiler warnings
3816 (defvar reftex-cite-format-builtin)
3818 ;; The history list of regular expressions used for citations
3819 (defvar reftex-cite-regexp-hist nil)
3821 ;; Prompt and help string for citation selection
3822 (defconst reftex-citation-prompt
3823 "Select: [n]ext [p]revious [r]estrict [ ]full_entry [q]uit RET [?]Help+more")
3825 (defconst reftex-citation-help
3826 " n / p Go to next/previous entry (Cursor motion works as well).
3827 C-s / C-r Search forward/backward. Use repeated C-s/C-r as in isearch.
3828 g / r Start over with new regexp / Refine with additional regexp.
3829 SPC Show full database entry in other window.
3830 f Toggle follow mode: Other window will follow with full db entry.
3831 . Show insertion point.
3832 q Quit without inserting \\cite macro into buffer.
3833 TAB Enter citation key with completion.
3834 RET Accept current entry (also on mouse-2)
3835 a Accept all entries.")
3837 (defvar reftex-select-bib-map nil
3838 "Keymap used for *RefTeX Select* buffer, when selecting a BibTeX entry.
3839 This keymap can be used to configure the BibTeX selection process which is
3840 started with the command \\[reftex-citation].")
3842 (defun reftex-select-bib-mode ()
3843 "Major mode for selecting a citation key in a LaTeX document.
3844 This buffer was created with RefTeX.
3845 It only has a meaningful keymap when you are in the middle of a
3847 In order to select a citation, move the cursor to it and press RET.
3848 Press `?' for a summary of important key bindings.
3850 During a selection process, these are the local bindings.
3852 \\{reftex-select-label-map}"
3854 (kill-all-local-variables)
3855 (make-local-hook 'pre-command-hook)
3856 (make-local-hook 'post-command-hook)
3857 (setq major-mode 'reftex-select-bib-mode
3858 mode-name "RefTeX Select Bib")
3859 ;; We do not set a local map - reftex-select-item does this.
3860 (run-hooks 'reftex-select-bib-mode-hook))
3862 ;; Find bibtex files
3864 (defun reftex-get-bibfile-list ()
3865 ;; Return list of bibfiles for current document.
3866 ;; When using the chapterbib or bibunits package you should either
3867 ;; use the same database files everywhere, or separate parts using
3868 ;; different databases into different files (included into the mater file).
3869 ;; Then this function will return the applicable database files.
3871 ;; Ensure access to scanning info
3872 (reftex-access-scan-info)
3874 ;; Try inside this file (and its includes)
3875 (cdr (reftex-last-assoc-before-elt
3876 'bib (list 'eof (buffer-file-name))
3877 (member (list 'bof (buffer-file-name))
3878 (symbol-value reftex-docstruct-symbol))))
3879 ;; Try after the beginning of this file
3880 (cdr (assq 'bib (member (list 'bof (buffer-file-name))
3881 (symbol-value reftex-docstruct-symbol))))
3882 ;; Anywhere in the entire document
3883 (cdr (assq 'bib (symbol-value reftex-docstruct-symbol)))
3884 (error "\\bibliography statement missing or .bib files not found.")))
3886 (defun reftex-find-tex-file (file master-dir &optional die)
3887 ;; Find FILE in MASTER-DIR or on reftex-tex-path.
3888 ;; FILE may be given without the .tex extension.
3890 ((file-name-absolute-p file)
3891 (if (file-exists-p file) file nil))
3893 (reftex-access-search-path "tex")
3894 (let* ((path (cons master-dir reftex-tex-path))
3897 (or (reftex-find-file-on-path (concat file ".tex") path)
3898 (reftex-find-file-on-path file path)))
3900 (reftex-access-search-path "tex" t file)
3901 (setq path (cons master-dir reftex-tex-path))
3903 (or (reftex-find-file-on-path (concat file ".tex") path)
3904 (reftex-find-file-on-path file path))))
3906 (die (error "No such file: %s" file) nil)
3907 (t (message "No such file: %s (ignored)" file) nil))))))
3909 (defun reftex-find-bib-file (file master-dir &optional die)
3910 ;; Find FILE in MASTER-DIR or on reftex-bib-path
3911 (reftex-access-search-path "bib")
3912 (let ((file1 (reftex-find-file-on-path
3913 file (cons master-dir reftex-bib-path))))
3915 (reftex-access-search-path "bib" t file)
3916 (setq file1 (reftex-find-file-on-path
3917 file (cons master-dir reftex-bib-path))))
3919 (die (error "No such file: %s" file) nil)
3920 (t (message "No such file: %s (ignored)" file) nil))))
3922 ;; Find a certain reference in any of the BibTeX files.
3924 (defun reftex-pop-to-bibtex-entry (key file-list
3925 &optional mark-to-kill highlight item)
3926 ;; Find BibTeX KEY in any file in FILE-LIST in another window.
3927 ;; If MARK-TO-KILL is non-nil, mark new buffer to kill.
3928 ;; If HIGHLIGHT is non-nil, highlight the match.
3929 ;; If ITEM in non-nil, search for bibitem instead of database entry.
3933 (concat "\\\\bibitem\\(\\[[^]]*\\]\\)?{" (regexp-quote key) "}")
3934 (concat "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*" (regexp-quote key))))
3935 (window-conf (current-window-configuration))
3939 (switch-to-buffer-other-window (current-buffer))
3941 (setq file (car file-list)
3942 file-list (cdr file-list))
3943 (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
3944 (error "No such file %s" file))
3945 (switch-to-buffer buf)
3947 (goto-char (point-min))
3948 (when (re-search-forward re nil t)
3949 (goto-char (match-beginning 0))
3952 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
3953 (throw 'exit (selected-window))))
3954 (set-window-configuration window-conf)
3956 (message "No \\bibitem with citation key %s" key)
3957 (message "No BibTeX entry with citation key %s" key)))))
3959 ;; Parse bibtex buffers
3961 (defun reftex-extract-bib-entries (buffers &optional get-word)
3962 ;; Extract bib entries which match regexps from BUFFERS.
3963 ;; BUFFERS is a list of buffers or file names.
3964 ;; Return list with entries."
3965 (let* (re-list first-re rest-re
3966 (buffer-list (if (listp buffers) buffers (list buffers)))
3967 found-list entry buffer1 buffer alist
3968 key-point start-point end-point)
3970 (setq re-list (split-string
3971 (read-string "RegExp [ && RegExp...]: "
3972 nil 'reftex-cite-regexp-hist)
3975 (setq first-re (car re-list) ; We'll use the first re to find things,
3976 rest-re (cdr re-list)) ; the others to narrow down.
3977 (if (string-match "\\`[ \t]*\\'" first-re)
3978 (error "Empty regular expression"))
3981 (save-window-excursion
3983 ;; Walk through all bibtex files
3985 (setq buffer (car buffer-list)
3986 buffer-list (cdr buffer-list))
3987 (if (and (bufferp buffer)
3988 (buffer-live-p buffer))
3989 (setq buffer1 buffer)
3990 (setq buffer1 (reftex-get-file-buffer-force
3991 buffer (not reftex-keep-temporary-buffers))))
3993 (error "Cannot find BibTeX file %s" buffer)
3994 (message "Scanning bibliography database %s" buffer1))
3996 (set-buffer buffer1)
3998 (goto-char (point-min))
3999 (while (re-search-forward first-re nil t)
4000 (catch 'search-again
4001 (setq key-point (point))
4002 (unless (re-search-backward
4003 "\\(\\`\\|[\n\r]\\)[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*[{(]" nil t)
4004 (throw 'search-again nil))
4005 (setq start-point (point))
4006 (goto-char (match-end 0))
4009 (error (goto-char key-point)
4010 (throw 'search-again nil)))
4011 (setq end-point (point))
4013 ;; Ignore @string, @comment and @c entries or things
4015 (when (or (string= (downcase (match-string 2)) "string")
4016 (string= (downcase (match-string 2)) "comment")
4017 (string= (downcase (match-string 2)) "c")
4018 (< (point) key-point)) ; this means match not in {}
4019 (goto-char key-point)
4020 (throw 'search-again nil))
4022 ;; Well, we have got a match
4024 (buffer-substring start-point (point)) "\n"))
4026 ;; Check if other regexp match as well
4027 (setq re-list rest-re)
4029 (unless (string-match (car re-list) entry)
4031 (throw 'search-again nil))
4034 (setq alist (reftex-parse-bibtex-entry
4035 nil start-point end-point))
4036 (push (cons "&entry" entry) alist)
4038 ;; check for crossref entries
4039 (if (assoc "crossref" alist)
4042 alist (reftex-get-crossref-alist alist))))
4045 (push (cons "&formatted" (reftex-format-bib-entry alist))
4048 ;; add it to the list
4049 (push alist found-list))))
4050 (reftex-kill-temporary-buffers))))
4051 (setq found-list (nreverse found-list))
4055 ((eq 'author reftex-sort-bibtex-matches)
4056 (sort found-list 'reftex-bib-sort-author))
4057 ((eq 'year reftex-sort-bibtex-matches)
4058 (sort found-list 'reftex-bib-sort-year))
4059 ((eq 'reverse-year reftex-sort-bibtex-matches)
4060 (sort found-list 'reftex-bib-sort-year-reverse))
4063 (defun reftex-bib-sort-author (e1 e2)
4064 (let ((al1 (reftex-get-bib-names "author" e1))
4065 (al2 (reftex-get-bib-names "author" e2)))
4066 (while (and al1 al2 (string= (car al1) (car al2)))
4069 (if (and (stringp (car al1))
4070 (stringp (car al2)))
4071 (string< (car al1) (car al2))
4072 (not (stringp (car al1))))))
4074 (defun reftex-bib-sort-year (e1 e2)
4075 (< (string-to-int (cdr (assoc "year" e1)))
4076 (string-to-int (cdr (assoc "year" e2)))))
4078 (defun reftex-bib-sort-year-reverse (e1 e2)
4079 (> (string-to-int (or (cdr (assoc "year" e1)) "0"))
4080 (string-to-int (or (cdr (assoc "year" e2)) "0"))))
4082 (defun reftex-get-crossref-alist (entry)
4083 ;; return the alist from a crossref entry
4084 (let ((crkey (cdr (assoc "crossref" entry)))
4089 (if (re-search-forward
4090 (concat "@\\w+[{(][ \t\n\r]*" (regexp-quote crkey)
4091 "[ \t\n\r]*,") nil t)
4093 (setq start (match-beginning 0))
4097 (reftex-parse-bibtex-entry nil start (point)))
4100 ;; Parse the thebibliography environment
4101 (defun reftex-extract-bib-entries-from-thebibliography (file)
4102 ;; Extract bib-entries from the \begin{thebibliography} environment.
4103 ;; Parsing is not as good as for the BibTeX database stuff.
4104 ;; The environment should be located in file FILE.
4106 (let* (start end buf entries re re-list)
4108 (error "Need file name to find thebibliography environment"))
4109 (setq buf (reftex-get-file-buffer-force
4110 file (not reftex-keep-temporary-buffers)))
4112 (error "No such file %s" file))
4113 (message "Scanning thebibliography environment in %s" file)
4119 (goto-char (point-min))
4120 (if (re-search-forward
4121 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
4123 (beginning-of-line 2)
4124 (setq start (point))))
4125 (if (re-search-forward
4126 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\end{thebibliography}" nil t)
4128 (beginning-of-line 1)
4129 (setq end (point))))
4130 (when (and start (point))
4132 (mapcar 'reftex-parse-bibitem
4135 (buffer-substring-no-properties start end)
4136 "[ \t\n\r]*\\\\bibitem\\(\\[[^]]*]\\)*")))))))
4138 (error "No bibitems found"))
4140 (setq re-list (split-string
4141 (read-string "RegExp [ && RegExp...]: "
4142 nil 'reftex-cite-regexp-hist)
4144 (if (string-match "\\`[ \t]*\\'" (car re-list))
4145 (error "Empty regular expression"))
4147 (while (and (setq re (pop re-list)) entries)
4152 (if (string-match re (cdr (assoc "&entry" x)))
4160 (cons (cons "&formatted" (reftex-format-bibitem x)) x)))
4165 ;; Parse and format individual entries
4167 (defun reftex-get-bib-names (field entry)
4168 ;; Return a list with the author or editor names in ENTRY
4169 (let ((names (reftex-get-bib-field field entry)))
4170 (if (equal "" names)
4171 (setq names (reftex-get-bib-field "editor" entry)))
4172 (while (string-match "\\band\\b[ \t]*" names)
4173 (setq names (replace-match "\n" nil t names)))
4174 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
4175 (setq names (replace-match "" nil t names)))
4176 (while (string-match "^[ \t]+\\|[ \t]+$" names)
4177 (setq names (replace-match "" nil t names)))
4178 (while (string-match "[ \t][ \t]+" names)
4179 (setq names (replace-match " " nil t names)))
4180 (split-string names "\n")))
4182 (defun reftex-parse-bibtex-entry (entry &optional from to)
4183 (let (alist key start field)
4188 (switch-to-buffer "*RefTeX-scratch*")
4193 (narrow-to-region from to))
4194 (goto-char (point-min))
4196 (if (re-search-forward
4197 "@\\(\\w+\\)[ \t\n\r]*[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
4200 (cons "&type" (downcase (reftex-match-string 1)))
4201 (cons "&key" (reftex-match-string 2)))))
4202 (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
4203 (setq key (downcase (reftex-match-string 1)))
4205 ((= (following-char) ?{)
4207 (setq start (point))
4211 ((= (following-char) ?\")
4213 (setq start (point))
4214 (while (and (search-forward "\"" nil t)
4215 (= ?\\ (char-after (- (point) 2))))))
4217 (setq start (point))
4218 (re-search-forward "[ \t\n\r,}]" nil 1)))
4219 (setq field (buffer-substring-no-properties start (1- (point))))
4220 ;; remove extra whitespace
4221 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
4222 (setq field (replace-match " " nil t field)))
4223 ;; remove leading garbage
4224 (if (string-match "^[ \t{]+" field)
4225 (setq field (replace-match "" nil t field)))
4226 ;; remove trailing garbage
4227 (if (string-match "[ \t}]+$" field)
4228 (setq field (replace-match "" nil t field)))
4229 (push (cons key field) alist))))
4232 (defun reftex-get-bib-field (fieldname entry)
4233 ;; Extract the field FIELDNAME from an ENTRY
4234 (or (cdr (assoc fieldname entry))
4237 (defun reftex-format-bib-entry (entry)
4238 ;; Format a BibTeX ENTRY so that it is nice to look at
4240 ((auth-list (reftex-get-bib-names "author" entry))
4241 (authors (mapconcat 'identity auth-list ", "))
4242 (year (reftex-get-bib-field "year" entry))
4243 (title (reftex-get-bib-field "title" entry))
4244 (type (reftex-get-bib-field "&type" entry))
4245 (key (reftex-get-bib-field "&key" entry))
4248 ((equal type "article")
4249 (concat (reftex-get-bib-field "journal" entry) " "
4250 (reftex-get-bib-field "volume" entry) ", "
4251 (reftex-get-bib-field "pages" entry)))
4252 ((equal type "book")
4253 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
4254 ((equal type "phdthesis")
4255 (concat "PhD: " (reftex-get-bib-field "school" entry)))
4256 ((equal type "mastersthesis")
4257 (concat "Master: " (reftex-get-bib-field "school" entry)))
4258 ((equal type "inbook")
4259 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
4260 ", pp. " (reftex-get-bib-field "pages" entry)))
4261 ((or (equal type "conference")
4262 (equal type "incollection")
4263 (equal type "inproceedings"))
4264 (concat "in: " (reftex-get-bib-field "booktitle" entry)))
4266 (setq authors (reftex-truncate authors 30 t t))
4267 (when (reftex-use-fonts)
4268 (put-text-property 0 (length authors) 'face reftex-bib-author-face
4270 (put-text-property 0 (length year) 'face reftex-bib-year-face
4272 (put-text-property 0 (length title) 'face reftex-bib-title-face
4274 (put-text-property 0 (length extra) 'face reftex-bib-extra-face
4276 (concat key "\n " authors " " year " " extra "\n " title "\n\n")))
4278 (defun reftex-parse-bibitem (item)
4279 ;; Parse a \bibitem entry
4280 (let ((key "") (text ""))
4281 (when (string-match "\\`{\\([^}]+\\)}\\([\001-\255]*\\)" item)
4282 (setq key (match-string 1 item)
4283 text (match-string 2 item)))
4284 ;; Clean up the text a little bit
4285 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
4286 (setq text (replace-match " " nil t text)))
4287 (if (string-match "\\`[ \t]+" text)
4288 (setq text (replace-match "" nil t text)))
4292 (cons "&entry" (concat key " " text)))))
4294 (defun reftex-format-bibitem (item)
4295 ;; Format a \bibitem entry so that it is (relatively) nice to look at.
4296 (let ((text (reftex-get-bib-field "&text" item))
4297 (key (reftex-get-bib-field "&key" item))
4300 ;; Wrap the text into several lines.
4301 (while (and (> (length text) 70)
4302 (string-match " " (substring text 60)))
4303 (push (substring text 0 (+ 60 (match-beginning 0))) lines)
4304 (setq text (substring text (+ 61 (match-beginning 0)))))
4306 (setq text (mapconcat 'identity (nreverse lines) "\n "))
4308 (when (reftex-use-fonts)
4309 (put-text-property 0 (length text) 'face reftex-bib-author-face text))
4310 (concat key "\n " text "\n\n")))
4314 (defun reftex-citation (&optional no-insert)
4315 "Make a citation using BibTeX database files.
4316 After asking for a Regular Expression, it scans the buffers with
4317 bibtex entries (taken from the \\bibliography command) and offers the
4318 matching entries for selection. The selected entry is formated according
4319 to `reftex-cite-format' and inserted into the buffer.
4320 If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
4321 The regular expression uses an expanded syntax: && is interpreted as `and'.
4322 Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
4323 When this function is called with point inside the braces of a \\cite
4324 command, it will add another key, ignoring the value of `reftex-cite-format'.
4325 When called with a numeric prefix, that many citations will be made and all
4326 put into the same \\cite command.
4327 When called with just C-u as prefix, enforces rescan of buffer for
4328 bibliography statement (e.g. if it was changed)."
4332 ;; check for recursive edit
4333 (reftex-check-recursive-edit)
4335 ;; if there is just 1 C-u prefix arg, force to rescan buffer
4336 (reftex-access-scan-info current-prefix-arg)
4338 ;; Call reftex-do-citation, but protected
4340 (reftex-do-citation current-prefix-arg no-insert)
4341 (reftex-kill-temporary-buffers)))
4343 (defun reftex-do-citation (&optional arg no-insert)
4344 ;; This really does the work of reftex-citation.
4346 ;; Check if there is already a cite command at point and change cite format
4347 ;; in order to only add another reference in the same cite command.
4348 (let (key format (macro (car (car (reftex-what-macro t)))))
4349 (if (and (stringp macro)
4350 (string-match "\\`\\\\cite\\|cite\\'" macro))
4357 (if (not (or (= (preceding-char) ?{)
4358 (= (preceding-char) ?,)))
4362 (if (not (or (= (following-char) ?})
4363 (= (following-char) ?,)))
4367 (setq format "%l"))))
4368 ;; else: figure out the correct format
4371 ((stringp reftex-cite-format) reftex-cite-format)
4372 ((and (symbolp reftex-cite-format)
4373 (assq reftex-cite-format reftex-cite-format-builtin))
4374 (nth 2 (assq reftex-cite-format reftex-cite-format-builtin)))
4375 (t reftex-cite-format)))
4377 (save-window-excursion
4378 (with-output-to-temp-buffer "*RefTeX Select*"
4379 (princ "SELECT A CITATION FORMAT\n\n")
4382 (function (lambda (x)
4383 (format "[%c] %s %s" (car x)
4384 (if (> (car x) 31) " " "")
4387 (reftex-enlarge-to-fit "*RefTeX Select*")
4388 (setq key (read-char))
4389 (if (assq key format)
4390 (setq format (cdr (assq key format)))
4391 (error "No citation format associated with key `%c'" key)))))
4393 (let* (entry data rtn ins-string re-list re found-list found-list-r)
4395 ;; Scan bibtex files
4398 ((assq 'bib (symbol-value reftex-docstruct-symbol))
4399 ;; using BibTeX database files.
4400 (reftex-extract-bib-entries (reftex-get-bibfile-list)))
4401 ((assq 'thebib (symbol-value reftex-docstruct-symbol))
4402 ;; using thebibliography environment.
4403 (reftex-extract-bib-entries-from-thebibliography
4404 (cdr (assq 'thebib (symbol-value reftex-docstruct-symbol)))))
4405 (reftex-default-bibliography
4406 (message "Using default bibliography")
4407 (reftex-extract-bib-entries reftex-default-bibliography))
4408 (t (error "Document does not have a bibliography"))))
4411 (error "Sorry, no matches found"))
4413 ;; remember where we came from
4414 (setq reftex-call-back-to-this-buffer (current-buffer))
4415 (set-marker reftex-select-return-marker (point))
4418 (save-window-excursion
4419 (delete-other-windows)
4420 (let ((default-major-mode 'reftex-select-bib-mode))
4421 (reftex-kill-buffer "*RefTeX Select*")
4422 (switch-to-buffer-other-window "*RefTeX Select*")
4423 (unless (eq major-mode 'reftex-select-bib-mode)
4424 (reftex-select-bib-mode))
4425 (let ((buffer-read-only nil))
4427 (reftex-insert-bib-matches found-list)))
4428 (setq buffer-read-only t)
4429 (if (= 0 (buffer-size))
4430 (error "Sorry, no matches found"))
4431 (setq truncate-lines t)
4437 reftex-citation-prompt
4438 reftex-citation-help
4439 reftex-select-bib-map
4441 'reftex-bibtex-selection-callback nil))
4444 (unless key (throw 'exit nil))
4449 (set-buffer reftex-call-back-to-this-buffer)
4450 (reftex-extract-bib-entries
4451 (reftex-get-bibfile-list))))
4452 (let ((buffer-read-only nil))
4454 (reftex-insert-bib-matches found-list))
4455 (if (= 0 (buffer-size))
4456 (error "Sorry, no matches found"))
4460 ;; restrict with new regular expression
4462 (split-string (read-string
4463 "RegExp [ && RegExp...]: "
4464 nil 'reftex-cite-regexp-hist)
4467 (setq re (car re-list)
4468 re-list (cdr re-list))
4475 re (cdr (assoc "&entry" x)))
4480 (setq found-list found-list-r)
4482 (let ((buffer-read-only nil))
4484 (reftex-insert-bib-matches found-list))
4496 (setq entry (list (cons "&key" key)))
4507 (if reftex-format-cite-function
4508 (funcall reftex-format-cite-function
4509 (reftex-get-bib-field "&key" entry)
4511 (reftex-format-citation entry format))))
4514 (if reftex-format-cite-function
4515 (funcall reftex-format-cite-function
4516 (reftex-get-bib-field "&key" entry)
4518 (reftex-format-citation entry format)))))
4519 (setq ins-string "")
4521 (set-marker reftex-select-return-marker (point))
4522 (kill-buffer "*RefTeX Select*")
4526 (when (string-match "\\?" ins-string)
4527 (search-backward "?")
4531 ;; Check if the prefix arg was numeric, and call recursively
4532 (when (and (integerp arg)
4535 "\\\\\\([a-zA-Z]*cite\\|cite[a-zA-Z]*\\)\\**\\(\\[[^]]*\\]\\)*{\\([^}]*\\)" nil t))
4536 (goto-char (match-end 0))
4538 (reftex-do-citation arg))
4540 ;; Return the citation key
4542 (reftex-get-bib-field "&key" entry)))))
4544 (defun reftex-insert-bib-matches (list)
4545 ;; Insert the bib matches and number them correctly
4547 (if (memq reftex-highlight-selection '(mouse both))
4548 reftex-mouse-selected-face
4554 (setq tmp (cdr (assoc "&formatted" x))
4556 (put-text-property 0 len ':data x tmp)
4557 (put-text-property 0 (1- len) 'mouse-face mouse-face tmp)
4561 (defun reftex-format-names (namelist n)
4562 (let (last (len (length namelist)))
4564 ((= 1 len) (car namelist))
4565 ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
4568 last (nth (1- n) namelist))
4569 (setcdr (nthcdr (- n 2) namelist) nil)
4571 (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
4572 (nth 1 reftex-cite-punctuation)
4575 (defun reftex-format-citation (entry format)
4576 ;; Format a citation from the info in the BibTeX ENTRY
4578 (unless (stringp format) (setq format "\\cite{%l}"))
4580 (if (and reftex-comment-citations
4581 (string-match "%l" reftex-cite-comment-format))
4582 (error "reftex-cite-comment-format contains illegal %%l"))
4584 (while (string-match
4585 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
4587 (let ((n (string-to-int (match-string 4 format)))
4588 (l (string-to-char (match-string 5 format)))
4594 (reftex-get-bib-field "&key" entry)
4595 (if reftex-comment-citations
4596 reftex-cite-comment-format
4598 ((= l ?a) (reftex-format-names
4599 (reftex-get-bib-names "author" entry)
4601 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
4602 ((= l ?b) (reftex-get-bib-field "booktitle" entry))
4603 ((= l ?c) (reftex-get-bib-field "chapter" entry))
4604 ((= l ?d) (reftex-get-bib-field "edition" entry))
4605 ((= l ?e) (reftex-format-names
4606 (reftex-get-bib-names "editor" entry)
4608 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
4609 ((= l ?h) (reftex-get-bib-field "howpublished" entry))
4610 ((= l ?i) (reftex-get-bib-field "institution" entry))
4611 ((= l ?j) (reftex-get-bib-field "journal" entry))
4612 ((= l ?k) (reftex-get-bib-field "key" entry))
4613 ((= l ?m) (reftex-get-bib-field "month" entry))
4614 ((= l ?n) (reftex-get-bib-field "number" entry))
4615 ((= l ?o) (reftex-get-bib-field "organization" entry))
4616 ((= l ?p) (reftex-get-bib-field "pages" entry))
4617 ((= l ?P) (car (split-string
4618 (reftex-get-bib-field "pages" entry)
4620 ((= l ?s) (reftex-get-bib-field "school" entry))
4621 ((= l ?u) (reftex-get-bib-field "publisher" entry))
4622 ((= l ?r) (reftex-get-bib-field "address" entry))
4623 ((= l ?t) (reftex-get-bib-field "title" entry))
4624 ((= l ?v) (reftex-get-bib-field "volume" entry))
4625 ((= l ?y) (reftex-get-bib-field "year" entry)))))
4627 (if (string= rpl "")
4628 (setq b (match-beginning 2) e (match-end 2))
4629 (setq b (match-beginning 3) e (match-end 3)))
4630 (setq format (concat (substring format 0 b) rpl (substring format e)))))
4631 (while (string-match "%%" format)
4632 (setq format (replace-match "%" t t format)))
4633 (while (string-match "[ ,.;:]*%<" format)
4634 (setq format (replace-match "" t t format)))
4637 (defun reftex-bibtex-selection-callback (data ignore no-revisit)
4638 ;; Callback function to be called from the BibTeX selection, in
4639 ;; order to display context. This function is relatively slow and not
4640 ;; recommended for follow mode. It works OK for individual lookups.
4641 (let ((win (selected-window))
4642 (key (reftex-get-bib-field "&key" data))
4643 bibfile-list item tmp)
4647 (set-buffer reftex-call-back-to-this-buffer)
4649 ((assq 'bib (symbol-value reftex-docstruct-symbol))
4650 (setq bibfile-list (reftex-get-bibfile-list)))
4651 ((setq tmp (assq 'thebib (symbol-value reftex-docstruct-symbol)))
4652 (setq bibfile-list (list (cdr tmp))
4654 (reftex-default-bibliography
4655 (setq bibfile-list reftex-default-bibliography))
4656 (t (ding) (throw 'exit))))
4660 (delq nil (mapcar (lambda (x)
4661 (if (get-file-buffer x) x nil))
4664 (reftex-pop-to-bibtex-entry
4665 key bibfile-list (not reftex-keep-temporary-buffers) t item))
4667 (select-window win)))
4669 ;;; ===========================================================================
4671 ;;; Here is the routine used for selection
4673 ;; Marker for return point from recursive edit
4674 (defvar reftex-recursive-edit-marker (make-marker))
4676 (defvar reftex-last-data nil)
4677 (defvar reftex-last-line nil)
4679 (defun reftex-check-recursive-edit ()
4680 ;; Check if we are already in a recursive edit. Abort with helpful
4682 (if (marker-position reftex-recursive-edit-marker)
4684 (substitute-command-keys
4685 "In unfinished selection process. Finish, or abort with \\[abort-recursive-edit]."))))
4687 (defun reftex-select-item (prompt help-string keymap
4690 ;; Select an item, using PROMPT. The function returns a key indicating
4691 ;; an exit status, along with a data structure indicating which item was
4693 ;; HELP-STRING contains help. KEYMAP is a keymap with the available
4694 ;; selection commands.
4695 ;; OFFSET can be a label list item which will be selected at start.
4696 ;; When it is t, point will start out at the beginning of the buffer.
4697 ;; Any other value will cause restart where last selection left off.
4698 ;; When CALL-BACK is given, it is a function which is called with the index
4700 ;; CB-FLAG is the initial value of that flag.
4702 (let* (ev data last-data callback-fwd (selection-buffer (current-buffer)))
4706 (save-window-excursion
4707 (setq truncate-lines t)
4709 ;; Find a good starting point
4713 (or (and (listp offset)
4714 (text-property-any (point-min) (point-max)
4716 (and (local-variable-p 'reftex-last-data (current-buffer))
4717 (boundp 'reftex-last-data)
4718 (listp reftex-last-data)
4719 (text-property-any (point-min) (point-max)
4720 ':data reftex-last-data))
4721 (and (local-variable-p 'reftex-last-line (current-buffer))
4722 (boundp 'reftex-last-line)
4723 (integerp reftex-last-line)
4724 (progn (goto-line reftex-last-line) (point)))
4726 (t (goto-char (point-min))))
4727 (beginning-of-line 1)
4728 (set (make-local-variable 'reftex-last-follow-point) (point))
4732 (use-local-map keymap)
4733 (add-hook 'pre-command-hook 'reftex-select-pre-command-hook nil t)
4734 (add-hook 'post-command-hook 'reftex-select-post-command-hook nil t)
4736 (set-marker reftex-recursive-edit-marker (point))
4737 (run-hooks 'post-command-hook) ;; because XEmacs does not do it
4740 (set-marker reftex-recursive-edit-marker nil)
4742 (set-buffer selection-buffer)
4744 (remove-hook 'pre-command-hook 'reftex-select-pre-command-hook t)
4745 (remove-hook 'post-command-hook
4746 'reftex-select-post-command-hook t))))))
4748 (set (make-local-variable 'reftex-last-line)
4749 (+ (count-lines (point-min) (point)) (if (bolp) 1 0)))
4750 (set (make-local-variable 'reftex-last-data) last-data)
4751 (reftex-kill-buffer "*RefTeX Help*")
4753 (list ev data last-data)))
4755 ;; The following variables are all bound dynamically in `reftex-select-item'.
4756 ;; The defvars are here only to silence the byte compiler.
4764 (defvar help-string)
4765 (defvar callback-fwd)
4768 ;; The selection commands
4770 (defun reftex-select-pre-command-hook ()
4771 (reftex-unhighlight 1)
4772 (reftex-unhighlight 0))
4774 (defun reftex-select-post-command-hook ()
4776 (setq data (get-text-property (point) ':data))
4777 (setq last-data (or data last-data))
4779 (when (and data cb-flag
4780 (not (equal reftex-last-follow-point (point))))
4781 (setq reftex-last-follow-point (point))
4782 (funcall call-back data callback-fwd
4783 (not reftex-revisit-to-follow)))
4785 (setq b (or (previous-single-property-change
4786 (1+ (point)) ':data)
4788 e (or (next-single-property-change
4791 (setq b (point) e (point)))
4792 (and (memq reftex-highlight-selection '(cursor both))
4793 (reftex-highlight 1 b e))
4794 (if (or (not (pos-visible-in-window-p b))
4795 (not (pos-visible-in-window-p e)))
4796 (recenter (/ (window-height) 2)))
4797 (when (and (fboundp 'current-message)
4798 (not (current-message)))
4801 (defun reftex-select-next (&optional arg)
4803 (setq callback-fwd t)
4804 (or (eobp) (forward-char 1))
4805 (re-search-forward "^[^. \t\n\r]" nil t arg)
4806 (beginning-of-line 1))
4807 (defun reftex-select-previous (&optional arg)
4809 (setq callback-fwd nil)
4810 (re-search-backward "^[^. \t\n\r]" nil t arg))
4811 (defun reftex-select-next-heading (&optional arg)
4814 (re-search-forward "^ " nil t arg)
4815 (beginning-of-line))
4816 (defun reftex-select-previous-heading (&optional arg)
4818 (re-search-backward "^ " nil t arg))
4819 (defun reftex-select-quit ()
4821 (throw 'myexit nil))
4822 (defun reftex-select-keyboard-quit ()
4825 (defun reftex-select-jump-to-previous ()
4829 ((and (local-variable-p 'reftex-last-data (current-buffer))
4831 (setq pos (text-property-any (point-min) (point-max)
4832 ':data reftex-last-data)))
4834 ((and (local-variable-p 'reftex-last-line (current-buffer))
4835 (integerp reftex-last-line))
4836 (goto-line reftex-last-line))
4838 (defun reftex-select-toggle-follow ()
4840 (setq cb-flag (not cb-flag)))
4841 (defun reftex-select-toggle-varioref ()
4843 (if (string= varioref "\\ref")
4844 (setq varioref "\\vref")
4845 (setq varioref "\\ref"))
4846 (force-mode-line-update))
4847 (defun reftex-select-show-insertion-point ()
4849 (let ((this-window (selected-window)))
4852 (switch-to-buffer-other-window
4853 (marker-buffer reftex-select-return-marker))
4854 (goto-char (marker-position reftex-select-return-marker))
4855 (recenter (/ (window-height) 2)))
4856 (select-window this-window))))
4857 (defun reftex-select-callback ()
4859 (if data (funcall call-back data callback-fwd nil) (ding)))
4860 (defun reftex-select-accept ()
4862 (throw 'myexit 'return))
4863 (defun reftex-select-mouse-accept (ev)
4865 (mouse-set-point ev)
4866 (setq data (get-text-property (point) ':data))
4867 (setq last-data (or data last-data))
4868 (throw 'myexit 'return))
4869 (defun reftex-select-read-label ()
4871 (let ((label (completing-read
4872 "Label: " (symbol-value reftex-docstruct-symbol)
4873 nil nil reftex-prefix)))
4874 (unless (or (equal label "") (equal label reftex-prefix))
4875 (throw 'myexit label))))
4876 (defun reftex-select-read-cite ()
4878 (let* ((list (mapcar (lambda (x)
4879 (cons (reftex-get-bib-field "&key" x) 1))
4881 (key (completing-read "Citation key: " list)))
4882 (unless (equal key "")
4883 (throw 'myexit key))))
4884 (defun reftex-select-help ()
4886 (with-output-to-temp-buffer "*RefTeX Help*"
4887 (princ help-string))
4888 (reftex-enlarge-to-fit "*RefTeX Help*" t))
4890 ;;; ===========================================================================
4892 ;;; View cross references
4894 (defun reftex-view-crossref (&optional arg)
4895 "View cross reference of \\ref or \\cite macro at point.
4896 If the macro at point is a \\ref, show the corresponding label definition.
4897 If it is a \\cite, show the BibTeX database entry or the \\bibitem.
4898 If there is no such macro at point, search forward to find one.
4899 When you call this function several times in direct succession, point will
4900 move to view subsequent cross references further down in the buffer.
4901 To cope with the plethora of variations in packages, this function
4902 assumes any macro either starting with or ending in `ref' or `cite' to
4903 contain cross references.
4904 When the LaTeX package `xr' is being used, this command will also view
4905 crossreferences in external documents. However, this works correctly only
4906 when the \\externaldocument macros are used with the optional label prefix
4908 With one or two C-u prefixes, enforce rescanning of the document.
4909 With argument t or 1, select the window showing the cross reference."
4913 ;; See where we are.
4914 (let* ((re "\\\\\\([a-z]*\\(cite\\|ref\\)\\|\\(cite\\|ref\\)[a-z]*\\)\\**\\(\\[[^{}]*\\]\\)?{")
4915 (macro (car (car (reftex-what-macro t))))
4916 (this-word (reftex-this-word "*a-zA-Z\\\\"))
4917 (my-window (selected-window))
4918 pop-window cmd args point)
4921 (string-match "\\`\\\\cite\\|\\`\\\\ref\\|cite\\'\\|ref\\'"
4923 (and (setq macro (match-string 0 macro))
4924 (string-match "\\`\\\\" macro)
4925 (setq macro (substring macro 1)))
4929 (eq last-command this-command)
4930 (eq last-command 'reftex-view-crossref))
4931 (if (string= macro "cite")
4933 (skip-chars-forward "^},%")
4934 (while (and (eq (following-char) ?%)
4935 (or (beginning-of-line 2) t)
4936 (skip-chars-forward " \t\n\r")))
4937 (skip-chars-forward ",")
4938 (if (eq (following-char) ?})
4942 (if (and (not macro)
4943 (or (not (string-match "\\`\\\\" this-word))
4944 (eq (following-char) ?\\)
4945 (search-backward "\\" nil t)
4948 ;; Only move far if this function was called directly
4949 (and (re-search-forward re nil t)
4950 (setq macro (or (match-string 2) (match-string 3))))
4951 ;; The macro needs to be at point
4952 (and (looking-at re)
4953 (setq macro (or (match-string 2) (match-string 3)))
4954 (goto-char (match-end 0)))))
4958 (error "No cross reference to display"))
4960 ;; Ensure access to scanning info
4961 (reftex-access-scan-info current-prefix-arg)
4964 ((string= macro "cite")
4966 ((assq 'bib (symbol-value reftex-docstruct-symbol))
4967 (setq cmd 'reftex-pop-to-bibtex-entry
4969 (reftex-this-word "^{},%\n\r")
4970 (reftex-get-bibfile-list) nil t)))
4971 ((assq 'thebib (symbol-value reftex-docstruct-symbol))
4972 (setq cmd 'reftex-pop-to-bibtex-entry
4974 (reftex-this-word "^{},%\n\r")
4975 (list (cdr (assq 'thebib
4976 (symbol-value reftex-docstruct-symbol))))
4978 (t (error "Cannot display crossref\n"))))
4979 ((string= macro "ref")
4980 (let* ((label (reftex-this-word "^{}%\n\r"))
4981 (xr-data (assoc 'xr (symbol-value reftex-docstruct-symbol)))
4982 (xr-re (nth 2 xr-data))
4983 (entry (assoc label (symbol-value reftex-docstruct-symbol))))
4985 (if (and (not entry) (string-match xr-re label))
4986 ;; Label is defined in external document
4990 (or (reftex-get-file-buffer-force
4991 (cdr (assoc (match-string 1 label) (nth 1 xr-data))))
4992 (error "Problem with external label %s" label))))
4993 (setq label (substring label (match-end 1)))
4994 (reftex-access-scan-info)
4996 (assoc label (symbol-value reftex-docstruct-symbol)))))
4998 (setq cmd 'reftex-pop-to-label
4999 args (list label (list (nth 3 entry)) nil t))
5000 (error "Label %s not known - reparse document might help" label))))
5001 (t (error "This should not happen (reftex-view-crossref)")))
5002 (setq point (point))
5004 (setq pop-window (selected-window))
5005 (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
5006 (select-window my-window)
5008 (when (or (equal arg t) (equal arg 1))
5009 (select-window pop-window))))
5011 (defun reftex-mouse-view-crossref (ev)
5012 "View cross reference of \\ref or \\cite macro where you click.
5013 If the macro at point is a \\ref, show the corresponding label definition.
5014 If it is a \\cite, show the BibTeX database entry.
5015 If there is no such macro at point, search forward to find one.
5016 With argument, actually select the window showing the cross reference."
5018 (mouse-set-point ev)
5019 (reftex-view-crossref current-prefix-arg))
5021 ;;; ===========================================================================
5023 ;;; Functions that check out the surroundings
5025 (defun reftex-what-macro (which &optional bound)
5026 ;; Find out if point is within the arguments of any TeX-macro.
5027 ;; The return value is either ("\\macro" . (point)) or a list of them.
5029 ;; If WHICH is nil, immediately return nil.
5030 ;; If WHICH is t, return list of all macros enclosing point.
5031 ;; If WHICH is a list of macros, look only for those macros and return the
5032 ;; name of the first macro in this list found to enclose point.
5033 ;; If the optional BOUND is an integer, bound backwards directed
5034 ;; searches to this point. If it is nil, limit to nearest \section -
5037 ;; This function is pretty stable, but can be fooled if the text contains
5038 ;; things like \macro{aa}{bb} where \macro is defined to take only one
5039 ;; argument. As RefTeX cannot know this, the string "bb" would still be
5040 ;; considered an argument of macro \macro.
5042 (unless reftex-section-regexp (reftex-compute-ref-cite-tables))
5044 (if (null which) (throw 'exit nil))
5045 (let ((bound (or bound (save-excursion (re-search-backward
5046 reftex-section-regexp nil 1)
5048 pos cmd-list cmd cnt cnt-opt entry)
5051 (narrow-to-region (max 1 bound) (point-max))
5052 ;; move back out of the current parenthesis
5053 (while (condition-case nil
5054 (progn (up-list -1) t)
5056 (setq cnt 1 cnt-opt 0)
5057 ;; move back over any touching sexps
5058 (while (and (reftex-move-to-previous-arg bound)
5060 (progn (backward-sexp) t)
5062 (if (eq (following-char) ?\[) (incf cnt-opt))
5065 (when (and (or (= (following-char) ?\[)
5066 (= (following-char) ?\{))
5067 (re-search-backward "\\\\[*a-zA-Z]+\\=" nil t))
5068 (setq cmd (reftex-match-string 0))
5069 (when (looking-at "\\\\begin{[^}]*}")
5070 (setq cmd (reftex-match-string 0)
5072 ;; This does ignore optional arguments. Very hard to fix.
5073 (when (setq entry (assoc cmd reftex-env-or-mac-alist))
5074 (if (> cnt (or (nth 4 entry) 100))
5079 (push (cons cmd (point)) cmd-list))
5081 (throw 'exit (cons cmd (point))))))
5083 (nreverse cmd-list)))))
5085 (defun reftex-what-environment (which &optional bound)
5086 ;; Find out if point is inside a LaTeX environment.
5087 ;; The return value is (e.g.) either ("equation" . (point)) or a list of
5090 ;; If WHICH is nil, immediately return nil.
5091 ;; If WHICH is t, return list of all environments enclosing point.
5092 ;; If WHICH is a list of environments, look only for those environments and
5093 ;; return the name of the first environment in this list found to enclose
5096 ;; If the optional BOUND is an integer, bound backwards directed searches to
5097 ;; this point. If it is nil, limit to nearest \section - like statement.
5101 (if (null which) (throw 'exit nil))
5102 (let ((bound (or bound (save-excursion (re-search-backward
5103 reftex-section-regexp nil 1)
5105 env-list end-list env)
5106 (while (re-search-backward "\\\\\\(begin\\|end\\){\\([^}]+\\)}"
5108 (setq env (buffer-substring-no-properties
5109 (match-beginning 2) (match-end 2)))
5111 ((string= (match-string 1) "end")
5112 (add-to-list 'end-list env))
5113 ((member env end-list)
5114 (setq end-list (delete env end-list)))
5116 (push (cons env (point)) env-list))
5118 (throw 'exit (cons env (point))))))
5119 (nreverse env-list)))))
5121 ;; ============================================================================
5123 ;; Some generally useful functions
5125 (defun reftex-no-props (string)
5126 ;; Return STRING with all text properties removed
5127 (and (stringp string)
5128 (set-text-properties 0 (length string) nil string))
5131 (defun reftex-match-string (n)
5132 ;; Match string without properties
5133 (when (match-beginning n)
5134 (buffer-substring-no-properties (match-beginning n) (match-end n))))
5136 (defun reftex-kill-buffer (buffer)
5137 ;; Kill buffer if it exists.
5138 (and (setq buffer (get-buffer buffer))
5139 (kill-buffer buffer)))
5141 (defun reftex-erase-buffer (&optional buffer)
5142 ;; Erase BUFFER if it exists. BUFFER defaults to current buffer.
5143 ;; This even erases read-only buffers.
5146 ;; erase current buffer
5147 (let ((buffer-read-only nil)) (erase-buffer)))
5148 ((setq buffer (get-buffer buffer))
5152 (let ((buffer-read-only nil)) (erase-buffer))))))
5154 (defun reftex-this-word (&optional class)
5155 ;; Grab the word around point.
5156 (setq class (or class "-a-zA-Z0-9:_/.*;|"))
5158 (buffer-substring-no-properties
5159 (progn (skip-chars-backward class) (point))
5160 (progn (skip-chars-forward class) (point)))))
5162 (defvar enable-multibyte-characters)
5163 (defun reftex-truncate (string ncols &optional ellipses padding)
5164 ;; Truncate a string to NCHAR characters.
5165 ;; Works fast with ASCII and correctly with Mule characters.
5166 ;; When ELLIPSES is non-nil, put three dots at the end of the string.
5169 ((and (boundp 'enable-multibyte-characters)
5170 enable-multibyte-characters)
5171 (if (<= (string-width string) ncols)
5174 (concat (truncate-string-to-width string (- ncols 3)) "...")
5175 (truncate-string-to-width string ncols))))
5177 (if (<= (length string) ncols)
5180 (concat (substring string 0 (- ncols 3)) "...")
5181 (substring string 0 ncols))))))
5183 (format (format "%%-%ds" ncols) string)
5186 (defun reftex-nearest-match (regexp &optional pos)
5187 ;; Find the nearest match of REGEXP. Set the match data.
5188 ;; If POS is given, calculate distances relative to it.
5189 ;; Return nil if there is no match.
5190 (let ((start (point)) (pos (or pos (point))) match1 match2 match)
5192 (when (re-search-backward regexp nil t)
5193 (setq match1 (match-data)))
5195 (when (re-search-forward regexp nil t)
5196 (setq match2 (match-data)))
5200 ((not match1) match2)
5201 ((not match2) match1)
5202 ((< (abs (- pos (car match1))) (abs (- pos (car match2)))) match1)
5204 (if match (progn (store-match-data match) t) nil)))
5206 (defun reftex-auto-mode-alist ()
5207 ;; Return an `auto-mode-alist' with only the .gz (etc) thingies.
5208 ;; Stolen from gnus nnheader.
5209 (let ((alist auto-mode-alist)
5212 (when (listp (cdr (car alist)))
5213 (push (car alist) out))
5217 (defun reftex-enlarge-to-fit (buf2 &optional keep-current)
5218 ;; Enlarge other window displaying buffer without killing current window
5219 ;; If KEEP-CURRENT in non-nil, current buffer must remain visible.
5220 (let* ((win1 (selected-window))
5221 (buf1 (current-buffer))
5222 (win2 (get-buffer-window buf2)))
5224 (select-window win2)
5225 (unless (and (pos-visible-in-window-p 1)
5226 (pos-visible-in-window-p (point-max)))
5227 (enlarge-window (1+ (- (count-lines 1 (point-max))
5228 (window-height))))))
5230 ((window-live-p win1) (select-window win1))
5232 ;; we must have the old buffer!
5233 (switch-to-buffer-other-window buf1)
5234 (shrink-window (- (window-height) window-min-height))))))
5236 (defun reftex-access-search-path (which &optional recurse file)
5237 ;; Access path from environment variables. WHICH is either "tex" or "bib".
5238 ;; When RECURSE is t, expand recursive paths, ending in double slash.
5239 ;; FILE is just for the message.
5240 (let* ((pathvar (intern (concat "reftex-" which "-path")))
5241 (status (get pathvar 'status)))
5243 ((eq status 'recursed))
5244 ((and status (null recurse)))
5246 (let ((env-vars (if (equal which "tex") (list "TEXINPUTS")
5247 reftex-bibpath-environment-variables)))
5248 (set pathvar (reftex-parse-colon-path
5249 (mapconcat (function (lambda(x) (or (getenv x) "")))
5250 env-vars path-separator))))
5251 (put pathvar 'status 'split))
5252 ((and (eq 'split status) recurse)
5253 (message "Expanding search path to find %s file: %s ..." which file)
5254 (set pathvar (reftex-expand-path (symbol-value pathvar)))
5255 (put pathvar 'status 'recursed)))))
5257 (defun reftex-find-file-on-path (file path)
5258 ;; Find FILE along the directory list PATH.
5260 (when (file-name-absolute-p file)
5261 (if (file-exists-p file)
5264 (let* ((thepath path) file1 dir
5265 (doubleslash (concat "/" "/")))
5266 (while (setq dir (pop thepath))
5267 (when (string= (substring dir -2) doubleslash)
5268 (setq dir (substring dir 0 -1)))
5269 (setq file1 (expand-file-name file (expand-file-name dir)))
5270 (if (file-exists-p file1)
5271 (throw 'exit file1)))
5275 (defun reftex-parse-colon-path (path)
5276 ;; Like parse-colon-parse, but // or /~ have no effects.
5277 (mapcar 'file-name-as-directory
5278 (delete "" (split-string path (concat path-separator "+")))))
5280 (defun reftex-expand-path (path)
5281 ;; Expand parts of path ending in a double slash
5282 (let (path1 dir dirs (doubleslash (concat "/" "/")))
5283 (while (setq dir (pop path))
5284 (if (string= (substring dir -2) doubleslash)
5286 (setq dir (substring dir 0 -1))
5287 (setq dirs (reftex-recursive-directory-list dir))
5288 (setq path1 (append dirs path1)))
5292 (defun reftex-recursive-directory-list (dir)
5293 (let ((path (list dir)) dirs path1)
5294 (while (setq dir (pop path))
5300 (if (and (file-directory-p x)
5301 (not (string-match "/\\.+\\'" x)))
5302 (file-name-as-directory x)
5304 (directory-files dir t))))
5305 (setq path (append dirs path))
5309 (defun reftex-make-regexp-allow-for-ctrl-m (string)
5310 ;; convert STRING into a regexp, allowing ^M for \n and vice versa
5312 (setq string (regexp-quote string))
5313 (while (setq start (string-match "[\n\r]" string (+ 3 start)))
5314 (setq string (replace-match "[\n\r]" nil t string)))
5317 (defun reftex-make-desperate-section-regexp (old)
5318 ;; Return a regexp which will still match a section statement even if
5319 ;; x-symbol or isotex or the like have been at work in the mean time.
5320 (let* ((n (1+ (string-match "[[{]" old)))
5321 (new (regexp-quote (substring old 0 (1+ (string-match "[[{]" old)))))
5322 (old (substring old n)))
5323 (while (string-match
5324 "\\([\r\n]\\)\\|\\(\\`\\|[ \t\n\r]\\)\\([a-zA-Z0-9]+\\)\\([ \t\n\r]\\|}\\'\\)"
5326 (if (match-beginning 1)
5327 (setq new (concat new "[^\n\r]*[\n\r]"))
5328 (setq new (concat new "[^\n\r]*" (match-string 3 old))))
5329 (setq old (substring old (match-end 0))))
5332 (defun reftex-delete-list (elt-list list)
5333 ;; like delete, but with a list of things to delete
5334 ;; (original code from Rory Molinari)
5336 (setq list (delete (car elt-list) list)
5337 elt-list (cdr elt-list)))
5340 (defun reftex-get-buffer-visiting (file)
5341 ;; return a buffer visiting FILE
5343 ((boundp 'find-file-compare-truenames) ; XEmacs
5344 (let ((find-file-compare-truenames t))
5345 (get-file-buffer file)))
5346 ((fboundp 'find-buffer-visiting) ; Emacs
5347 (find-buffer-visiting file))
5348 (t (error "This should not happen (reftex-get-buffer-visiting)"))))
5350 (defun reftex-get-file-buffer-force (file &optional mark-to-kill)
5351 ;; Return a buffer visiting file. Make one, if necessary.
5352 ;; If neither such a buffer nor the file exist, return nil.
5353 ;; If MARK-TO-KILL is t and there is no live buffer, load the file with
5354 ;; initializations according to `reftex-initialize-temporary-buffers',
5355 ;; and mark the buffer to be killed after use.
5357 (let ((buf (reftex-get-buffer-visiting file)))
5360 ;; We have it already as a buffer - just return it
5363 ((file-readable-p file)
5364 ;; At least there is such a file and we can read it.
5366 (if (or (not mark-to-kill)
5367 (eq t reftex-initialize-temporary-buffers))
5369 ;; Visit the file with full magic
5370 (setq buf (find-file-noselect file))
5372 ;; Else: Visit the file just briefly, without or
5373 ;; with limited Magic
5375 ;; The magic goes away
5376 (let ((format-alist nil)
5377 (auto-mode-alist (reftex-auto-mode-alist))
5378 (default-major-mode 'fundamental-mode)
5379 (enable-local-variables nil)
5380 (after-insert-file-functions nil))
5381 (setq buf (find-file-noselect file)))
5383 ;; Is there a hook to run?
5384 (when (listp reftex-initialize-temporary-buffers)
5387 (run-hooks 'reftex-initialize-temporary-buffers))))
5389 ;; Lets see if we got a license to kill :-|
5391 (add-to-list 'reftex-buffers-to-kill buf))
5393 ;; Return the new buffer
5396 ;; If no such file exists, return nil
5399 (defun reftex-splice-symbols-into-list (list alist)
5400 ;; Splice the association in ALIST of any symbols in LIST into the list.
5404 (while (and (not (null (car list))) ;; keep list elements nil
5405 (symbolp (car list)))
5406 (setq tmp (car list))
5409 (setq list (append (nth 2 (assoc tmp alist)) (cdr list))))
5411 (error "Cannot treat symbol %s in reftex-label-alist"
5412 (symbol-name tmp)))))
5413 (push (pop list) rtn))
5416 (defun reftex-uniquify (alist &optional keep-list)
5417 ;; Return a list of all elements in ALIST, but each car only once.
5418 ;; Elements of KEEP-LIST are not removed even if duplicate.
5421 (setq elm (pop alist))
5422 (if (or (member (car elm) keep-list)
5423 (not (assoc (car elm) new)))
5427 (defun reftex-use-fonts ()
5428 ;; Return t if we can and want to use fonts.
5431 (featurep 'font-lock)))
5433 (defun reftex-refontify ()
5434 ;; Return t if we need to refontify context
5435 (and (reftex-use-fonts)
5436 (or (eq t reftex-refontify-context)
5437 (and (eq 1 reftex-refontify-context)
5438 (or (featurep 'x-symbol))))))
5440 (defun reftex-fontify-select-label-buffer ()
5441 ;; Fontify the `*RefTeX Select*' buffer
5443 ((fboundp 'font-lock-default-fontify-region)
5444 ;; Good: we have the indirection functions, and can support lazy-lock etc.
5445 (set (make-local-variable 'font-lock-fontify-region-function)
5446 'reftex-select-font-lock-fontify-region)
5447 (let ((major-mode 'latex-mode))
5448 (font-lock-mode 1)))
5449 ((fboundp 'font-lock-set-defaults-1)
5450 ;; Looks like the XEmacs font-lock stuff.
5451 ;; FIXME: this is still kind of a hack, but might go away some day.
5452 (set (make-local-variable 'font-lock-keywords) nil)
5453 (let ((major-mode 'latex-mode)
5454 (font-lock-defaults-computed nil))
5455 (font-lock-set-defaults-1)
5456 (reftex-select-font-lock-fontify-region (point-min) (point-max))))
5459 (message "Sorry: cannot refontify RefTeX Select buffer."))))
5461 (defun reftex-select-font-lock-fontify-region (beg end &optional loudly)
5462 ;; Fontify a region, but only lines starting with a dot.
5463 (let ((func (if (fboundp 'font-lock-default-fontify-region)
5464 'font-lock-default-fontify-region
5465 'font-lock-fontify-region))
5468 (while (re-search-forward "^\\." end t)
5469 (setq beg1 (point) end1 (progn (skip-chars-forward "^\n") (point)))
5470 (funcall func beg1 end1 nil)
5473 ;; Highlighting uses overlays. If this is for XEmacs, we need to load
5474 ;; the overlay library, available in version 19.15
5475 (and (not (fboundp 'make-overlay))
5479 (error "RefTeX needs overlay emulation (available in XEmacs 19.15)"))))
5481 ;; We keep a vector with several different overlays to do our highlighting.
5482 (defvar reftex-highlight-overlays [nil nil])
5484 ;; Initialize the overlays
5485 (aset reftex-highlight-overlays 0 (make-overlay 1 1))
5486 (overlay-put (aref reftex-highlight-overlays 0)
5488 (aset reftex-highlight-overlays 1 (make-overlay 1 1))
5489 (overlay-put (aref reftex-highlight-overlays 1)
5490 'face reftex-cursor-selected-face)
5492 ;; Two functions for activating and deactivation highlight overlays
5493 (defun reftex-highlight (index begin end &optional buffer)
5494 "Highlight a region with overlay INDEX."
5495 (move-overlay (aref reftex-highlight-overlays index)
5496 begin end (or buffer (current-buffer))))
5497 (defun reftex-unhighlight (index)
5498 "Detach overlay INDEX."
5499 (delete-overlay (aref reftex-highlight-overlays index)))
5501 (defun reftex-highlight-shall-die ()
5502 ;; Function used in pre-command-hook to remove highlights.
5503 (remove-hook 'pre-command-hook 'reftex-highlight-shall-die)
5504 (reftex-unhighlight 0))
5506 ;;; ---------------------------------------------------------------------------
5508 ;;; Functions to compile the tables, reset the mode etc.
5510 (defun reftex-reset-mode ()
5511 "Reset RefTeX Mode. Required to implement changes to some list variables.
5512 This function will compile the information in `reftex-label-alist' and similar
5513 variables. It is called when RefTeX is first used, and after changes to
5517 ;; Record that we have done this
5518 (setq reftex-tables-dirty nil)
5520 (list reftex-label-alist reftex-label-alist-external-add-ons
5521 reftex-default-label-alist-entries))
5523 ;; Reset the file search path variables
5524 (put 'reftex-tex-path 'status nil)
5525 (put 'reftex-bib-path 'status nil)
5527 ;; Kill temporary buffers associated with RefTeX - just in case they
5528 ;; were not cleaned up properly
5530 (let ((buffer-list '("*RefTeX Help*" "*RefTeX Select*"
5531 "*Duplicate Labels*" "*toc*" "*RefTeX-scratch*"))
5533 (while (setq buf (pop buffer-list))
5534 (if (get-buffer buf)
5535 (kill-buffer buf))))
5536 (reftex-erase-all-selection-buffers))
5538 ;; Make sure the current document will be rescanned soon.
5539 (reftex-reset-scanning-information)
5541 ;; Plug functions into AUCTeX if the user option says so.
5542 (reftex-plug-into-AUCTeX)
5544 (message "updating internal tables...")
5545 (reftex-compute-ref-cite-tables)
5546 (message "updating internal tables... done"))
5548 (defun reftex-reset-scanning-information ()
5549 "Reset the symbols containing information from buffer scanning.
5550 This enforces rescanning the buffer on next use."
5551 (if (string= reftex-last-toc-master (reftex-TeX-master-file))
5552 (reftex-erase-buffer "*toc*"))
5553 (let ((symlist reftex-multifile-symbols)
5556 (setq symbol (car symlist)
5557 symlist (cdr symlist))
5558 (if (and (symbolp (symbol-value symbol))
5559 (not (null (symbol-value symbol))))
5560 (set (symbol-value symbol) nil)))))
5562 (defun reftex-erase-all-selection-buffers ()
5563 ;; Remove all selection buffers associated with current document.
5566 (reftex-erase-buffer (reftex-make-selection-buffer-name type))))
5567 reftex-typekey-list))
5569 (defun reftex-compute-ref-cite-tables ()
5570 ;; Update ref and cite tables
5572 ;; Update AUCTeX style information
5573 (when (and (featurep 'tex-site) (fboundp 'TeX-update-style))
5574 (condition-case nil (TeX-update-style) (error nil)))
5576 ;; Compile information in reftex-label-alist
5577 (let ((tmp (reftex-uniquify (reftex-splice-symbols-into-list
5580 reftex-label-alist-external-add-ons
5581 reftex-default-label-alist-entries)
5582 reftex-label-alist-builtin)
5584 entry env-or-mac typekeychar typekey prefix context word
5585 fmt reffmt labelfmt wordlist qh-list macros-with-labels
5586 nargs nlabel opt-args cell sum i words-are-re)
5588 (setq reftex-words-to-typekey-alist nil
5589 reftex-typekey-list nil
5590 reftex-typekey-to-format-alist nil
5591 reftex-typekey-to-prefix-alist nil
5592 reftex-env-or-mac-alist nil
5593 reftex-label-env-list nil
5594 reftex-label-mac-list nil)
5597 (setq entry (car tmp)
5598 env-or-mac (car entry)
5601 (if (null env-or-mac)
5602 (setq env-or-mac ""))
5603 (if (stringp (car entry))
5604 ;; This is before version 2.00 - convert entry to new format
5605 ;; This is just to keep old users happy
5606 (setq entry (cons (string-to-char (car entry))
5607 (cons (concat (car entry) ":")
5609 (setq typekeychar (nth 0 entry)
5610 typekey (char-to-string typekeychar)
5611 prefix (nth 1 entry)
5613 context (nth 3 entry)
5614 wordlist (nth 4 entry))
5615 (if (stringp wordlist)
5616 ;; This is before version 2.04 - convert to new format
5617 (setq wordlist (nthcdr 4 entry)))
5619 (if (and (stringp fmt)
5620 (string-match "@" fmt))
5621 ;; special syntax for specifying a label format
5622 (setq fmt (split-string fmt "@+"))
5623 (setq fmt (list "\\label{%s}" fmt)))
5624 (setq labelfmt (car fmt)
5627 (add-to-list 'reftex-typekey-list typekey))
5628 (if (and typekey prefix
5629 (not (assoc typekey reftex-typekey-to-prefix-alist)))
5630 (add-to-list 'reftex-typekey-to-prefix-alist
5631 (cons typekey prefix)))
5633 ((string-match "\\`\\\\" env-or-mac)
5635 (let ((result (reftex-parse-args env-or-mac)))
5636 (setq env-or-mac (or (first result) env-or-mac)
5637 nargs (second result)
5638 nlabel (third result)
5639 opt-args (fourth result))
5640 (if nlabel (add-to-list 'macros-with-labels env-or-mac)))
5641 (add-to-list 'reftex-label-mac-list env-or-mac))
5643 (setq nargs nil nlabel nil opt-args nil)
5644 (cond ((string= env-or-mac "any"))
5645 ((string= env-or-mac ""))
5646 ((string= env-or-mac "section"))
5648 (add-to-list 'reftex-label-env-list env-or-mac)))))
5649 ;; Translate some special context cases
5650 (when (assq context reftex-default-context-regexps)
5653 (cdr (assq context reftex-default-context-regexps))
5654 (regexp-quote env-or-mac))))
5656 (not (assoc typekey reftex-typekey-to-format-alist))
5657 (push (cons typekey reffmt) reftex-typekey-to-format-alist))
5658 (and (not (string= env-or-mac "any"))
5659 (not (string= env-or-mac ""))
5660 (not (assoc env-or-mac reftex-env-or-mac-alist))
5661 (push (list env-or-mac typekey context labelfmt
5662 nargs nlabel opt-args)
5663 reftex-env-or-mac-alist))
5664 (if (eq (car wordlist) 'regexp)
5665 (setq wordlist (cdr wordlist)
5667 (setq words-are-re nil))
5668 (while (and (setq word (pop wordlist))
5670 (setq word (identity (if words-are-re word (regexp-quote word))))
5671 (or (assoc word reftex-words-to-typekey-alist)
5672 (push (cons word typekey) reftex-words-to-typekey-alist)))
5674 ((string= "" env-or-mac) nil)
5675 ((setq cell (assoc typekey qh-list))
5676 (push env-or-mac (cdr cell)))
5678 (push (list typekey env-or-mac) qh-list)))))
5681 (sort qh-list (function
5682 (lambda (x1 x2) (string< (car x1) (car x2))))))
5683 (setq reftex-typekey-to-prefix-alist
5684 (nreverse reftex-typekey-to-prefix-alist))
5685 (setq reftex-type-query-prompt
5686 (concat "Label type: "
5687 (mapconcat (function (lambda(x) (format "[%s]" (car x))))
5690 (setq reftex-type-query-help
5691 (concat "SELECT A LABEL TYPE:\n--------------------\n"
5700 (setq sum (+ sum (length x)))
5708 ;; Convert magic words to regular expressions
5709 (setq reftex-words-to-typekey-alist
5714 fmt (cdr (assoc typekey reftex-typekey-to-format-alist)))
5715 (setq word (concat "\\W\\(" word "[ \t\n\r]*\\)\\("))
5717 (while (and (< i 10)
5719 (not (member (aref fmt i) '(?%))))
5720 (setq word (concat word "\\|" (regexp-quote
5721 (substring fmt 0 (1+ i)))))
5723 (cons (concat word "\\)\\=") typekey))
5724 (nreverse reftex-words-to-typekey-alist)))
5726 ;; Calculate the regular expressions
5727 (let ((label-re "\\\\label{\\([^}]*\\)}")
5728 (include-re "\\(\\`\\|[\n\r]\\)[ \t]*\\\\\\(include\\|input\\)[{ \t]+\\([^} \t\n\r]+\\)")
5730 (concat "\\(\\`\\|[\n\r]\\)[ \t]*\\\\\\("
5731 (mapconcat 'car reftex-section-levels "\\|")
5732 "\\)\\*?\\(\\[[^]]*\\]\\)?{"))
5733 (appendix-re "\\(\\`\\|[\n\r]\\)[ \t]*\\(\\\\appendix\\)")
5735 (if macros-with-labels
5737 (mapconcat 'regexp-quote macros-with-labels "\\|")
5740 (find-label-re-format
5742 (mapconcat 'regexp-quote (append '("\\label")
5743 macros-with-labels) "\\|")
5744 "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]")))
5745 (setq reftex-section-regexp section-re
5746 reftex-section-or-include-regexp
5747 (concat section-re "\\|" include-re)
5748 reftex-everything-regexp
5749 (concat label-re "\\|" section-re "\\|" include-re
5751 (if macros-with-labels "\\|" "") macro-re)
5752 reftex-find-label-regexp-format find-label-re-format
5753 reftex-find-label-regexp-format2
5754 "\\([]} \t\n\r]\\)\\([[{]\\)\\(%s\\)[]}]"))))
5756 ;;; Keybindings --------------------------------------------------------------
5758 (define-key reftex-mode-map "\C-c=" 'reftex-toc)
5759 (define-key reftex-mode-map "\C-c(" 'reftex-label)
5760 (define-key reftex-mode-map "\C-c)" 'reftex-reference)
5761 (define-key reftex-mode-map "\C-c[" 'reftex-citation)
5762 (define-key reftex-mode-map "\C-c&" 'reftex-view-crossref)
5764 ;; Bind `reftex-mouse-view-crossref' only when the key is still free
5765 (if (string-match "XEmacs" emacs-version)
5766 (unless (key-binding [(shift button2)])
5767 (define-key reftex-mode-map [(shift button2)]
5768 'reftex-mouse-view-crossref))
5769 (unless (key-binding [(shift mouse-2)])
5770 (define-key reftex-mode-map [(shift mouse-2)]
5771 'reftex-mouse-view-crossref)))
5773 ;; If the user requests so, she can have a few more bindings:
5775 (reftex-extra-bindings
5776 (define-key reftex-mode-map "\C-ct" 'reftex-toc)
5777 (define-key reftex-mode-map "\C-cl" 'reftex-label)
5778 (define-key reftex-mode-map "\C-cr" 'reftex-reference)
5779 (define-key reftex-mode-map "\C-cc" 'reftex-citation)
5780 (define-key reftex-mode-map "\C-cv" 'reftex-view-crossref)
5781 (define-key reftex-mode-map "\C-cg" 'reftex-grep-document)
5782 (define-key reftex-mode-map "\C-cs" 'reftex-search-document)))
5784 ;; Selection Keymaps
5785 (let ((map (make-sparse-keymap)))
5786 ; First, the common stuff
5787 (substitute-key-definition
5788 'next-line 'reftex-select-next map global-map)
5789 (substitute-key-definition
5790 'previous-line 'reftex-select-previous map global-map)
5791 (substitute-key-definition
5792 'keyboard-quit 'reftex-select-keyboard-quit map global-map)
5793 (substitute-key-definition
5794 'newline 'reftex-select-accept map global-map)
5795 (define-key map " " 'reftex-select-callback)
5796 (define-key map "n" 'reftex-select-next)
5797 (define-key map [(down)] 'reftex-select-next)
5798 (define-key map "p" 'reftex-select-previous)
5799 (define-key map [(up)] 'reftex-select-previous)
5800 (define-key map "f" 'reftex-select-toggle-follow)
5801 (define-key map "\C-m" 'reftex-select-accept)
5802 (define-key map [(return)] 'reftex-select-accept)
5803 (define-key map "q" 'reftex-select-quit)
5804 (define-key map "." 'reftex-select-show-insertion-point)
5805 (define-key map "?" 'reftex-select-help)
5806 (if (string-match "XEmacs" emacs-version)
5807 (define-key map [(button2)] 'reftex-select-mouse-accept) ; XEmacs
5808 (define-key map [(mouse-2)] 'reftex-select-mouse-accept)) ; Emacs
5810 (loop for key across "0123456789" do
5811 (define-key map (vector (list key)) 'digit-argument))
5812 (define-key map "-" 'negative-argument)
5814 (setq reftex-select-label-map map)
5815 (setq reftex-select-bib-map (copy-keymap map))
5819 (loop for key across "cgilrRstx#%" do
5820 (define-key reftex-select-label-map (vector (list key))
5821 (list 'lambda '() '(interactive) (list 'throw '(quote myexit) key))))
5822 (define-key reftex-select-label-map "b" 'reftex-select-jump-to-previous)
5823 (define-key reftex-select-label-map "v" 'reftex-select-toggle-varioref)
5824 (define-key reftex-select-label-map [(tab)] 'reftex-select-read-label)
5825 (define-key reftex-select-label-map "\C-i" 'reftex-select-read-label)
5826 (define-key reftex-select-label-map "\C-c\C-n" 'reftex-select-next-heading)
5827 (define-key reftex-select-label-map "\C-c\C-p" 'reftex-select-previous-heading)
5829 (loop for key across "grRa" do
5830 (define-key reftex-select-bib-map (vector (list key))
5831 (list 'lambda '() '(interactive) (list 'throw '(quote myexit) key))))
5832 (define-key reftex-select-bib-map "\C-i" 'reftex-select-read-cite)
5833 (define-key reftex-select-bib-map [(tab)] 'reftex-select-read-cite))
5835 ;; Table of Contents map
5836 (let ((map reftex-toc-map))
5837 (if (string-match "XEmacs" emacs-version)
5838 (define-key map [(button2)] 'reftex-toc-mouse-goto-line-and-hide);XEmacs
5839 (define-key map [(mouse-2)] 'reftex-toc-mouse-goto-line-and-hide)) ;Emacs
5840 (define-key map "n" 'next-line)
5841 (define-key map "p" 'previous-line)
5842 (define-key map "?" 'reftex-toc-show-help)
5843 (define-key map " " 'reftex-toc-view-line)
5844 (define-key map "\C-m" 'reftex-toc-goto-line-and-hide)
5845 (define-key map "\C-i" 'reftex-toc-goto-line)
5846 (define-key map "r" 'reftex-toc-rescan)
5847 (define-key map "R" 'reftex-toc-Rescan)
5848 (define-key map "g" 'revert-buffer)
5849 (define-key map "q" 'reftex-toc-quit)
5850 (define-key map "Q" 'reftex-toc-quit-and-kill)
5851 (define-key map "f" 'reftex-toc-toggle-follow)
5852 (define-key map "x" 'reftex-toc-external)
5853 (loop for key across "0123456789" do
5854 (define-key map (vector (list key)) 'digit-argument))
5855 (define-key map "-" 'negative-argument))
5857 ;;; Menus --------------------------------------------------------------------
5859 ;; Define a menu for the menu bar if Emacs is running under X
5864 reftex-mode-menu reftex-mode-map
5865 "Menu used in RefTeX mode"
5867 ["Table of Contents" reftex-toc t]
5869 ["\\label" reftex-label t]
5870 ["\\ref" reftex-reference t]
5871 ["\\cite" reftex-citation t]
5872 ["View Crossref" reftex-view-crossref t]
5875 ["Only this File" reftex-parse-one t]
5876 ["Entire Document" reftex-parse-all (reftex-is-multi)]
5877 ["Save to File" (reftex-access-parse-file 'write)
5878 (> (length (symbol-value reftex-docstruct-symbol)) 0)]
5879 ["Restore from File" (reftex-access-parse-file 'restore) t]
5881 ["Enable Partial Scans"
5882 (setq reftex-enable-partial-scans (not reftex-enable-partial-scans))
5883 :style toggle :selected reftex-enable-partial-scans]
5884 ["Auto-Save Parse Info"
5885 (setq reftex-save-parse-info (not reftex-save-parse-info))
5886 :style toggle :selected reftex-save-parse-info]
5888 ["Reset RefTeX Mode" reftex-reset-mode t])
5890 ["Search Whole Document" reftex-search-document t]
5891 ["Replace in Document" reftex-query-replace-document t]
5892 ["Grep on Document" reftex-grep-document t]
5894 ["Create TAGS File" reftex-create-tags-file t]
5896 ["Find Duplicate Labels" reftex-find-duplicate-labels t]
5897 ["Change Label and Refs" reftex-change-label t]
5898 ;;;["Renumber Simple Labels" reftex-renumber-simple-labels t]
5900 ["Save document" reftex-save-all-document-buffers t])
5902 ("Reference Options"
5904 ["Use `\\vref' by Default"
5905 (setq reftex-vref-is-default (not reftex-vref-is-default))
5906 :style toggle :selected reftex-vref-is-default]
5909 ["Use Multiple Buffers"
5910 (setq reftex-use-multiple-selection-buffers
5911 (not reftex-use-multiple-selection-buffers))
5912 :style toggle :selected reftex-use-multiple-selection-buffers]
5913 ["Auto Update Buffers"
5914 (setq reftex-auto-update-selection-buffers
5915 (not reftex-auto-update-selection-buffers))
5916 :style toggle :selected reftex-auto-update-selection-buffers])
5923 (capitalize (symbol-name (car x)))
5924 (list 'setq 'reftex-cite-format (list 'quote (car x)))
5925 ':style 'radio ':selected
5926 (list 'eq 'reftex-cite-format (list 'quote (car x))))))
5927 reftex-cite-format-builtin)
5929 "Bibinfo in Comments"
5931 (setq reftex-comment-citations (not reftex-comment-citations))
5932 :style toggle :selected reftex-comment-citations]
5934 "Sort Database Matches"
5935 ["by Author" (setq reftex-sort-bibtex-matches 'author)
5936 :style radio :selected (eq reftex-sort-bibtex-matches 'author)]
5937 ["by Year" (setq reftex-sort-bibtex-matches 'year)
5938 :style radio :selected (eq reftex-sort-bibtex-matches 'year)]
5939 ["by Year, reversed" (setq reftex-sort-bibtex-matches 'reverse-year)
5940 :style radio :selected (eq reftex-sort-bibtex-matches 'reverse-year)]
5941 ["Not" (setq reftex-sort-bibtex-matches nil)
5942 :style radio :selected (eq reftex-sort-bibtex-matches nil)])
5944 ["Browse RefTeX group" reftex-customize t]
5946 ["Build Full Customize Menu" reftex-create-customize-menu
5947 (fboundp 'customize-menu-create)])
5950 ["Info" reftex-info t]
5951 ["Commentary" reftex-show-commentary t])))
5953 ;;; Run Hook ------------------------------------------------------------------
5955 (run-hooks 'reftex-load-hook)
5957 ;;; That's it! ----------------------------------------------------------------
5959 (setq reftex-tables-dirty t) ; in case this file is evaluated by hand
5962 ;;;============================================================================
5964 ;;; reftex.el ends here