(unexec): Call update_dynamic_symbols unconditionally.
[bpt/emacs.git] / lisp / textmodes / reftex.el
CommitLineData
fba437e6 1;; reftex.el --- Minor mode for doing \label, \ref and \cite in LaTeX
a7ec1775
RS
2;; Copyright (c) 1997 Free Software Foundation, Inc.
3
4;; Author: Carsten Dominik <dominik@strw.LeidenUniv.nl>
5;; Keywords: tex
6
7;; This file is part of GNU Emacs.
8
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)
12;; any later version.
13
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.
18
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.
23
24;;---------------------------------------------------------------------------
25;;
26;;; Commentary:
27;;
fba437e6
RS
28;; RefTeX is a minor mode with distinct support for \ref, \label and
29;; \cite commands in (multi-file) LaTeX documents.
a7ec1775
RS
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.
33;;
34;; To turn RefTeX Minor Mode on and off in a particular buffer, use
35;; `M-x reftex-mode'.
36;;
37;; To turn on RefTeX Minor Mode for all LaTeX files, add one of the
38;; following lines to your .emacs file:
39;;
40;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
41;; (add-hook 'latex-mode-hook 'turn-on-reftex) ; with Emacs latex mode
42;;
43;; For key bindings, see further down in this documentation.
44;;
45;;---------------------------------------------------------------------------
46;;
47;; OVERVIEW
48;;
fba437e6 49;; 1. USING \label AND \ref. Labels and references are one of the
a7ec1775
RS
50;; strong points of LaTeX. But, in documents with hundreds of
51;; equations, figures, tables etc. it becomes quickly impossible to
52;; find good label names and to actually remember them. Then, also
53;; completion of labels in not enough. One actually needs to see the
54;; context of the label definition to find the right one.
55;;
56;; - RefTeX distinguishes labels for different environments. It
57;; always knows if a certain label references a figure, table
58;; etc. You can configure RefTeX to recognize any additional
59;; labeled environments you might have defined yourself.
60;;
61;; - RefTeX defines automatically unique labels. Type `C-c ('
62;; (reftex-label) to insert a label at point. RefTeX will either
63;; - derive a label from context (default for section labels)
64;; - insert a simple label consisting of a prefix and a number
65;; (default for equations and enumerate items) or
66;; - prompt for a label string (figures and tables)
67;; Which labels are created how can be controlled with the variable
68;; reftex-insert-label-flags.
69;;
70;; - Referencing labels is a snap and I promise you'll love it.
71;; In order to make a reference, type `C-c )' (reftex-reference).
72;; This shows an outline of the documents with all labels of a
73;; certain type (figure, equation,...) and context of the label
fba437e6 74;; definition. Selecting one of the labels inserts a \ref macro
a7ec1775
RS
75;; into the original buffer. Online help during the selection is
76;; available with `?'.
77;;
78;; 2. CITATIONS. After typing `C-c [' (reftex-citation), RefTeX will
79;; let you specify a regexp to search in current BibTeX database files
80;; (as specified in the \bibliography command) and pull out a formatted
81;; list of matches for you to choose from. The list is *formatted* and
82;; thus much easier to read than the raw database entries. It can also
83;; be sorted. The text inserted into the buffer is by default just
84;; `\cite{KEY}', but can also contain author names and the year in a
85;; configurable way. See documentation of the variable
86;; reftex-cite-format.
87;;
88;; 3. TABLE OF CONTENTS. Typing `C-c =' (reftex-toc) will show
89;; a table of contents of the document. From that buffer, you can
90;; jump quickly to every part of your document. This is similar to
91;; imenu, only it works for entire multifile documents and uses the
92;; keyboard rather than the mouse. The initial version of this
93;; function was contributed by Stephen Eglen.
94;;
95;; 4. MULTIFILE DOCUMENTS are supported in the same way as by AUCTeX.
96;; I.e. if a source file is not a full LaTeX document by itself,
97;; but included by another file, you may specify the name of
98;; the (top level) master file in a local variable section at the
99;; end of the source file, like so:
100;;
101;; %%% Local Variables:
102;; %%% TeX-master: my_master.tex
103;; %%% End:
104;;
105;; This will only take effect when you load the file next time or when
106;; you reset RefTeX with M-x reftex-reset-mode.
107;;
108;; RefTeX will also recognize the file variable tex-main-file. This
109;; variable is used by the Emacs TeX modes and works just like
110;; AUCTeX's TeX-master variable. See the documentation of your TeX/LaTeX
111;; modes.
112;;
113;; RefTeX knows about all files related to a document via input and
114;; include. It provides functions to run regular expression searches and
115;; replaces over the entire document and to create a TAGS file.
116;;
117;; 5. DOCUMENT PARSING. RefTeX needs to parse the document in order to find
118;; labels and other information. It will do it automatically once, when
119;; you start working with a document. If you need to enforce reparsing
120;; later, call any of the functions reftex-citation, reftex-label,
121;; reftex-reference, reftex-toc with a raw C-u prefix.
122;;
123;;-------------------------------------------------------------------------
124;;
125;; CONFIGURATION
126;;
127;; RefTeX contains many configurable options which change the way it works.
128;;
129;; Most importantly, RefTeX needs to be configured if you use labels to
130;; mark non-standard environments. RefTeX always understands LaTeX section
131;; commands and the following environments: figure, figure*,
132;; sidewaysfigure, table, table*, sidewaystable, equation, eqnarray,
133;; enumerate. For everythings else, it needs to be configured.
134;;
135;; A good way to configure RefTeX is with the custom.el package by Per
136;; Abrahamsen, shipped with Emacs 20 and XEmacs 19.15. To do this, just
137;; say `M-x reftex-customize'. This will not work with older versions
138;; of custom.el.
139;;
140;; Here is a complete list of the RefTeX configuration variables with
141;; their default settings. You could copy this list to your .emacs file
142;; and change whatever is necessary. Each variable has an extensive
143;; documentation string. Look it up for more information!
144;;
145;; ;; Configuration Variables and User Options for RefTeX ------------------
fba437e6 146;; ;; Support for \label and \ref ------------------------------------------
a7ec1775
RS
147;; (setq reftex-label-alist nil)
148;; (setq reftex-default-label-alist-entries '(Sideways LaTeX))
149;; (setq reftex-use-text-after-label-as-context nil)
150;; ;; Label insertion
151;; (setq reftex-insert-label-flags '("s" "sft"))
152;; (setq reftex-derive-label-parameters '(3 20 t 1 "-"
153;; ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is")))
154;; (setq reftex-label-illegal-re "[\000-\040\177-\377\\\\#$%&~^_{}]")
155;; (setq reftex-abbrev-parameters '(4 2 "^saeiou" "aeiou"))
156;; ;; Label referencing
157;; (setq reftex-label-menu-flags '(t t nil nil nil nil))
158;; (setq reftex-guess-label-type t)
159;; ;; BibteX citation configuration ----------------------------------------
160;; (setq reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB"))
161;; (setq reftex-bibfile-ignore-list nil)
162;; (setq reftex-sort-bibtex-matches 'reverse-year)
163;; (setq reftex-cite-format 'reftex-cite-format-default)
164;; ;; Table of contents configuration --------------------------------------
165;; (setq reftex-toc-follow-mode nil)
166;; ;; Miscellaneous configurations -----------------------------------------
167;; (setq reftex-extra-bindings nil)
168;; (setq reftex-use-fonts t)
169;; (setq reftex-keep-temporary-buffers t)
170;; (setq reftex-auto-show-entry t)
171;;
172;; CONFIGURATION EXAMPLES:
173;; =======================
174;;
175;; Suppose you are working with AMS-LaTeX amsmath package (with its math
176;; environments like `align', `multiline' etc.). Here is how you would
177;; configure RefTeX to recognize these environments:
178;;
179;; (setq reftex-label-alist '(AMSTeX))
180;;
181;; This is very easy since RefTeX has builtin support for AMS-LaTeX.
182;; Suppose, however, you are also
183;;
184;; - using "\newtheorem" in LaTeX in order to define two new environments
185;; "Theorem" and "Axiom" like this:
186;;
187;; \newtheorem{axiom}{Axiom}
188;; \newtheorem{theorem}{Theorem}
189;;
190;; - making your figures not directly with the figure environment, but with
191;; a macro like
192;;
193;; \newcommand{\myfig}[4][tbp]{
194;; \begin{figure}[#1]
195;; \epsimp[#4]{#2}
196;; \caption{#3}
197;; \end{figure}}
198;;
199;; which would be called like
200;;
201;; \myfig{filename}{\label{fig:13} caption text}{1}
202;;
203;; Here is how to tell RefTeX to also recognize Theorem and Axiom as
204;; labeled environments, and that any labels defined inside the \myfig
205;; macro are figure labels:
206;;
207;; (setq reftex-label-alist
208;; '(AMSTeX
209;; ("axiom" ?a "ax:" "~\\ref{%s}" nil ("Axiom" "Ax."))
210;; ("theorem" ?h "thr:" "~\\ref{%s}" t ("Theorem" "Theor." "Th."))
211;; ("\\myfig" ?f "fig:" nil t)))
212;;
213;; The type indicator characters ?a and ?h are used for prompts when
214;; RefTeX queries for a label type. Note that "h" was chosen for "theorem"
215;; since "t" is already taken by "table". Note that also "s", "f", "e", "n"
216;; are taken by the standard environments.
217;; The automatic labels for Axioms and Theorems will look like "ax:23" or
218;; "thr:24".
219;; The "\ref{%s}" is a format string indicating how to insert references to
220;; these labels. The nil format in the \myfig entry means to use the same
221;; format as other figure labels.
222;; The next item indicates how to grab context of the label definition.
223;; - t means to get it from a default location (from the beginning of a \macro
fba437e6 224;; or after the \begin statement). t is *not* a good choice for eqnarray
a7ec1775
RS
225;; and similar environments.
226;; - nil means to use the text right after the label definition.
227;; - For more complex ways of getting context, see the docstring of
228;; reftex-label-alist.
229;; The strings at the end of each entry are used to guess the correct label
230;; type from the word before point when creating a reference. E.g. if you
231;; write: "as we have shown in Theorem" and then press `C-)', RefTeX will
232;; know that you are looking for a Theorem label and restrict the labels in
233;; the menu to only these labels without even asking.
234;; See also the documentation string of the variable reftex-label-alist.
235;;
236;; Depending on how you would like the label insertion and selection for the
237;; new environments to work, you might want to add the letters "a" and "h"
238;; to some of the flags in the following variables:
239;;
240;; reftex-insert-label-flags
241;; reftex-label-menu-flags
242;;
243;; The individual flags in these variables can be set to t or nil to enable or
244;; disable the feature for all label types. They may also contain a string of
245;; label type letters in order to turn on the feature for those types only.
246;;
247;; -----
248;; If you are writing in a language different from english you might want to
249;; add magic words for that language. Here is a German example:
250;;
251;; (setq reftex-label-alist
252;; '((nil ?s nil nil nil ("Kapitel" "Kap." "Abschnitt" "Teil"))
253;; (nil ?e nil nil nil ("Gleichung" "Gl."))
254;; (nil ?t nil nil nil ("Tabelle"))
255;; (nil ?f nil nil nil ("Figur" "Abbildung" "Abb."))
256;; (nil ?n nil nil nil ("Punkt"))))
257;;
258;; Using `nil' as first item in each entry makes sure that this entry does
259;; not replace the original entry for that label type.
260;;
261;; HOOKS
262;; -----
263;; Loading reftex.el runs the hook reftex-load-hook. Turning on reftex-mode
264;; runs reftex-mode-hook.
265;;
266;;-------------------------------------------------------------------------
267;;
268;; KEY BINDINGS
269;;
270;; All important functions of RefTeX can be reached from its menu which
271;; is installed in the menu bar as "Ref" menu. Only the more frequently used
272;; functions have key bindings.
273;;
274;; Here is the default set of keybindings from RefTeX.
275;;
276;; C-c = reftex-toc
277;; C-c ( reftex-label
278;; C-c ) reftex-reference
279;; C-c [ reftex-citation
280;; C-c & reftex-view-crossref
281;;
282;; I've used these bindings in order to avoid interfering with AUCTeX's
283;; settings. Personally, I also bind some functions in the C-c LETTER
284;; map for easier access:
285;;
286;; C-c t reftex-toc
287;; C-c l reftex-label
288;; C-c r reftex-reference
289;; C-c c reftex-citation
290;; C-c v reftex-view-crossref
291;; C-c s reftex-search-document
292;; C-c g reftex-grep-document
293;;
294;; If you want to copy those as well, set in your .emacs file:
295;;
296;; (setq reftex-extra-bindings t)
297;;
298;; It is possible to bind the function for viewing cross references to a
299;; mouse event. Something like the following in .emacs will do the trick:
300;;
301;; (add-hook 'reftex-load-hook
302;; '(lambda ()
303;; (define-key reftex-mode-map [(alt mouse-1)]
304;; 'reftex-mouse-view-crossref)))
305;;
306;;-------------------------------------------------------------------------
307;;
308;; RELATED PACKAGES
309;;
310;; AUCTeX
311;; ------
312;; If you are writing any TeX or LaTeX documents with Emacs, you should
313;; have a look at AUCTeX, the definitive package to work with TeX and LaTeX.
314;; Information on AUCTeX can be found here:
315;;
316;; http://www.sunsite.auc.dk/auctex/
317;;
318;; AUCTeX version 9.7f and later can be configured to delegate label
319;; insertion to RefTeX. Do do that, say in your .emacs file
320;;
321;; (setq LaTeX-label-function 'reftex-label)
322;;
323;; RefTeX also provides functions which can replace TeX-arg-label and
324;; TeX-arg-cite in AUCTeX. These functions are compatible with the originals,
325;; but use RefTeX internals to create and select labels and citation keys.
326;; There are 3 functions: reftex-arg-label, reftex-arg-ref, reftex-arg-cite.
327;;
328;; AUCTeX can support RefTeX via style files. A style file may contain
329;; calls to reftex-add-to-label-alist which defines additions to
330;; reftex-label-alist. The argument taken by this function must have exactly
331;; the same format as reftex-label-alist. E.g. a good entry in a style file
332;; for the amsmath package would be
333;;
334;; (and (fboundp 'reftex-add-to-label-alist)
335;; (reftex-add-to-label-alist '(AMSTeX)))
336;;
337;; while a package defining a proposition environment with \newtheorem
338;; might use
339;;
340;; (and
341;; (fboundp 'reftex-add-to-label-alist)
342;; (reftex-add-to-label-alist
343;; '(("proposition" ?p "prop:" "~\\ref{%s}" t
344;; ("Proposition" "Prop.")))))
345;;
346;; Bib-cite.el
347;; -----------
348;; Once you have written a document with labels, refs and citations, it can be
349;; nice to read such a file like a hypertext document. RefTeX has some support
350;; for that (reftex-view-crossref, reftex-search-document). A more elegant
351;; interface with mouse support and links into Hyperbole is provided (among
352;; other things) by Peter S. Galbraith's bib-cite.el. There is some overlap in
353;; the functionalities of bib-cite and RefTeX. Bib-cite.el comes bundled with
354;; AUCTeX. You can also get the latest version from
355;;
356;; ftp://ftp.phys.ocean.dal.ca/users/rhogee/elisp/bib-cite.el
357;;
358;;-------------------------------------------------------------------------
359;;
360;; PERFORMANCE ISSUES
361;;
362;; 1. RefTeX will load other parts of a multifile document as well as BibTeX
363;; database files for lookup purposes. These buffers are kept, so that
364;; subsequent lookup in the same files is fast. For large documents and
365;; large BibTeX databases, this can use up a lot of memory. If you have
366;; more time than memory, try the following option, which will remove
367;; buffers created for lookup after use.
368;;
369;; (setq reftex-keep-temporary-buffers nil)
370;;
371;; 2. Parsing the document for labels and their context can be slow.
372;; Therefore, RefTeX does it just once automatically. Further parsing
373;; happens only on user request
374;; - with a raw C-u prefix arg to any of the functions reftex-label,
375;; reftex-reference, reftex-citation, reftex-toc.
376;; - with the `r' key from the label selection menu or the *toc* buffer.
377;;
378;; *** If you use reftex-label to create labels, the list will be updated
379;; *** internally, so that no extra parsing is required.
380;;
381;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
382;;
383;; KNOWN BUGS
384;;
385;; o If you change reftex-label-alist in an editing session, you need to
386;; reset reftex with `M-x reftex-reset-mode' in order to make these
387;; changes effective. Changes introduced with the function
388;; reftex-add-to-label-alist as well as changes applied from the
389;; customization buffer automatically trigger a reset.
390;;
391;; o At times the short context shown by RefTeX may not be what you want.
392;; In particular, eqnarray environments can be difficult to
393;; parse. RefTeX's default behavior for eqnarrays is to scan backwards to
394;; either a double backslash or the beginning of the environment. If this
395;; gives unsatisfactory results, make it a habit to place the label
396;; *before* each equation
397;;
398;; \begin{eqnarray}
399;; \label{eq:1}
400;; E = \gamma m c^2 \\
401;; \label{eq:2}
402;; \gamma = \sqrt{1-v^2/c^2}
403;; \end{eqnarray}
404;;
405;; and turn off parsing for context in equation and eqnarray environments
406;; with
407;;
408;; (setq reftex-use-text-after-label-as-context "e").
409;;
410;; o RefTeX keeps only one global copy of the configuration variables.
411;; Also any additions from style files go into a global variable.
412;; Practically, this should not be a problem. Theoretically, it could
413;; give conflicts if two documents used environments with identical
414;; names, but different associated label types.
415;;
416;; o Input, include, bibliography and section statements have to be first
417;; on a line (except for white space) in order to be seen by reftex.
418;;
419;; o When the document is scanned, RefTeX creates a large buffer containing
420;; the entire document instead of scanning the individual files one by
421;; one. This is necessary since a file might not contain the context
422;; needed by RefTeX.
423;;
424;; o If you have two identical section headings in the same file,
425;; reftex-toc will only let you jump to the first one because it searches
426;; for the section heading from the beginning of the file. You can work
427;; around this by changing one of the section titles in a way LaTeX does
428;; not see, e.g. with extra white space. RefTeX will distinguish
429;; \section{Introduction} from \section{ Introduction}.
430;;
431;; o RefTeX sees also labels in regions commented out and will refuse to
432;; make duplicates of such a label. This is considered to be a feature.
433;;
434;; o When RefTeX tries to show a window full of context from inside a
435;; section hidden with outline-minor-mode, it will unhide that section.
436;; This change will not be reversed automatically.
437;;
438;;---------------------------------------------------------------------------
439;;
440;; TO DO
441;;
442;; I think I am pretty much done with this one...
443;;
444;;---------------------------------------------------------------------------
445;;
446;; AUTHOR
447;;
448;; Carsten Dominik <dominik@strw.LeidenUniv.nl>
449;;
450;; with contributions from Stephen Eglen
451;;
452;; The newest version of RefTeX can be found at
453;;
454;; http://www.strw.leidenuniv.nl/~dominik/Tools/
455;; ftp://strw.leidenuniv.nl/pub/dominik/
456;;
457;; THANKS TO:
458;; ---------
459;; At least the following people have invested time to test and bug-fix
460;; reftex.el. Some have send patches for fixes or new features.
461;;
462;; Stephen Eglen <stephene@cogs.susx.ac.uk>
463;; F.E.Burstall <F.E.Burstall@maths.bath.ac.uk>
464;; Karl Eichwalder <ke@ke.Central.DE>
465;; Laurent Mugnier <mugnier@onera.fr>
466;; Rory Molinari <molinari@yunt.math.lsa.umich.edu>
467;; Soren Dayton <csdayton@cs.uchicago.edu>
468;; Daniel Polani <polani@Informatik.Uni-Mainz.DE>
469;; Allan Strand <astrand@trillium.NMSU.Edu>
470;;
471;; The view crossref feature was inspired by the similar function in
472;; Peter S. Galbraith's bib-cite.el.
473;;
474;; Finally thanks to Uwe Bolick <bolick@physik.tu-berlin.de> who first
475;; got me (some years ago) into supporting LaTeX labels and references
476;; with an Editor (which was MicroEmacs at the time).
477\f
478;;; Code:
479
480;; Stuff that needs to be there when we use defcustom
481;; --------------------------------------------------
482
483(require 'custom)
484
485(defvar reftex-tables-dirty t
486 "Flag showing if tables need to be re-computed.")
487
488(eval-and-compile
489 (defun reftex-set-dirty (symbol value)
490 (setq reftex-tables-dirty t)
491 (set symbol value)))
492
493;;; Begin of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
494
495;; Configuration Variables and User Options for RefTeX ------------------
496
497(defgroup reftex nil
498 "LaTeX label and citation support."
499 :tag "RefTeX"
500 :link '(url-link :tag "Home Page" "http://strw.leidenuniv.nl/~dominik/Tools/")
501 :prefix "reftex-"
502 :group 'tex)
503
504(defun reftex-customize ()
505 "Call the customize function with reftex as argument."
506 (interactive)
507 (if (fboundp 'customize-group)
508 (customize-group 'reftex)
509 (customize 'reftex)))
510
fba437e6 511;; Support for \label and \ref --------------------------------------
a7ec1775
RS
512
513(defgroup reftex-label-support nil
514 "Support for creation, insertion and referencing of labels in LaTeX"
515 :group 'reftex)
516
517(defgroup reftex-defining-label-environments nil
518 "Definition of environments and macros to do with label"
519 :group 'reftex-label-support)
520
521
522(defcustom reftex-label-alist nil
fba437e6 523 "Alist with information on environments for \\label-\\ref use.
a7ec1775
RS
524See the definition of reftex-label-alist-builtin for examples. This variable
525should define additions and changes to the default. The only things you MUST
526NOT change is that '?s' is the type indicator for section labels and SPACE is
527for the 'any' label type. These are hard-coded at other places in the code.
528
529Changes to this variable after reftex.el has been loaded become only
530effective when RefTeX is reset with \\[reftex-reset-mode].
531
532Each list entry is a list describing an environment or macro carrying a
533label. The elements of each list entry are:
534
5350. Name of the environment (like \"table\") or macro (like \"\\\\myfig\").
536 Special names: `section' for section labels, `any' to define a group
537 which contains all labels.
538 This may also be nil if this entry is only meant to change some settings
539 associated with the type indicator character (see below).
540
5411. Type indicator character, like ?t.
542 The type indicator is a single character used in prompts for
543 label types. It must be a printable character. The same character
544 may occur several times in this list, to cover cases in which different
545 environments carry the same label type (like equation and eqnarray).
546
5472. Label prefix string, like \"tab:\".
548 The prefix is a short string used as the start of a label. It may be the
549 empty string.
550
5513. Format string for reference insert in buffer. Each %s will be replaced by
552 the label (yes, several %s can be in there, so that you can set this to:
553 \"\\ref{%s} on page~\\pageref{%s}\").
554 When the format starts with ~, whitespace before point will be removed so
555 that the reference cannot be separated from the word before it.
556
5574. Indication on how to find the short context.
558 - If `nil', use the text following the \\label{...} macro.
559 - If `t', use
560 - text following the \\begin{...} statement of environments
561 (not a good choice in in eqnarray or enumerate environments!)
562 - the section heading for section labels.
563 - the begin of the macro for macros.
564 - If a string, use as regexp to search *backward* from the label. Context
565 is then the text following the end of the match. E.g. putting this to
566 \"\\\\\\\\caption{\" will use the beginning of the caption in a figure
567 or table environment. \"\\\\\\\\begin{eqnarray}\\\\|\\\\\\\\\\\\\\\\\"
568 works for eqnarrays.
569 - If a function, call this function with the name of the environment/macro
fba437e6 570 as argument. On call, point will be just after the \\label macro. The
a7ec1775
RS
571 function is expected to return a suitable context string. It should
572 throw an exception (error) when failing to find context.
573 Consider the following example, which would return the 10 characters
574 following the label as context:
575
576 (defun my-context-function (env-or-mac)
577 (if (> (point-max) (+ 10 (point)))
578 (buffer-substring (point) (+ 10 (point)))
579 (error \"Buffer too small\")))
580
581 Setting the variable reftex-use-text-after-label-as-context to t overrides
582 the setting here.
583
5845. List of magic words which identify a reference to be of this type. If the
585 word before point is equal to one of these words when calling
586 reftex-reference, the label list offered will be automatically restricted
587 to labels of the correct type.
588
589If the type indicator characters of two or more entries are the same, RefTeX
590will use
591 - the first non-nil format and prefix
592 - the magic words of all involved entries.
593
594Any list entry may also be a symbol. If that has an association in
595reftex-label-alist-builtin, the cdr of that association is spliced into the
596list. See the AMSTeX configuration example in the comment section of
597reftex.el."
598 :group 'reftex-defining-label-environments
599 :set 'reftex-set-dirty
600 :type '(list
601 :convert-widget
602 (lambda (widget)
603 (let*
604 ((args
605 (list
606 `(repeat
607 :inline t
608 (radio
609 :value ("" ?a nil nil t nil)
610 (choice
611 :tag "Builtin"
612 :value AMSTeX
613 ,@(mapcar (function (lambda (x)
614 (list 'const ':tag (nth 1 x) (car x))))
615 reftex-label-alist-builtin))
616 (list :tag "Detailed custom entry"
617 (choice :tag "Environment or \\macro "
618 (const :tag "Ignore, just use typekey" nil)
619 (string ""))
620 (character :tag "Typekey character " ?a)
621 (choice :tag "Label prefix string "
622 (const :tag "Copy from similar label type" nil)
623 (string :tag "Specify here" "lab:"))
624 (choice :tag "Label reference format"
625 (const :tag "Copy from similar label type" nil)
626 (string :tag "Specify here" "~\\ref{%s}"))
627 (choice :tag "Grab context method "
628 (const :tag "Default position" t)
629 (const :tag "After label" nil)
630 (regexp :tag "Regular expression" "")
631 (symbol :tag "Function" my-context-function))
632 (repeat :tag "List of Magic Words" (string))))))))
633 (widget-put widget :args args)
634 widget))))
635
636(defcustom reftex-default-label-alist-entries '(Sideways LaTeX)
637 "Default label alist specifications. LaTeX should be the last entry.
638This list describes the default label environments RefTeX should always use in
639addition to the specifications in reftex-label-alist. It is probably a
640mistake to remove the LaTeX symbol from this list.
641
642Here are the current options:
643
644LaTeX The standard LaTeX environments
645Sideways The sidewaysfigure and sidewaystable environments
646AMSTeX The math environments in the AMS_LaTeX amsmath package
647AAS The deluxetable environment from the American Astronomical Society"
648 :group 'reftex-defining-label-environments
649 :set 'reftex-set-dirty
650 :type '(list :indent 4
651 :convert-widget
652 (lambda (widget)
653 (let* ((args
654 (list
655 `(checklist
656 :inline t
657 ,@(reverse
658 (mapcar (lambda (x)
659 (list 'const ':tag (nth 1 x) (car x)))
660 reftex-label-alist-builtin))))))
661 (widget-put widget :args args)
662 widget))))
663
664(defcustom reftex-use-text-after-label-as-context nil
665 "*t means, grab context from directly after the \\label{..} macro.
666This is the fastest method for obtaining context of the label definition, but
667requires discipline when placing labels. Setting this variable to t takes
668precedence over the individual settings in reftex-label-alist.
669This variable may be set to t, nil, or a string of label type letters
670indicating the label types for which it should be true."
671 :group 'reftex-defining-label-environments
672 :set 'reftex-set-dirty
673 :type '(choice
674 (const :tag "on" t) (const :tag "off" nil)
675 (string :tag "Selected label types")))
676
677;; Label insertion
678
679(defgroup reftex-making-and-inserting-labels nil
680 "Options on how to create new labels"
681 :group 'reftex-label-support)
682
683(defcustom reftex-insert-label-flags '("s" "sft")
684 "Flags governing label insertion. First flag DERIVE, second flag PROMPT.
685
686If DERIVE is t, RefTeX will try to derive a sensible label from context.
687A section label for example will be derived from the section heading.
688The conversion of the context to a legal label is governed by the
689specifications given in reftex-derive-label-parameters.
690If RefTeX fails to derive a label, it will prompt the user.
691
692If PROMPT is t, the user will be prompted for a label string. The prompt will
693already contain the prefix, and (if DERIVE is t) a default label derived from
694context. When PROMPT is nil, the default label will be inserted without
695query.
696
697So the combination of DERIVE and PROMPT controls label insertion. Here is a
698table describing all four possibilities:
699
700DERIVE PROMPT ACTION
701-------------------------------------------------------------------------
702 nil nil Insert simple label, like eq:22 or sec:13. No query.
703 nil t Prompt for label
704 t nil Derive a label from context and insert without query
705 t t Derive a label from context and prompt for confirmation
706
707Each flag may be set to t, nil, or a string of label type letters
708indicating the label types for which it should be true.
709Thus, the combination may be set differently for each label type. The
710default settings \"s\" and \"sft\" mean: Derive section labels from headings
711(with confirmation). Prompt for figure and table labels. Use simple labels
712without confirmation for everything else."
713 :group 'reftex-making-and-inserting-labels
714 :type '(list (choice :tag "Derive label from context"
715 (const :tag "always" t)
716 (const :tag "never" nil)
717 (string :tag "for selected label types" ""))
718 (choice :tag "Prompt for label string "
719 :entry-format " %b %v"
720 (const :tag "always" t)
721 (const :tag "never" nil)
722 (string :tag "for selected label types" ""))))
723
724(defcustom reftex-derive-label-parameters '(3 20 t 1 "-" ; continue
725 ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is"))
726 "Parameters for converting a string into a label.
727NWORDS Number of words to use.
728MAXCHAR Maximum number of characters in a label string.
729ILLEGAL nil: Throw away any words containing characters illegal in labels.
730 t: Throw away only the illegal characters, not the whole word.
731ABBREV nil: Never abbreviate words.
732 t: Always abbreviate words (see reftex-abbrev-parameters).
733 not t and not nil: Abbreviate words if necessary to shorten
734 label string below MAXCHAR.
735SEPARATOR String separating different words in the label
736IGNOREWORDS List of words which should not be part of labels"
737 :group 'reftex-making-and-inserting-labels
738 :type '(list (integer :tag "Number of words " 3)
739 (integer :tag "Maximum label length " 20)
740 (choice :tag "Illegal characters in words"
741 (const :tag "throw away entire word" nil)
742 (const :tag "throw away single chars" t))
743 (choice :tag "Abbreviate words "
744 (const :tag "never" nil)
745 (const :tag "always" t)
746 (const :tag "when label is too long" 1))
747 (string :tag "Separator between words " "-")
748 (repeat :tag "Ignore words"
749 :entry-format " %i %d %v"
750 (string :tag ""))))
751
752(defcustom reftex-label-illegal-re "[\000-\040\177-\377\\\\#$%&~^_{}]"
753 "Regexp matching characters not legal in labels.
754For historic reasons, this character class comes *with* the [] brackets."
755 :group 'reftex-making-and-inserting-labels
756 :type '(regexp :tag "Character class"))
757
758(defcustom reftex-abbrev-parameters '(4 2 "^saeiou" "aeiou")
759 "Parameters for abbreviation of words.
760MIN-CHARS minimum number of characters remaining after abbreviation
761MIN-KILL minimum number of characters to remove when abbreviating words
762BEFORE character class before abbrev point in word
763AFTER character class after abbrev point in word"
764 :group 'reftex-making-and-inserting-labels
765 :type '(list
766 (integer :tag "Minimum chars per word" 4)
767 (integer :tag "Shorten by at least " 2)
768 (string :tag "cut before char class " "^saeiou")
769 (string :tag "cut after char class " "aeiou")))
770
771
772;; Label referencing
773
774(defgroup reftex-referencing-labels nil
775 "Options on how to reference labels"
776 :group 'reftex-label-support)
777
778(defcustom reftex-label-menu-flags '(t t nil nil nil nil)
779 "*List of flags governing the label menu makeup.
780The flags are:
781
782TABLE-OF-CONTENTS Show the labels embedded in a table of context.
783SECTION-NUMBERS Include section numbers (like 4.1.3) in table of contents.
784COUNTERS Show counters. This just numbers the labels in the menu.
785NO-CONTEXT Non-nil means do NOT show the short context.
786FOLLOW follow full context in other window.
787SHOW-COMMENTED Show labels from regions which are commented out. RefTeX
788 sees these labels, but does not normally show them.
789
790Each of these flags can be set to t or nil, or to a string of type letters
791indicating the label types for which it should be true. These strings work
792like character classes in regular expressions. Thus, setting one of the
793flags to \"sf\" makes the flag true for section and figure labels, nil
794for everything else. Setting it to \"^ft\" makes it the other way round.
795
796Most options can also be switched from the label menu itself - so if you
797decide here to not have a table of contents in the label menu, you can still
798get one interactively during selection from the label menu."
799 :group 'reftex-referencing-labels
800 :type '(list
801 (choice :tag "Embed in table of contents "
802 (const :tag "on" t) (const :tag "off" nil)
803 (string :tag "Selected label types"))
804 (choice :tag "Show section numbers "
805 (const :tag "on" t) (const :tag "off" nil))
806 (choice :tag "Show individual counters "
807 (const :tag "on" t) (const :tag "off" nil)
808 (string :tag "Selected label types"))
809 (choice :tag "Hide short context "
810 (const :tag "on" t) (const :tag "off" nil)
811 (string :tag "Selected label types"))
812 (choice :tag "Follow context in other window"
813 (const :tag "on" t) (const :tag "off" nil)
814 (string :tag "Selected label types"))
815 (choice :tag "Show commented labels "
816 (const :tag "on" t) (const :tag "off" nil)
817 (string :tag "Selected label types"))))
818
819
820(defcustom reftex-guess-label-type t
821 "*Non-nil means, reftex-reference will try to guess the label type.
822To do that, RefTeX will look at the word before the cursor and compare it with
823the words given in reftex-label-alist. When it finds a match, RefTeX will
824immediately offer the correct label menu - otherwise it will prompt you for
825a label type. If you set this variable to nil, RefTeX will always prompt."
826 :group 'reftex-referencing-labels
827 :type '(boolean))
828
829;; BibteX citation configuration ----------------------------------------
830
831(defgroup reftex-citation-support nil
832 "Support for referencing bibliographic data with BibTeX"
833 :group 'reftex)
834
835(defcustom reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB")
836 "*List of env vars which might contain the path to BibTeX database files."
837 :group 'reftex-citation-support
838 :set 'reftex-set-dirty
839 :type '(repeat (string :tag "Environment variable")))
840
841(defcustom reftex-bibfile-ignore-list nil
842 "List of files in \\bibliography{..} RefTeX should *not* parse.
843The file names have to be in the exact same form as in the bibliography
844macro - i.e. without the .bib extension.
845Intended for files which contain only `@string' macro definitions and the
846like, which are ignored by RefTeX anyway."
847 :group 'reftex-citation-support
848 :set 'reftex-set-dirty
849 :type '(repeat (string :tag "File name")))
850
851(defcustom reftex-sort-bibtex-matches 'reverse-year
852 "*Sorting of the entries found in BibTeX databases by reftex-citation.
853Possible values:
854nil Do not sort entries.
855'author Sort entries by author name.
856'year Sort entries by increasing year.
857'reverse-year Sort entries by decreasing year."
858 :group 'reftex-citation-support
859 :type '(choice (const :tag "not" nil)
860 (const :tag "by author" author)
861 (const :tag "by year" year)
862 (const :tag "by year, reversed" reverse-year)))
863
864(defcustom reftex-cite-format 'reftex-cite-format-default
865 "Defines the format of citations to be inserted into the buffer.
866It can be a string, a list of strings, or an alist with characters as keys
867and a list of strings in the car. In the simplest case, this can just
868be the string \"\\cite{KEY}\", which is also the default. See the
869definition of the reftex-cite-format-XXXX constants for more complex
870examples.
871 If reftex-cite-format is a string, it will be used as the format. In
872the format, AUTHOR will be replaced by the last name of the
873author, YEAR will be replaced by the year and KEY by the citation
874key. If AUTHOR is present several times, it will be replaced with
875successive author names.
876See the constant reftex-cite-format-default for an example.
877 If reftex-cite-format is a list of strings, the string used will
878depend upon the number of authors of the article. No authors means,
879the first string will be used, 1 author means, the second string will
880be used etc. The last string in the list will be used for all articles
881with too many authors. See reftex-cite-format-1-author-simple for an
882example.
883 If reftex-cite-format is a list of cons cells, the car of each cell
884needs to be a character. When a selected reference is accepted by
885pressing that key, the cdr of the associated list will be used as
886described above. See reftex-cite-format-2-authors for an example.
887 In order to configure this variable, you can either set
888reftex-cite-format directly yourself or set it to the SYMBOL of one of
889the predefined constants. E.g.:
890(setq reftex-cite-format 'reftex-cite-format-2-authors)"
891 :group 'reftex-citation-support
892 :type
893'(choice
894 (choice :tag "symbolic defaults"
895 :value reftex-cite-format-default
896 (const reftex-cite-format-default)
897 (const reftex-cite-format-1-author-simple)
898 (const reftex-cite-format-2-authors))
899 (string :tag "format string" "\\cite{KEY}")
900 (repeat :tag "list of strings"
901 :value ("\cite{KEY}" "AUTHOR \cite{KEY}" "AUTHOR and AUTHOR \cite{KEY}")
902 (string :tag "format string" ""))
903 (repeat :tag "key-ed lists of strings"
904 :value ((?\r . ("\cite{KEY}" "AUTHOR \cite{KEY}" "AUTHOR and AUTHOR \cite{KEY}")))
905 (cons :tag "Enter a keyed list of format strings"
906 (character :tag "Key character " ?\r)
907 (repeat
908 (string :tag "format string" ""))))))
909
910;; Table of contents configuration --------------------------------------
911
912(defgroup reftex-table-of-contents-browser nil
913 "A multifile table of contents browser."
914 :group 'reftex)
915
916(defcustom reftex-toc-follow-mode nil
917 "Non-nil means, point in *toc* buffer will cause other window to follow.
918The other window will show the corresponding part of the document.
919This flag can be toggled from within the *toc* buffer with the `f' key."
920 :group 'reftex-table-of-contents-browser
921 :type '(boolean))
922
923;; Miscellaneous configurations -----------------------------------------
924
925(defgroup reftex-miscellaneous-configurations nil
926 "Collection of further configurations"
927 :group 'reftex)
928
929(defcustom reftex-extra-bindings nil
930 "Non-nil means, make additional key bindings on startup.
931These extra bindings are located in the users C-c letter map."
932 :group 'reftex-miscellaneous-configurations
933 :type '(boolean))
934
935(defcustom reftex-use-fonts t
936 "*Non-nil means, use fonts in label menu and on-the-fly help.
937Font-lock must be loaded as well to actually get fontified display."
938 :group 'reftex-miscellaneous-configurations
939 :type '(boolean))
940
941(defcustom reftex-keep-temporary-buffers t
942 "*Non-nil means, keep any TeX and BibTeX files loaded for lookup.
943Nil means, kill it immediately after use unless it was already an existing
944buffer before the lookup happened. It is faster to keep the buffers, but can
945use a lot of memory, depending on the size of your database and document."
946 :group 'reftex-miscellaneous-configurations
947 :type '(boolean))
948
949(defcustom reftex-auto-show-entry t
950 "*Non-nil means, showing context in another window may unhide a section.
951This is important when using outline-minor-mode. If the context to be shown
952is in a hidden section, RefTeX will issue a \"show-entry\" command in order
953to show it. This is not reversed when the label is selected - so the section
954remains shown after command completion."
955 :group 'reftex-miscellaneous-configurations
956 :type '(boolean))
957
958
959;;; End of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
960
961;;;===========================================================================
962;;;
963;;; Define the formal stuff for a minor mode named RefTeX.
964;;;
965
966(defvar reftex-mode nil
967 "Determines if RefTeX minor mode is active.")
968(make-variable-buffer-local 'reftex-mode)
969
970(defvar reftex-mode-map (make-sparse-keymap)
971 "Keymap for RefTeX minor mode.")
972
973(defvar reftex-mode-menu nil)
974
975;;;###autoload
976(defun turn-on-reftex ()
977 "Turn on RefTeX minor mode."
978 (reftex-mode t))
979
980;;;###autoload
981(defun reftex-mode (&optional arg)
fba437e6 982 "Minor mode with distinct support for \\label, \\ref and \\cite in LaTeX.
a7ec1775
RS
983
984Labels can be created with `\\[reftex-label]' and referenced with `\\[reftex-reference]'.
985When referencing, you get a menu with all labels of a given type and
986context of the label definition. The selected label is inserted as a
fba437e6 987\\ref macro.
a7ec1775
RS
988
989Citations can be made with `\\[reftex-citation]' which will use a regular expression
990to pull out a *formatted* list of articles from your BibTeX
fba437e6 991database. The selected citation is inserted as a \\cite macro.
a7ec1775
RS
992
993A Table of Contents of the entire (multifile) document with browsing
994capabilities is available with `\\[reftex-toc]'.
995
996Most command have help available on the fly. This help is accessed by
997pressing `?' to any prompt mentioning this feature.
998
999\\{reftex-mode-map}
1000Under X, these functions will be available also in a menu on the menu bar.
1001
1002------------------------------------------------------------------------------"
1003
1004 (interactive "P")
1005 (setq reftex-mode (not (or (and (null arg) reftex-mode)
1006 (<= (prefix-numeric-value arg) 0))))
1007
1008 ; Add or remove the menu, and run the hook
1009 (if reftex-mode
1010 (progn
1011 (easy-menu-add reftex-mode-menu)
1012 (run-hooks 'reftex-mode-hook))
1013 (easy-menu-remove reftex-mode-menu)))
1014
1015(or (assoc 'reftex-mode minor-mode-alist)
1016 (setq minor-mode-alist
1017 (cons '(reftex-mode " Ref") minor-mode-alist)))
1018
1019(or (assoc 'reftex-mode minor-mode-map-alist)
1020 (setq minor-mode-map-alist
1021 (cons (cons 'reftex-mode reftex-mode-map)
1022 minor-mode-map-alist)))
1023
1024
1025;;; ===========================================================================
1026;;;
1027;;; Interfaces for other packages
1028;;; -----------------------------
1029;;;
1030;;; AUCTeX
1031;;; ------
1032
1033(defun reftex-arg-label (optional &optional prompt definition)
1034 "Use reftex-label to create a label and insert it with TeX-argument-insert.
1035This function is intended for AUCTeX macro support."
1036 (let ((label (reftex-label nil t)))
1037 (if (and definition (not (string-equal "" label)))
1038 (LaTeX-add-labels label))
1039 (TeX-argument-insert label optional optional)))
1040
1041(defun reftex-arg-ref (optional &optional prompt definition)
1042 "Use reftex-reference to select a label, insert it with TeX-argument-insert.
1043This function is intended for AUCTeX macro support."
1044 (let ((label (reftex-reference nil t)))
1045 (if (and definition (not (string-equal "" label)))
1046 (LaTeX-add-labels label))
1047 (TeX-argument-insert label optional optional)))
1048
1049(defun reftex-arg-cite (optional &optional prompt definition)
1050 "Use reftex-citation to select a key, insert it with TeX-argument-insert.
1051This function is intended for AUCTeX macro support."
1052 (let ((key (reftex-citation nil t)))
1053 (TeX-argument-insert (or key "") optional optional)))
1054
1055(defvar reftex-label-alist-external-add-ons nil
1056 "List of label alist entries added with reftex-add-to-label-alist.")
1057
1058;;;###autoload
1059(defun reftex-add-to-label-alist (entry-list)
1060 "Add label environment descriptions to reftex-label-alist-external-add-ons.
1061The format of ENTRY-LIST is exactly like reftex-label-alist. See there
1062for details.
1063This function makes it possible to support RefTeX from AUCTeX style files.
1064The entries in ENTRY-LIST will be processed after the user settings in
1065reftex-label-alist, and before the defaults (specified in
1066reftex-default-label-alist-entries). Any changes made to
1067reftex-label-alist-external-add-ons will raise a flag to the effect that a
1068mode reset is done on the next occasion."
1069 (let (entry)
1070 (while entry-list
1071 (setq entry (car entry-list)
1072 entry-list (cdr entry-list))
1073 (if (not (member entry reftex-label-alist-external-add-ons))
1074 (setq reftex-tables-dirty t
1075 reftex-label-alist-external-add-ons
1076 (cons entry reftex-label-alist-external-add-ons))))))
1077
1078;;; ===========================================================================
1079;;;
1080;;; Multifile support
1081;;;
1082;;; Technical notes: Multifile works as follows: We keep just one list
1083;;; of labels for each master file - this can save a lot of memory.
1084;;; reftex-master-index-list is an alist which connects the true file name
1085;;; of each master file with the symbols holding the information on that
1086;;; document. Each buffer has local variables which point to these symbols.
1087
1088
1089;; List of variables which handle the multifile stuff.
1090;; This list is used to tie, untie, and reset these symbols.
1091(defconst reftex-multifile-symbols
1092 '(reftex-label-numbers-symbol reftex-list-of-labels-symbol
1093 reftex-bibfile-list-symbol))
1094
1095;; Alist connecting master file names with the corresponding lisp symbols
1096(defvar reftex-master-index-list nil)
1097
1098;; Last index used for a master file
1099(defvar reftex-multifile-index 0)
1100
1101;; Alist connecting a master file with all included files.
1102;; This information is not yet used, just collected.
1103(defvar reftex-master-include-list nil)
1104
1105;; Variable holding the symbol with current value of label postfix
1106(defvar reftex-label-numbers-symbol nil )
1107(make-variable-buffer-local 'reftex-label-numbers-symbol)
1108
1109;; Variable holding the symbol with the label list of the document.
1110;; Each element of the label list is again a list with the following elements:
1111;; 0: One character label type indicator
1112;; 1: Short context to put into label menu
1113;; 2: The label
1114;; 3: The name of the file where the label is defined
1115(defvar reftex-list-of-labels-symbol nil)
1116(make-variable-buffer-local 'reftex-list-of-labels-symbol)
1117
1118;; Variable holding the symbol with a list of library files for this document
1119(defvar reftex-bibfile-list-symbol nil)
1120(make-variable-buffer-local 'reftex-bibfile-list-symbol)
1121
1122(defun reftex-next-multifile-index ()
1123 ;; Return the next free index for multifile symbols.
1124 (setq reftex-multifile-index (1+ reftex-multifile-index)))
1125
1126(defun reftex-tie-multifile-symbols ()
1127 ;; Tie the buffer-local symbols to globals connected with the master file.
1128 ;; If the symbols for the current master file do not exist, they are created.
1129
1130 (let* ((master (file-truename (reftex-TeX-master-file)))
1131 (index (assoc master reftex-master-index-list))
1132 (symlist reftex-multifile-symbols)
1133 (symbol nil)
1134 (symname nil)
1135 (newflag nil))
1136 ;; find the correct index
1137 (if index
1138 ;; symbols do exist
1139 (setq index (cdr index))
1140 ;; get a new index and add info to the alist
1141 (setq index (reftex-next-multifile-index)
1142 reftex-master-index-list (cons
1143 (cons master index)
1144 reftex-master-index-list)
1145 newflag t))
1146
1147 ;; get/create symbols and tie them
1148 (while symlist
1149 (setq symbol (car symlist)
1150 symlist (cdr symlist)
1151 symname (symbol-name symbol))
1152 (set symbol (intern (concat symname "-" (int-to-string index))))
1153 ;; initialize if new symbols
1154 (if newflag (set (symbol-value symbol) nil)))
1155
1156 ;; Return t if the symbols did already exist, nil when we've made them
1157 (not newflag)))
1158
1159(defun reftex-untie-multifile-symbols ()
1160 ;; Remove ties from multifile symbols, so that next use makes new ones.
1161 (let ((symlist reftex-multifile-symbols)
1162 (symbol nil))
1163 (while symlist
1164 (setq symbol (car symlist)
1165 symlist (cdr symlist))
1166 (set symbol nil))))
1167
1168(defun reftex-TeX-master-file ()
1169 ;; Return the name of the master file associated with the current buffer.
1170 ;; When AUCTeX is loaded, we will use it's more sophisticated method.
1171 ;; We also support the default TeX and LaTeX modes
1172 ;; by checking for a variable tex-main-file.
1173
1174 (let
1175 ((master
1176 (cond
1177 ((fboundp 'TeX-master-file) ; AUCTeX is loaded. Use its mechanism.
1178 (TeX-master-file t))
1179 ((boundp 'TeX-master) ; The variable is defined - lets use it.
1180 (cond
1181 ((eq TeX-master t)
1182 (buffer-file-name))
1183 ((eq TeX-master 'shared)
1184 (setq TeX-master (read-file-name "Master file: "
1185 nil nil t nil)))
1186 (TeX-master)
1187 (t
1188 (setq TeX-master (read-file-name "Master file: "
1189 nil nil t nil)))))
1190 ((boundp 'tex-main-file)
1191 ;; This is the variable from the default TeX modes
1192 (cond
1193 ((stringp tex-main-file)
1194 ;; ok, this must be it
1195 tex-main-file)
1196 (t
1197 ;; In this case, the buffer is its own master
1198 (buffer-file-name))))
1199 (t
1200 ;; Know nothing about master file. Assume this is a master file.
1201 (buffer-file-name)))))
1202 (cond
1203 ((null master)
1204 (error "Need a filename for this buffer. Please save it first."))
1205 ((or (file-exists-p master)
1206 (reftex-get-buffer-visiting master))
1207 ;; We either see the file, or have a buffer on it. OK.
1208 )
1209 ((or (file-exists-p (concat master ".tex"))
1210 (reftex-get-buffer-visiting (concat master ".tex")))
1211 ;; Ahh, an extra .tex was missing...
1212 (setq master (concat master ".tex")))
1213 (t
1214 ;; Something is wrong here. Throw an exception.
1215 (error "No such master file %s" master)))
1216 (expand-file-name master)))
1217
1218(defun reftex-make-master-buffer (master-file mode)
1219 "Make a master buffer which contains the MASTER-FILE and all includes.
1220This is to prepare a buffer containing the entire document in correct
1221sequence for parsing. Therefore it will even expand includes which are
1222commented out.
1223The function returns the number of input/include files not found."
1224
1225 (interactive "fmaster file: ")
1226 (let ((not-found 0) file file-list tmp (font-lock-maximum-size 1))
1227 (switch-to-buffer "*reftex-master.tex*")
1228 (erase-buffer)
1229 (if (not (eq major-mode mode))
1230 (funcall mode))
1231 ;; first insert the master file
1232 (if (not (file-exists-p master-file))
1233 (error "No such master file: %s" master-file))
1234 (reftex-insert-buffer-or-file master-file)
1235 (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
1236 (setq file-list (cons master-file file-list))
1237 (goto-char 1)
1238 ;; remember from which file these lines came
1239 (put-text-property (point-min) (point-max) 'file
1240 (expand-file-name master-file))
1241 ;; Now find recursively all include/input statements and expand them
1242 (while (re-search-forward
1243 "^[ \t]*\\\\\\(include\\|input\\){\\([^}\n]+\\)}" nil t)
1244 ;; Change default directory, so that relative fine names work correctly
1245 (setq file (reftex-no-props (match-string 2)))
1246 (save-match-data
1247 (cd (file-name-directory
1248 (get-text-property (match-beginning 0) 'file)))
1249 (if (not (string-match "\\.tex$" file))
1250 (setq file (concat file ".tex"))))
1251 (if (file-exists-p file)
1252 (progn
1253 (replace-match
1254 (format "\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% START OF %s FILE: %s\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% END OF %s FILE: %s\n"
1255 (match-string 1) file
1256 (match-string 1) file))
1257 (beginning-of-line 0)
1258 (narrow-to-region (point) (point))
1259 ;; insert the file
1260 (reftex-insert-buffer-or-file file)
1261 (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
1262 (setq file-list (cons (expand-file-name file) file-list))
1263 ;; remember from which file these lines came
1264 (put-text-property (point-min) (point-max)
1265 'file (expand-file-name file))
1266 (goto-char (point-min))
1267 (widen))
1268 (message "Input/include file %s not found. Ignored. Continuing..."
1269 file)
1270 (setq not-found (1+ not-found))))
1271 (setq file-list (nreverse file-list))
1272 (while (setq tmp (assoc (car file-list) reftex-master-include-list))
1273 (setq reftex-master-include-list (delq tmp reftex-master-include-list)))
1274 (setq reftex-master-include-list (cons file-list reftex-master-include-list))
1275 not-found))
1276
1277(defun reftex-insert-buffer-or-file (file)
1278 "If there is a buffer associated with FILE, insert it - otherwise the FILE."
1279 (let ((buffer (reftex-get-buffer-visiting file)))
1280 (if buffer
1281 (let (beg end beg1 end1)
1282 (save-excursion
1283 ;; make sure we get the whole buffer
1284 (set-buffer buffer)
1285 (setq beg (point-min) end (point-max))
1286 (widen)
1287 (setq beg1 (point-min) end1 (point-max)))
1288 (insert-buffer-substring buffer beg1 end1)
1289 (save-excursion
1290 (set-buffer buffer)
1291 (narrow-to-region beg end)))
1292 (insert-file-contents file))))
1293
1294
1295(defun reftex-parse-document (&optional buffer)
1296 "Rescan the document."
1297 (interactive)
1298 (save-window-excursion
1299 (save-excursion
1300 (if buffer
1301 (if (not (bufferp buffer))
1302 (error "No such buffer %s" (buffer-name buffer))
1303 (set-buffer buffer)))
1304 (reftex-access-scan-info t))))
1305
1306(defun reftex-access-scan-info (&optional rescan)
1307 ;; Access the scanning info. When the multifile symbols are not yet tied,
1308 ;; tie them. When they are have to be created, do a buffer scan to
1309 ;; fill them.
1310
1311 ;; If RESCAN is non-nil, enforce document scanning
1312
1313 (catch 'exit
1314 (let ((rescan (or (equal rescan t) (equal rescan '(4)))))
1315
1316 ;; Reset the mode if we had changes from style hooks
1317 (and reftex-tables-dirty
1318 (reftex-reset-mode))
1319
1320 (if (eq reftex-list-of-labels-symbol nil)
1321 ;; Symbols are not yet tied: Tie them and see if they are set
1322 (reftex-tie-multifile-symbols))
1323
1324 (if (and (symbol-value reftex-list-of-labels-symbol)
1325 (not rescan))
1326 ;; Lists do already exist and we don't need to rescan.
1327 ;; Return from here.
1328 (throw 'exit t))
1329
1330 ;; We need to rescan
1331 ;; =================
1332
1333 (unwind-protect
1334 (save-window-excursion
1335 (save-excursion
1336
1337 ;; do the scanning
1338
1339 (let ((label-list-symbol reftex-list-of-labels-symbol)
1340 (label-numbers-symbol reftex-label-numbers-symbol)
1341 (bibfile-list-symbol reftex-bibfile-list-symbol))
1342
1343 (message "Creating master buffer...")
1344 (reftex-make-master-buffer (reftex-TeX-master-file) major-mode)
1345
1346 (message "Scanning document...")
1347
1348 (reftex-scan-buffer-for-labels
1349 label-numbers-symbol label-list-symbol)
1350
1351 (reftex-scan-buffer-for-bibliography-statement
1352 bibfile-list-symbol)
1353
1354 (message "Scanning document... done"))))
1355
1356 (if (get-buffer "*reftex-master.tex*")
1357 (kill-buffer "*reftex-master.tex*"))))))
1358
1359(defun reftex-create-tags-file ()
1360 "Create TAGS file by running `etags' on the current document.
1361The TAGS file is also immediately visited with `visit-tags-table."
1362 (interactive)
1363 (reftex-access-scan-info current-prefix-arg)
1364 (let* ((master (reftex-TeX-master-file))
1365 (files (assoc master reftex-master-include-list))
1366 (cmd (format "etags %s" (mapconcat 'identity files " "))))
1367 (save-excursion
1368 (set-buffer (reftex-get-buffer-visiting master))
1369 (message "Running etags to create TAGS file...")
1370 (shell-command cmd)
1371 (visit-tags-table "TAGS"))))
1372
1373;; History of grep commands.
1374(defvar reftex-grep-history nil)
1375(defvar reftex-grep-command "grep -n "
1376 "Last grep command used in \\[reftex-grep-document]; default for next grep.")
1377
1378(defun reftex-grep-document (grep-cmd)
1379 "Run grep query through all files related to this document.
1380With prefix arg, force to rescan document.
1381This works also without an active TAGS table."
1382
1383 (interactive
1384 (list (read-from-minibuffer "Run grep on document (like this): "
1385 reftex-grep-command nil nil
1386 'reftex-grep-history)))
1387 (reftex-access-scan-info current-prefix-arg)
1388 (let* ((master (reftex-TeX-master-file))
1389 (default-directory (file-name-directory master))
1390 (re (format "\\`%s\\(.*\\)" (regexp-quote
1391 (expand-file-name default-directory))))
1392 (files (assoc master reftex-master-include-list))
1393 (cmd (format
1394 "%s %s" grep-cmd
1395 (mapconcat (function (lambda (x)
1396 (if (string-match re x)
1397 (match-string 1 x)
1398 x)))
1399 files " "))))
1400 (grep cmd)))
1401
1402(defun reftex-search-document (&optional regexp)
1403 "Regexp search through all files of the current TeX document.
1404Starts always in the master file. Stops when a match is found.
1405To continue searching for next match, use command \\[tags-loop-continue].
1406This works also without an active TAGS table."
1407 (interactive)
1408 (let ((default (reftex-this-word)))
1409 (if (not regexp)
1410 (setq regexp (read-string (format "Search regexp in document [%s]: "
1411 default))))
1412 (if (string= regexp "") (setq regexp (regexp-quote default)))
1413
1414 (reftex-access-scan-info current-prefix-arg)
1415 (tags-search regexp (list 'assoc (reftex-TeX-master-file)
1416 'reftex-master-include-list))))
1417
1418(defun reftex-query-replace-document (&optional from to delimited)
1419 "Run a query-replace-regexp of FROM with TO over the entire TeX document.
1420Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
1421If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1422with the command \\[tags-loop-continue].
1423This works also without an active TAGS table."
1424 (interactive)
1425 (let ((default (reftex-this-word)))
1426 (if (not from)
1427 (progn
1428 (setq from (read-string (format "Replace regexp in document [%s]: "
1429 default)))
1430 (if (string= from "") (setq from (regexp-quote default)))))
1431 (if (not to)
1432 (setq to (read-string (format "Replace regexp %s with: " from))))
1433 (reftex-access-scan-info current-prefix-arg)
1434 (tags-query-replace from to (or delimited current-prefix-arg)
1435 (list 'assoc (reftex-TeX-master-file)
1436 'reftex-master-include-list))))
1437
1438(defun reftex-change-label (&optional from to)
fba437e6 1439 "Query replace FROM with TO in all \\label and \\ref commands.
a7ec1775
RS
1440Works on the entire multifile document.
1441If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1442with the command \\[tags-loop-continue].
1443This works also without an active TAGS table."
1444 (interactive)
1445 (let ((default (reftex-this-word "-a-zA-Z0-9_*.:")))
1446 (if (not from)
1447 (setq from (read-string (format "Replace label globally [%s]: "
1448 default))))
1449 (if (string= from "") (setq from default))
1450 (if (not to)
1451 (setq to (read-string (format "Replace label %s with: "
1452 from))))
1453 (reftex-query-replace-document
1454 (concat "\\\\\\(label\\|[a-z]*ref\\){" (regexp-quote from) "}")
1455 (format "\\\\\\1{%s}" to))))
1456
1457(defun reftex-this-word (&optional class)
1458;; grab the word around point
1459 (setq class (or class "-a-zA-Z0-9:_/.*;|"))
1460 (save-excursion
1461 (buffer-substring-no-properties
1462 (progn (skip-chars-backward class) (point))
1463 (progn (skip-chars-forward class) (point)))))
1464
1465;;; ===========================================================================
1466;;;
1467;;; Functions to create and reference automatic labels
1468
1469;; The following constants are derived from reftex-label-alist
1470
1471;; Prompt used for label type querys directed to the user
1472(defconst reftex-type-query-prompt nil)
1473
1474;; Help string for label type querys
1475(defconst reftex-type-query-help nil)
1476
1477;; Alist relating label type to reference format
1478(defconst reftex-typekey-to-format-alist nil)
1479
1480;; Alist relating label type to label affix
1481(defconst reftex-typekey-to-prefix-alist nil)
1482
1483;; Alist relating environments or macros to label type and context regexp
1484(defconst reftex-env-or-mac-alist nil)
1485
1486;; List of macros carrying a label
1487(defconst reftex-label-mac-list nil)
1488
1489;; List of environments carrying a label
1490(defconst reftex-label-env-list nil)
1491
1492;; List of all typekey letters in use
1493(defconst reftex-typekey-list nil)
1494
1495;; Alist relating magic words to a label type
1496(defconst reftex-words-to-typekey-alist nil)
1497
1498;; The last list-of-labels entry used in a reference
1499(defvar reftex-last-used-reference (list nil nil nil nil))
1500
1501;; The regular expression used to abbreviate words
1502(defconst reftex-abbrev-regexp
1503 (concat
1504 "^\\("
1505 (make-string (nth 0 reftex-abbrev-parameters) ?.)
1506 "[" (nth 2 reftex-abbrev-parameters) "]*"
1507 "\\)"
1508 "[" (nth 3 reftex-abbrev-parameters) "]"
1509 (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
1510
1511;; Global variables used for communication between functions
1512(defvar reftex-default-context-position nil)
1513(defvar reftex-location-start nil)
1514(defvar reftex-call-back-to-this-buffer nil)
1515
1516;; List of buffers created temporarily for lookup, which should be killed
1517(defvar reftex-buffers-to-kill nil)
1518
1519;; The regexp used to find section statements
1520(defconst reftex-section-regexp "^[ ]*\\\\\\(part\\|chapter\\|section\\|subsection\\|subsubsection\\|paragraph\\|subparagraph\\|subsubparagraph\\)\\*?\\(\\[[^]]*\\]\\)?{")
1521
1522;; LaTeX section commands and level numbers
1523(defconst reftex-section-levels
1524 '(
1525 ("part" . 0)
1526 ("chapter" . 1)
1527 ("section" . 2)
1528 ("subsection" . 3)
1529 ("subsubsection" . 4)
1530 ("paragraph" . 5)
1531 ("subparagraph" . 6)
1532 ("subsubparagraph" . 7)
1533 ))
1534
1535(defun reftex-label (&optional environment no-insert)
1536 "Insert a unique label. Return the label.
1537If ENVIRONMENT is given, don't bother to find out yourself.
1538If NO-INSERT is non-nil, do not insert label into buffer.
1539With prefix arg, force to rescan document first.
1540The label is also inserted into the label list.
1541This function is controlled by the settings of reftex-insert-label-flags."
1542
1543 (interactive)
1544
1545 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
1546 (reftex-access-scan-info current-prefix-arg)
1547
1548 ;; Find out what kind of environment this is and abort if necessary
1549 (if (or (not environment)
1550 (not (assoc environment reftex-env-or-mac-alist)))
1551 (setq environment (reftex-label-location)))
1552 (if (not environment)
1553 (error "Can't figure out what kind of label should be inserted"))
1554
1555 ;; Ok, go ahead
1556 (let (label num typekey prefix entry cell lab valid default force-prompt)
1557 (setq typekey (nth 1 (assoc environment
1558 reftex-env-or-mac-alist)))
1559 (setq prefix (or (cdr (assoc typekey reftex-typekey-to-prefix-alist))
1560 (concat typekey "-")))
1561
1562 ;; make a default label
1563 (cond
1564
1565 ((reftex-typekey-check typekey (nth 0 reftex-insert-label-flags))
1566 ;; derive a label from context
1567 (setq default (nth 2 (reftex-label-info " ")))
1568 ;; catch the cases where the is actually no context available
1569 (if (or (string-match "NO MATCH FOR CONTEXT REGEXP" default)
1570 (string-match "ILLEGAL VALUE OF PARSE" default)
1571 (string-match "SECTION HEADING NOT FOUND" default)
1572 (string-match "HOOK ERROR" default)
1573 (string-match "^[ \t]*$" default))
1574 (setq default prefix
1575 force-prompt t) ; need to prompt
1576 (setq default (concat prefix (reftex-string-to-label default)))
1577
1578 ;; make it unique
1579 (setq label default)
1580 (setq num 1)
1581 (while (assoc label (symbol-value reftex-list-of-labels-symbol))
1582 (setq label (concat default "-" (setq num (1+ num)))))
1583 (setq default label)))
1584
1585 ((reftex-typekey-check typekey (nth 1 reftex-insert-label-flags)) ; prompt
1586 ;; Minimal default: the user will be prompted
1587 (setq default prefix))
1588
1589 (t
1590 ;; make an automatic label
1591 (while (assoc
1592 (setq default (concat prefix (reftex-next-label-number typekey)))
1593 (symbol-value reftex-list-of-labels-symbol)))))
1594
1595 ;; Should we ask the user?
1596 (if (or (reftex-typekey-check typekey
1597 (nth 1 reftex-insert-label-flags)) ; prompt
1598 force-prompt)
1599
1600 (while (not valid)
1601 ;; iterate until we get a legal label
1602
1603 (setq label (read-string "Label: " default))
1604
1605 ;; Lets make sure that this is a legal label
1606 (cond
1607
1608 ;; Test if label contains strange characters
1609 ((string-match reftex-label-illegal-re label)
1610 (message "Label \"%s\" contains illegal characters" label)
1611 (ding)
1612 (sit-for 2))
1613
1614 ;; Look it up in the label list
1615 ((setq entry (assoc label
1616 (symbol-value reftex-list-of-labels-symbol)))
1617 (message "Label \"%s\" exists in file %s" label (nth 3 entry))
1618 (ding)
1619 (sit-for 2))
1620
1621 ;; Label is ok
1622 (t
1623 (setq valid t))))
1624 (setq label default))
1625
1626 ;; Insert the label
1627 (if (not no-insert)
1628 (insert "\\label{" label "}"))
1629
1630 ;; Insert the label into the label list
1631 (if (symbol-value reftex-list-of-labels-symbol)
1632 (let ((cnt 0)
1633 (pos (point))
1634 (all (symbol-value reftex-list-of-labels-symbol))
1635 (look-for nil)
1636 (note nil)
1637 (text nil)
1638 (file (buffer-file-name)))
1639
1640 ;; find the previous label in order to know where to insert new label
1641 ;; into label list
1642 (save-excursion
1643 (if (re-search-backward "\\\\label{\\([^}]+\\)}" nil 1 2)
1644 (setq look-for (reftex-no-props (match-string 1))))
1645 (if (or (re-search-forward
1646 "\\\\\\(include\\|input\\){[^}\n]+}" pos t)
1647 (re-search-forward reftex-section-regexp pos t)
1648 (null look-for))
1649 (setq note "POSITION UNCERTAIN. RESCAN TO FIX.")))
1650 (if (not look-for)
1651 (set reftex-list-of-labels-symbol
1652 (cons (list label typekey text file note)
1653 (symbol-value reftex-list-of-labels-symbol)))
1654 (while all
1655 (setq cell (car all)
1656 all (cdr all)
1657 cnt (1+ cnt)
1658 lab (nth 0 cell))
1659 (if (string= lab look-for)
1660 (progn
1661 (setcdr
1662 (nthcdr (1- cnt)
1663 (symbol-value reftex-list-of-labels-symbol))
1664 (cons (list label typekey text file note)
1665 (nthcdr
1666 cnt (symbol-value reftex-list-of-labels-symbol))))
1667 ;; to end the loop, set all to nil
1668 (setq all nil)))))))
1669 ;; return value of the function is the label
1670 label))
1671
1672(defun reftex-string-to-label (string)
1673 ;; Convert a string (a sentence) to a label.
1674 ;;
1675 ;; Uses reftex-derive-label-parameters and reftex-abbrev-parameters
1676 ;;
1677
1678 (let* ((words0 (reftex-split "[- \t\n\r]+"
1679 (reftex-no-props string)))
1680 (ignore-words (nth 5 reftex-derive-label-parameters))
1681 words word)
1682
1683 ;; remove words from the ignore list or with funny characters
1684 (while words0
1685 (setq word (car words0) words0 (cdr words0))
1686 (cond
1687 ((member (downcase word) ignore-words))
1688 ((string-match reftex-label-illegal-re word)
1689 (if (nth 2 reftex-derive-label-parameters)
1690 (progn
1691 (while (string-match reftex-label-illegal-re word)
1692 (setq word (replace-match "" nil nil word)))
1693 (setq words (cons word words)))))
1694 (t
1695 (setq words (cons word words)))))
1696 (setq words (nreverse words))
1697
1698 ;; restrict number of words
1699 (if (> (length words) (nth 0 reftex-derive-label-parameters))
1700 (setcdr (nthcdr (1- (nth 0 reftex-derive-label-parameters)) words) nil))
1701
1702 ;; First, try to use all words
1703 (setq string (mapconcat '(lambda(w) w) words
1704 (nth 4 reftex-derive-label-parameters)))
1705
1706 ;; Abbreviate words if enforced by user settings or string length
1707 (if (or (eq t (nth 3 reftex-derive-label-parameters))
1708 (and (nth 3 reftex-derive-label-parameters)
1709 (> (length string) (nth 1 reftex-derive-label-parameters))))
1710 (setq words
1711 (mapcar
1712 '(lambda (w) (if (string-match reftex-abbrev-regexp w)
1713 (match-string 1 w)
1714 w))
1715 words)
1716 string (mapconcat '(lambda(w) w) words
1717 (nth 4 reftex-derive-label-parameters))))
1718
1719 ;; Shorten if still to long
1720 (setq string
1721 (if (> (length string) (nth 1 reftex-derive-label-parameters))
1722 (substring string 0 (nth 1 reftex-derive-label-parameters))
1723 string))
1724
1725 ;; Delete the final punctuation, if any
1726 (if (string-match "[^a-zA-Z0-9]+$" string)
1727 (setq string (replace-match "" nil nil string)))
1728 string))
1729
1730(defun reftex-label-location (&optional bound)
1731 ;; Return the environment or macro which determines the label type at point.
1732 ;; If optional BOUND is an integer, limit backward searches to that point.
1733
1734 (let* ((loc1 (reftex-what-macro reftex-label-mac-list bound))
1735 (loc2 (reftex-what-environment reftex-label-env-list bound))
1736 (p1 (or (cdr loc1) 0))
1737 (p2 (or (cdr loc2) 0)))
1738
1739 (setq reftex-location-start (max p1 p2))
1740 (if (> p1 p2)
1741 (progn
1742 (setq reftex-default-context-position p1)
1743 (car loc1))
1744 (setq reftex-default-context-position
1745 (+ p2 8 (length (car loc2))))
1746 (or (car loc2) "section"))))
1747
1748
1749(defun reftex-next-label-number (type)
1750 ;; Increment value of automatic labels in current buffer. Return new value.
1751
1752 ;; Ensure access to scanning info
1753 (reftex-access-scan-info)
1754
1755 (let ((n (cdr (assoc type (symbol-value reftex-label-numbers-symbol)))))
1756 (if (not (integerp n))
1757 ;; oops - type not known - make one here
1758 (progn
1759 (set reftex-label-numbers-symbol
1760 (cons (cons type 0)
1761 (symbol-value reftex-label-numbers-symbol)))
1762 (setq n 0)))
1763 (setq n (1+ n))
1764 (setcdr (assoc type (symbol-value reftex-label-numbers-symbol)) n)
1765 n))
1766
1767;; Help string for the reference label menu
1768(defconst reftex-reference-label-help
1769 " AVAILABLE KEYS IN REFERENCE LABEL MENU
1770 ======================================
1771 n / p Go to next/previous label (Cursor motion works as well)
1772 r / s Rescan document for labels / Switch label type
1773 t / # Toggle table of contents / Toggle counter mode
1774 c Toggle display of short context
1775 SPACE Show full context for current label in other window
1776 f Toggle follow mode: other window will follow context
1777 a / q Use last referenced label / Quit without accepting label
1778 ? / C-r Display this help message / Recursive Edit into other window
1779 RETURN Accept current label")
1780
1781(defun reftex-reference (&optional type no-insert)
1782 "Make a LaTeX reference. Look only for labels of a certain TYPE.
1783With prefix arg, force to rescan buffer for labels. This should only be
1784necessary if you have recently entered labels yourself without using
1785reftex-label. Rescanning of the buffer can also be requested from the
1786label selection menu.
1787The function returns the selected label or nil.
fba437e6 1788If NO-INSERT is non-nil, do not insert \\ref command, just return label.
a7ec1775
RS
1789When called with 2 C-u prefix args, disable magic word recognition."
1790
1791 (interactive)
1792
1793 ;; check for active recursive edits
1794 (reftex-check-recursive-edit)
1795
1796 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
1797 (reftex-access-scan-info current-prefix-arg)
1798
1799 (if (not type)
1800 ;; guess type from context
1801 (if (and reftex-guess-label-type
1802 (not (= 16 (prefix-numeric-value current-prefix-arg)))
1803 (setq type (assoc (downcase (reftex-word-before-point))
1804 reftex-words-to-typekey-alist)))
1805 (setq type (cdr type))
1806 (setq type (reftex-query-label-type))))
1807
1808 (let (label pair
1809 (form (or (cdr (assoc type reftex-typekey-to-format-alist))
1810 "\\ref{%s}")))
1811
1812 ;; Have the user select a label
1813 (setq pair (reftex-offer-label-menu type))
1814 (setq label (car pair))
1815
1816 (if (and label
1817 (not no-insert))
1818 (progn
1819 ;; do we need to remove spaces?
1820 (if (string= "~" (substring form 0 1))
1821 (while (or (= (preceding-char) ?\ )
1822 (= (preceding-char) ?\C-i))
1823 (backward-delete-char 1)))
1824 ;; ok, insert the reference
1825 (insert (format form label label))
1826 (message ""))
1827 (message "Quit"))
1828 ;; return the label
1829 label))
1830
1831(defun reftex-goto-label (&optional arg)
1832 "Go to a LaTeX label. With prefix ARG: go to label in another window."
1833 (interactive "P")
1834 (let (type label file pair)
1835 (if (not type)
1836 (setq type (reftex-query-label-type)))
1837
1838 (setq pair (reftex-offer-label-menu type)
1839 label (car pair)
1840 file (cdr pair))
1841 (if (and label file (file-exists-p file))
1842 (progn
1843 (if arg
1844 (find-file-other-window file)
1845 (find-file file))
1846 (goto-char (point-min))
1847 (if (not (search-forward (concat "\\label{" label "}") nil t))
1848 (error "No such label found: %s" label)
1849 (reftex-highlight 0 (match-beginning 0) (match-end 0))
1850 (add-hook 'pre-command-hook 'reftex-highlight-shall-die)))
1851 (message "Quit")
1852 nil)))
1853
1854;; Internal list with index numbers of labels in the selection menu
1855(defvar reftex-label-index-list nil)
1856
1857(defun reftex-offer-label-menu (typekey)
1858 ;; Offer a menu with the appropriate labels. Return (label . file).
1859 (let* ((buf (current-buffer))
1860 (near-label (reftex-find-nearby-label))
1861 (toc (reftex-typekey-check typekey reftex-label-menu-flags 0))
1862 (context (not (reftex-typekey-check
1863 typekey reftex-label-menu-flags 3)))
1864 (counter (reftex-typekey-check
1865 typekey reftex-label-menu-flags 2))
1866 (follow (reftex-typekey-check
1867 typekey reftex-label-menu-flags 4))
1868 offset rtn key cnt entry)
1869
1870 (setq reftex-call-back-to-this-buffer buf)
1871 (setq entry (cons nil nil))
1872
1873 (unwind-protect
1874 (catch 'exit
1875 (while t
1876 (save-window-excursion
1877 (switch-to-buffer-other-window "*RefTeX Select*")
1878 (erase-buffer)
1879 (setq truncate-lines t)
1880 (setq reftex-label-index-list (reftex-make-and-insert-label-list
1881 typekey buf toc context counter
1882 near-label))
1883 (setq near-label "_ ") ; turn off search for near label
1884 (setq offset (or (car reftex-label-index-list) offset))
1885 ;; use only when searched
1886 (setq reftex-label-index-list (cdr reftex-label-index-list))
1887 ;; only this is the true list
1888 (if (not reftex-label-index-list)
1889 (error "No labels of type \"%s\"" typekey))
1890 (setq rtn
1891 (reftex-select-item
1892 nil
1893 "Label: [n]ext [p]rev [r]escan [t]oc [ ]context [q]uit RETURN [?]HELP+more"
1894 "^>"
1895 "\n[^.]"
1896 2
1897 reftex-reference-label-help
1898 '(?r ?c ?t ?s ?# ?a)
1899 offset
1900 'reftex-select-label-callback follow))
1901 (setq key (car rtn)
1902 cnt (cdr rtn)
1903 offset (1+ cnt))
1904 (if (not key) (throw 'exit nil))
1905 (cond
1906 ((equal key ?r)
1907 ;; rescan buffer
1908 (reftex-parse-document buf))
1909 ((equal key ?c)
1910 ;; toggle context mode
1911 (setq context (not context)))
1912 ((equal key ?s)
1913 ;; switch type
1914 (setq typekey (reftex-query-label-type)))
1915 ((equal key ?t)
1916 ;; toggle tabel of contents display
1917 (setq toc (not toc)))
1918 ((equal key ?#)
1919 ;; toggle counter display
1920 (setq counter (not counter)))
1921 ((equal key ?a)
1922 ;; reuse the last referenced label again
1923 (setq entry reftex-last-used-reference)
1924 (throw 'exit t))
1925 (t
1926 (set-buffer buf)
1927 (setq entry (nth (nth cnt reftex-label-index-list)
1928 (symbol-value reftex-list-of-labels-symbol)))
1929 (setq reftex-last-used-reference entry)
1930 (throw 'exit t))))))
1931 (kill-buffer "*RefTeX Select*")
1932 (reftex-kill-temporary-buffers))
1933 (cons (reftex-no-props (nth 0 entry)) (nth 3 entry))))
1934
1935;; Indentation for table of context lines in the menu
1936(defconst reftex-toc-indent " ")
1937;; Indentation for the lines containing the label
1938(defconst reftex-label-indent "> ")
1939;; Indentation for context lines
1940(defconst reftex-context-indent ". ")
1941;; Indentation per section level
1942(defvar reftex-level-indent 2
1943 "*Number of spaces to be used for indentation per section level.
1944With more indentation, the label menu looks nicer, but shows less context.
1945Changing this is only fully operational after the next buffer scan.")
1946
1947(defun reftex-make-and-insert-label-list (typekey0 buf toc context
1948 counter near-label)
1949 ;; Insert a menu of all labels in buffer BUF into current buffer.
1950 ;; Return the list of labels, with the index of NEAR-LABEL as extra car.
1951 (let (ins-list index-list offset)
1952 (save-excursion
1953 (set-buffer buf)
1954 (let* ((all nil)
1955 (font (reftex-use-fonts))
1956 (cnt 0)
1957 (file nil)
1958 (index -1)
1959 (toc-indent reftex-toc-indent)
1960 (label-indent
1961 (concat reftex-label-indent
1962 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
1963 (context-indent
1964 (concat reftex-context-indent
1965 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
1966 cell text label typekey note comment)
1967
1968 ; Ensure access to scanning info
1969 (reftex-access-scan-info)
1970
1971 (setq all (symbol-value reftex-list-of-labels-symbol))
1972
1973 (while all
1974
1975 (setq index (1+ index)
1976 cell (car all)
1977 all (cdr all))
1978
1979 (if (null (nth 2 cell))
1980 ;; No context yet. Quick update
1981 (progn
1982 (setq cell (reftex-label-info-update cell))
1983 (setcar (nthcdr index
1984 (symbol-value reftex-list-of-labels-symbol))
1985 cell)))
1986
1987 ;; in the following setq we *copy* the label, since we will change
1988 ;; its properties, and we cannot have any properties in the list
1989 ;; (because of assoc searches)
1990 (setq label (copy-sequence (nth 0 cell))
1991 typekey (nth 1 cell)
1992 text (nth 2 cell)
1993 file (nth 3 cell)
1994 note (nth 4 cell)
1995 comment (get-text-property 0 'in-comment text))
1996
1997 (if (string= label near-label)
1998 (setq offset (1+ cnt)))
1999
2000 (cond
2001 ((and toc (string= typekey "toc"))
2002 (setq ins-list
2003 (cons (concat toc-indent text "\n")
2004 ins-list)))
2005 ((string= typekey "toc"))
2006 ((and (or (string= typekey typekey0) (string= typekey0 " "))
2007 (or (nth 5 reftex-label-menu-flags) ; show-commented?
2008 (null comment)))
2009 (setq cnt (1+ cnt))
2010 (if comment (setq label (concat "% " label)))
2011 (if font
2012 (put-text-property
2013 0 (length label)
2014 'face
2015 (if comment
2016 'font-lock-comment-face
2017 'font-lock-reference-face)
2018 label))
2019 (setq index-list (cons index index-list))
2020 (setq ins-list
2021 (cons (concat
2022 label-indent
2023 label
2024 (if counter (format " (%d) " cnt))
2025 (if comment " LABEL IS COMMENTED OUT ")
2026 (if note (concat " " note) "")
2027 "\n"
2028 (if context (concat context-indent text "\n")))
2029 ins-list))))
2030 )))
2031
2032 (apply 'insert (nreverse ins-list))
2033 (cons offset (nreverse index-list))))
2034
2035(defun reftex-query-label-type ()
2036 ;; Ask for label type
2037 (message reftex-type-query-prompt)
2038 (let ((key (read-char)))
2039 (if (equal key ?\?)
2040 (progn
2041 (save-window-excursion
2042 (with-output-to-temp-buffer "*RefTeX Help*"
2043 (princ reftex-type-query-help))
2044 (setq key (read-char))
2045 (kill-buffer "*RefTeX Help*"))))
2046 (if (not (member (char-to-string key) reftex-typekey-list))
2047 (error "No such label type: %s" (char-to-string key)))
2048 (char-to-string key)))
2049
2050(defun reftex-find-nearby-label ()
2051 ;; Find a nearby label.
2052 (save-excursion
2053 (if (or (re-search-backward "\\\\label{\\([^}]+\\)}" nil t)
2054 (re-search-forward "\\\\label{\\([^}]+\\)}" nil t))
2055 (reftex-no-props (match-string 1))
2056 nil)))
2057
2058;; Variable holding the vector with section numbers
2059(defvar reftex-section-numbers [0 0 0 0 0 0 0 0])
2060
2061(defun reftex-scan-buffer-for-labels (label-numbers-symbol label-list-symbol)
2062 ;; Scan the buffer for labels and save them in a list.
2063 (save-excursion
2064 (let ((regexp (concat "\\\\label{\\([^}]*\\)}" "\\|"
2065 reftex-section-regexp))
2066 (font (reftex-use-fonts))
2067 (bound 0)
2068 (highest-level 100)
2069 file (level 1) start star text text1 label section-number macro find)
2070 (set label-list-symbol nil)
2071 (goto-char 0)
2072
2073 ;; reset label numbers
2074 (set label-numbers-symbol
2075 (mapcar '(lambda(x) (cons x 0)) reftex-typekey-list))
2076
2077 ;; reset section numbers
2078 (reftex-section-number reftex-section-numbers -1)
2079
2080 (while (re-search-forward regexp nil t)
2081 (setq file (get-text-property (match-beginning 0) 'file))
2082 (if (string= (buffer-substring (match-beginning 0)
2083 (+ 7 (match-beginning 0))) "\\label{")
2084 ;; It is a label
2085 (progn
2086 (setq label (reftex-no-props (match-string 1)))
2087 (set label-list-symbol
2088 (cons (reftex-label-info label file bound)
2089 (symbol-value label-list-symbol))))
2090
2091 ;; It is a section
2092 (setq bound (point))
2093 (setq star (= ?* (char-after (match-end 2))))
2094 (setq find (buffer-substring-no-properties
2095 (1- (match-beginning 2)) (match-end 0)))
2096 (setq macro (reftex-no-props (match-string 2)))
2097 (setq level (cdr (assoc macro reftex-section-levels)))
2098
2099 (setq section-number (reftex-section-number
2100 reftex-section-numbers level star))
2101 (setq highest-level (min highest-level level))
2102 (if (= level highest-level)
2103 (message
2104 "Scanning %s %s ..."
2105 (car (nth level reftex-section-levels))
2106 section-number))
2107
2108 ;; get the title
2109 (save-match-data
2110 (setq text1 (reftex-context-substring))
2111 (setq text (reftex-nicify-text text1)))
2112
2113 (setq find (reftex-allow-for-ctrl-m (concat find text1)))
2114
2115 ;; add section number and indentation
2116 (setq text
2117 (concat
2118 (make-string (* reftex-level-indent level) ?\ )
2119 (if (nth 1 reftex-label-menu-flags) ; section number flag
2120 (concat section-number " "))
2121 text))
2122 ;; fontify
2123 (if font (put-text-property 0 (length text)
2124 'face 'font-lock-comment-face text))
2125
2126 ;; insert in list
2127 (set label-list-symbol
2128 (cons (list nil "toc" text file find)
2129 (symbol-value label-list-symbol)))))
2130 (set label-list-symbol
2131 (nreverse (symbol-value label-list-symbol))))))
2132
2133
2134(defun reftex-label-info-update (cell)
2135 ;; Update information about just one label in a different file.
2136 ;; CELL contains the old info list
2137 (let* ((label (nth 0 cell))
2138 (typekey (nth 1 cell))
2139 (text (nth 2 cell))
2140 (file (nth 3 cell))
2141 (note (nth 4 cell))
2142 (buf (reftex-get-file-buffer-force
2143 file (not reftex-keep-temporary-buffers))))
2144 (if (not buf)
2145 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")
2146 (save-excursion
2147 (set-buffer buf)
2148 (save-restriction
2149 (widen)
2150 (goto-char 1)
2151
2152 (if (re-search-forward (concat "\\\\label{" (regexp-quote label) "}")
2153 nil t)
2154 (append (reftex-label-info label file) (list note))
2155 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")))))))
2156
2157(defun reftex-label-info (label &optional file bound)
2158 ;; Return info list on LABEL at point.
2159 (let* ((env-or-mac (reftex-label-location bound))
2160 (typekey (nth 1 (assoc env-or-mac reftex-env-or-mac-alist)))
2161 (file (or file (buffer-file-name)))
2162 (parse (if (reftex-typekey-check
2163 typekey reftex-use-text-after-label-as-context)
2164 nil
2165 (nth 2 (assoc env-or-mac reftex-env-or-mac-alist))))
2166 (text (reftex-short-context env-or-mac parse reftex-location-start)))
2167 (if (reftex-in-comment)
2168 (put-text-property 0 1 'in-comment t text))
2169 (list label typekey text file)))
2170
2171(defun reftex-in-comment ()
2172 (save-excursion
2173 (skip-chars-backward "^%\n\r")
2174 (= (preceding-char) ?%)))
2175
2176(defun reftex-short-context (env parse &optional bound)
2177 ;; Get about one line of useful context for the label definition at point.
2178
2179 (reftex-nicify-text
2180
2181 (cond
2182
2183 ((null parse)
2184 (save-excursion
2185 (reftex-context-substring)))
2186
2187 ((eq parse t)
2188 (if (string= env "section")
2189 ;; special treatment for section labels
2190 (save-excursion
2191 (if (re-search-backward reftex-section-regexp (point-min) t)
2192 (progn
2193 (goto-char (match-end 0))
2194 (reftex-context-substring))
2195 "SECTION HEADING NOT FOUND"))
2196 (save-excursion
2197 (goto-char reftex-default-context-position)
2198 (reftex-context-substring))))
2199
2200 ((stringp parse)
2201 (save-excursion
2202 (if (re-search-backward parse bound t)
2203 (progn
2204 (goto-char (match-end 0))
2205 (reftex-context-substring))
2206 "NO MATCH FOR CONTEXT REGEXP")))
2207 ((fboundp parse)
2208 ;; A hook function. Call it.
2209 (save-excursion
2210 (condition-case error-var
2211 (funcall parse env)
2212 ('error (format "HOOK ERROR: %s" (cdr error-var))))))
2213 (t
2214 "ILLEGAL VALUE OF PARSE"))))
2215
2216(defun reftex-context-substring ()
2217 ;; Return up to 100 chars from point
2218 ;; When point is just after a { or [, limit string to matching parenthesis
2219 (cond
2220 ((or (= (preceding-char) ?\{)
2221 (= (preceding-char) ?\[))
2222 ;; inside a list - get only the list, with modified syntax to be perfect
2223 (buffer-substring
2224 (point)
2225 (min (+ 100 (point))
2226 (point-max)
2227 (condition-case nil
2228 (progn
2229 (up-list 1)
2230 (1- (point)))
2231 ('error (point-max))))))
2232 (t
2233 ;; no list - just grab 100 characters
2234 (buffer-substring (point) (min (+ 100 (point)) (point-max))))))
2235
2236(defun reftex-section-number (section-numbers &optional level star)
2237 ;; Return a string with the current section number.
2238 ;; When LEVEL is non-nil, increase section numbers on that level.
2239 (let* ((depth 6) idx n (string ""))
2240 (if level
2241 (progn
2242 (if (and (> level -1) (not star))
2243 (aset section-numbers level (1+ (aref section-numbers level))))
2244 (setq idx (1+ level))
2245 (while (<= idx depth)
2246 (aset section-numbers idx 0)
2247 (setq idx (1+ idx)))))
2248 (setq idx 0)
2249 (while (<= idx depth)
2250 (setq n (aref section-numbers idx))
2251 (setq string (concat string (if (not (string= string "")) "." "")
2252 (int-to-string n)))
2253 (setq idx (1+ idx)))
2254 (save-match-data
2255 (if (string-match "\\`\\(0\\.\\)+" string)
2256 (setq string (replace-match "" nil nil string)))
2257 (if (string-match "\\(\\.0\\)+\\'" string)
2258 (setq string (replace-match "" nil nil string))))
2259 (if star
2260 (concat (make-string (1- (length string)) ?\ ) "*")
2261 string)))
2262
2263;; A variable to remember the index of the last label context shown
2264(defvar reftex-last-cnt 0)
2265
2266(defun reftex-select-label-callback (cnt)
2267 ;; Callback function called from the label selection in order to
2268 ;; show context in another window
2269 (let* ((this-window (selected-window))
2270 index entry label file buffer)
2271 ;; pop to original buffer in order to get correct variables
2272 (catch 'exit
2273 (save-excursion
2274 (set-buffer reftex-call-back-to-this-buffer)
2275 (setq index (nth (or cnt 1) reftex-label-index-list)
2276 entry (nth index (symbol-value reftex-list-of-labels-symbol))
2277 label (nth 0 entry)
2278 file (nth 3 entry)))
2279
2280 ;; goto the file in another window
2281 (setq buffer (reftex-get-file-buffer-force
2282 file (not reftex-keep-temporary-buffers)))
2283 (if buffer
2284 ;; good - the file is available
2285 (switch-to-buffer-other-window buffer)
2286 ;; we have got a problem here. The file does not exist.
2287 ;; Let' get out of here..
2288 (ding)
2289 (throw 'exit nil))
2290
2291
2292 ;; search for that label
2293 (if (not (and (integerp cnt)
2294 (integerp reftex-last-cnt)
2295 (if (> cnt reftex-last-cnt)
2296 (search-forward (concat "\\label{" label "}") nil t)
2297 (search-backward (concat "\\label{" label "}") nil t))))
2298 (progn
2299 (goto-char 1)
2300 (search-forward (concat "\\label{" label "}") nil t)))
2301 (reftex-highlight 0 (match-beginning 0) (match-end 0))
2302 (reftex-show-entry)
2303 (recenter (/ (window-height) 2))
2304 (select-window this-window))))
2305
2306(defun reftex-pop-to-label (label file-list &optional mark-to-kill highlight)
2307 ;; Find LABEL in any file in FILE-LIST in another window.
2308 ;; If mark-to-kill is non-nil, mark new buffer for killing.
2309 ;; If HIGHLIGHT is non-nil, highlight the label definition.
2310 (let* ((re (concat "\\\\label{" (regexp-quote label) "}"))
2311 file buf)
2312 (catch 'exit
2313 (while file-list
2314 (setq file (car file-list)
2315 file-list (cdr file-list))
2316 (if (not (setq buf (reftex-get-file-buffer-force file mark-to-kill)))
2317 (error "No such file %s" file))
2318 (set-buffer buf)
2319 (widen)
2320 (goto-char (point-min))
2321 (if (re-search-forward re nil t)
2322 (progn
2323 (switch-to-buffer-other-window buf)
2324 (goto-char (match-beginning 0))
2325 (recenter (/ (window-height) 2))
2326 (if highlight
2327 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
2328 (throw 'exit (selected-window)))))
2329 (error "Label %s not found" label))))
2330
2331(defun reftex-find-duplicate-labels ()
2332 "Produce a list of all duplicate labels in the document."
2333
2334 (interactive)
2335
2336 ;; Rescan the document to make sure
2337 (reftex-access-scan-info t)
2338
2339 (let ((master (reftex-TeX-master-file))
2340 (dlist
2341 (mapcar
2342 '(lambda(x)
2343 (let (x1)
2344 (cond
2345 ((car x)
2346 (setq x1 (reftex-all-assoc-string
2347 (car x) (symbol-value reftex-list-of-labels-symbol)))
2348 (if (< 1 (length x1))
2349 (append (list (reftex-no-props (car x)))
2350 (mapcar '(lambda(x)
2351 (abbreviate-file-name (nth 3 x))) x1))
2352 (list nil)))
2353 (t nil))))
2354 (reftex-uniquify (symbol-value reftex-list-of-labels-symbol)))))
2355 (setq dlist (reftex-uniquify dlist))
2356 (if (null dlist) (error "No duplicate labels in document"))
2357 (switch-to-buffer-other-window "*Help*")
2358 (make-local-variable 'TeX-master)
2359 (setq TeX-master master)
2360 (erase-buffer)
2361 (insert " MULTIPLE LABELS IN CURRENT DOCUMENT:\n")
2362 (insert " Move point to label and type `M-x reftex-change-label'\n"
2363 " This will run a query-replace on the label and its references\n")
2364 (insert " LABEL FILE\n")
2365 (insert " -------------------------------------------------------------\n")
2366 (while dlist
2367 (if (and (car (car dlist))
2368 (cdr (car dlist)))
2369 (progn
2370 (insert (mapconcat '(lambda(x) x) (car dlist) "\n ") "\n")))
2371 (setq dlist (cdr dlist)))
2372 (goto-char (point-min))))
2373
2374(defun reftex-all-assoc-string (key list)
2375 ;; Return a list of all associations of KEY in LIST. Comparison with string=
2376 (let (rtn)
2377 (while list
2378 (if (string= (car (car list)) key)
2379 (setq rtn (cons (car list) rtn)))
2380 (setq list (cdr list)))
2381 (nreverse rtn)))
2382
2383(defun reftex-kill-temporary-buffers ()
2384 ;; Kill all buffers in the list reftex-kill-temporary-buffers.
2385 (while reftex-buffers-to-kill
2386 (if (bufferp (car reftex-buffers-to-kill))
2387 (progn
2388 (and (buffer-modified-p (car reftex-buffers-to-kill))
2389 (y-or-n-p (format "Save file %s? "
2390 (buffer-file-name
2391 (car reftex-buffers-to-kill))))
2392 (save-excursion
2393 (set-buffer (car reftex-buffers-to-kill))
2394 (save-buffer)))
2395 (kill-buffer (car reftex-buffers-to-kill))))
2396 (setq reftex-buffers-to-kill (cdr reftex-buffers-to-kill))))
2397
2398(defun reftex-show-entry ()
2399 ;; Show entry if point is hidden by outline mode
2400 (let ((pos (point)))
2401 (if (and reftex-auto-show-entry
2402 (boundp 'outline-minor-mode)
2403 outline-minor-mode
2404 (looking-at "[^\n\r]*\r"))
2405 (progn
2406 (outline-back-to-heading)
2407 (show-entry)
2408 (goto-char pos)))))
2409
2410
2411(defun reftex-nicify-text (text)
2412 ;; Make TEXT nice for inclusion into label menu
2413 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text) ; remove extra whitespace
2414 (setq text (replace-match " " nil t text)))
2415 (if (string-match "\\\\end{.*" text) ; nothing beyond \end{
2416 (setq text (replace-match "" nil t text)))
2417 (if (string-match "\\\\label{[^}]*}" text) ; kill the label
2418 (setq text (replace-match "" nil t text)))
2419 (if (string-match "^ +" text) ; leading whitespace
2420 (setq text (replace-match "" nil t text)))
2421 (cond
2422 ((> (length text) 100) ; not to long
2423 (setq text (substring text 0 100)))
2424 ((= (length text) 0) ; not empty
2425 (setq text " ")))
2426 text)
2427
2428(defun reftex-typekey-check (typekey conf-variable &optional n)
2429 ;; Check if CONF-VARIABLE is true or contains TYPEKEY
2430 (and n (setq conf-variable (nth n conf-variable)))
2431 (or (equal conf-variable t)
2432 (and (stringp conf-variable)
2433 (string-match (concat "[" conf-variable "]") typekey))))
2434
2435;;; ===========================================================================
2436;;;
2437;;; Table of contents (contributed from Stephen Eglen, changed by C. Dominik)
2438
2439;; We keep at most one *toc* buffer - it is easy to make them
2440
2441(defvar reftex-last-toc-master nil
2442 "Stores the name of the tex file that `reftex-toc' was last run on.")
2443
2444(defvar reftex-last-toc-file nil
2445 "Stores the file name from which `reftex-toc' was called. For redo command.")
2446
2447(defvar reftex-toc-return-marker (make-marker)
2448 "Marker which makes it possible to return from toc to old position.")
2449
2450(defun reftex-toc ()
2451 "Show the table of contents for the current document.
2452To see the corresponding part of the LaTeX document, use within the
2453*toc* buffer:
2454
2455SPC Show the corresponding section of the LaTeX document
2456RET Goto the section and hide the *toc* buffer
2457q Hide the *toc* window and return to position of last reftex-toc command
2458Q Kill the *toc* buffer and return to position of last reftex-toc command
2459f Toggle follow mode on and off
2460
2461When called with a raw C-u prefix, rescan the document first."
2462
2463 (interactive)
2464
2465 (and (not (string= reftex-last-toc-master (reftex-TeX-master-file)))
2466 (get-buffer "*toc*")
2467 (kill-buffer "*toc*"))
2468
2469 (setq reftex-last-toc-file (buffer-file-name))
2470 (setq reftex-last-toc-master (reftex-TeX-master-file))
2471
2472 (set-marker reftex-toc-return-marker (point))
2473
2474 ;; if follow mode is active, arrange to delay it one command
2475 (if reftex-toc-follow-mode
2476 (setq reftex-toc-follow-mode 1))
2477
2478 (if (and current-prefix-arg
2479 (get-buffer "*toc*"))
2480 (kill-buffer "*toc*"))
2481
2482 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
2483 (reftex-access-scan-info current-prefix-arg)
2484
2485 (let* ((all (symbol-value reftex-list-of-labels-symbol))
2486 (where (reftex-nearest-section))
2487 toc toc1 cell label file find startpos)
2488
2489 (if (and (get-buffer "*toc*")
2490 (get-buffer-window (get-buffer "*toc*")))
2491 (select-window (get-buffer-window (get-buffer "*toc*")))
2492 (delete-other-windows)
2493 (switch-to-buffer-other-window (current-buffer))
2494 (switch-to-buffer-other-window (get-buffer-create "*toc*")))
2495
2496 (cond
2497 ;; buffer is empty - fill it with the table of contents
2498 ((= (buffer-size) 0)
2499
2500 (local-set-key " " 'reftex-toc-view-line)
2501 (local-set-key "\C-m" 'reftex-toc-goto-line-and-hide)
2502 (local-set-key "r" 'reftex-toc-redo)
2503 (local-set-key "q" 'reftex-toc-quit)
2504 (local-set-key "Q" 'reftex-toc-quit-and-kill)
2505 (local-set-key "f" 'reftex-toc-toggle-follow)
2506 (setq truncate-lines t)
2507 (make-local-hook 'post-command-hook)
2508 (make-local-hook 'pre-command-hook)
2509 (setq post-command-hook '(reftex-toc-post-command-hook))
2510 (setq pre-command-hook '(reftex-toc-pre-command-hook))
2511
2512 (insert (format
2513"TABLE-OF-CONTENTS on %s
2514MENU: SPC=view RET=goto [q]uit [Q]uit+kill [r]escan [f]ollow-mode on/off
2515-------------------------------------------------------------------------------
2516" (abbreviate-file-name reftex-last-toc-master)))
2517 (setq startpos (point))
2518
2519 (if (reftex-use-fonts)
2520 (put-text-property 1 (point) 'face 'font-lock-keyword-face))
2521 (put-text-property 1 (point) 'intangible t)
2522
2523 (while all
2524 (setq cell (car all)
2525 all (cdr all))
2526 (setq label (nth 0 cell)
2527 toc (nth 2 cell)
2528 file (nth 3 cell)
2529 find (nth 4 cell))
2530 (if (not label)
2531 (progn
2532 (setq toc1 (concat toc "\n"))
2533 (put-text-property 0 (length toc1)
2534 'file file toc1)
2535 (put-text-property 0 (length toc1)
2536 'find find toc1)
2537 (insert toc1)
2538 )))
2539
2540 (backward-delete-char 1)
2541
2542 (setq buffer-read-only t))
2543 (t
2544 (goto-line 3)
2545 (beginning-of-line)
2546 (setq startpos (point))))
2547
2548 ;; Find the correct section
2549 (goto-char (point-max))
2550 (beginning-of-line)
2551 (while (and (> (point) startpos)
2552 (or (not (string= (get-text-property (point) 'file)
2553 (car where)))
2554 (not (string= (get-text-property (point) 'find)
2555 (cdr where)))))
2556 (beginning-of-line 0))))
2557
2558(defun reftex-nearest-section ()
2559 ;; Return (file . find) of nearest section command
2560 (let (cell label rest)
2561 (save-excursion
2562 (cond
2563 ;; Try to find a section heading
2564 ((or (re-search-backward reftex-section-regexp nil t)
2565 (re-search-forward reftex-section-regexp nil t))
2566 (goto-char (match-end 0))
2567 (cons (buffer-file-name)
2568 (reftex-allow-for-ctrl-m
2569 (concat (buffer-substring-no-properties
2570 (1- (match-beginning 1)) (match-end 0))
2571 (reftex-context-substring)))))
2572 ;; Try to find a label
2573 ((and (or (re-search-backward "\\\\label{\\([^}]+\\)}" nil t)
2574 (re-search-forward "\\\\label{\\([^}]+\\)}" nil t))
2575 (setq label (reftex-no-props (match-string 1)))
2576 (setq cell (assoc label (symbol-value
2577 reftex-list-of-labels-symbol)))
2578 (setq rest (memq cell (symbol-value reftex-list-of-labels-symbol)))
2579 (setq cell (car (memq (assoc nil rest) rest)))
2580 (null (car cell)))
2581 (cons (nth 3 cell) (nth 4 cell)))
2582 (t nil)))))
2583
2584(defun reftex-toc-pre-command-hook ()
2585 ;; used as pre command hook in *toc* buffer
2586 (reftex-unhighlight 0)
2587 (reftex-unhighlight 1))
2588
2589(defun reftex-toc-post-command-hook ()
2590 ;; used in the post-command-hook for the *toc* buffer
2591 (and (> (point) 1)
2592 (save-excursion
2593 (reftex-highlight 1
2594 (progn (beginning-of-line) (point))
2595 (progn (end-of-line) (point)))))
2596 (cond
2597 ((integerp reftex-toc-follow-mode)
2598 ;; remove delayed action
2599 (setq reftex-toc-follow-mode t))
2600 (reftex-toc-follow-mode
2601 ;; show context in other window
2602 (condition-case nil
2603 (reftex-toc-visit-line)
2604 ('error t)))))
2605
2606(defun reftex-toc-toggle-follow ()
2607 "Toggle toc-follow mode.
2608(it is not really a mode, just a flag)."
2609 (interactive)
2610 (setq reftex-toc-follow-mode (not reftex-toc-follow-mode)))
2611(defun reftex-toc-view-line ()
2612 "View document location in other window."
2613 (interactive)
2614 (reftex-toc-visit-line))
2615(defun reftex-toc-goto-line-and-hide ()
2616 "Go to document location in other window. Hide the *toc* window."
2617 (interactive)
2618 (reftex-toc-visit-line 'hide))
2619(defun reftex-toc-quit ()
2620 "Hide the *toc* window and do not move point."
2621 (interactive)
2622 (delete-window)
2623 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
2624 (goto-char (marker-position reftex-toc-return-marker)))
2625(defun reftex-toc-quit-and-kill ()
2626 "Kill the *toc* buffer."
2627 (interactive)
2628 (kill-buffer "*toc*")
2629 (delete-window)
2630 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
2631 (goto-char (marker-position reftex-toc-return-marker)))
2632(defun reftex-toc-redo ()
2633 "Regenerate the *toc* buffer. Call only from within the *toc* buffer"
2634 (interactive)
2635 (switch-to-buffer (reftex-get-file-buffer-force reftex-last-toc-file))
2636 (delete-other-windows)
2637 (setq current-prefix-arg '(4))
2638 (reftex-toc))
2639
2640(defun reftex-toc-visit-line (&optional final)
2641 ;; Visit the tex file corresponding to the toc entry on the current line.
2642 ;; If FINAL is t, stay there
2643 ;; If FINAL is 'hide, hide the *toc* window.
2644 ;; Otherwise, move cursor back into *toc* window
2645
2646 (let (file find beg end (toc-window (selected-window)) show-window)
2647 (save-excursion
2648 (beginning-of-line)
2649 (setq beg (point))
2650 (end-of-line)
2651 (setq end (point)))
2652
2653 ;; get the file and the search string
2654 (setq file (get-text-property (point) 'file))
2655 (setq find (get-text-property (point) 'find))
2656 (if (or (not file) (not find))
2657 (error "Cannot visit line"))
2658
2659 (switch-to-buffer-other-window (reftex-get-file-buffer-force file))
2660 (setq show-window (selected-window))
2661 (goto-char (point-min))
2662
2663 (if (not (re-search-forward find nil t))
2664 (error "Cannot visit line"))
2665
2666 (setq beg (match-beginning 0)
2667 end (match-end 0))
2668
2669 (goto-char beg)
2670 (recenter 1)
2671 (reftex-highlight 0 beg end (current-buffer))
2672
2673 (select-window toc-window)
2674
2675 ;; use the `final' parameter to decide what to do next
2676 (cond
2677 ((equal final t)
2678 (reftex-unhighlight 0)
2679 (select-window show-window))
2680 ((eq final 'hide)
2681 (reftex-unhighlight 0)
2682 (delete-window))
2683 (t nil))))
2684
2685;;; ===========================================================================
2686;;;
2687;;; BibTeX citations.
2688
2689;; Variables and constants
2690
2691;; Internal variable, but used from different functions
2692(defvar reftex-cite-format1 nil)
2693
2694;; The history list of regular expressions used for citations
2695(defvar reftex-cite-regexp-hist nil)
2696
2697;; Help string for citation selection
2698(defconst reftex-citation-help
2699 "AVAILABLE KEYS IN MAKE CITATION MENU
2700---------------------------------------
2701 n / p Go to next/previous entry (Cursor motion works as well)
2702 r restrict selection with another regexp
2703 SPACE Show full database entry in other window
2704 f Toggle follow mode: Other window will follow with full db entry
2705 q Quit without inserting \\cite macro into buffer
2706 ? Display this help message
2707 C-r Recursive edit into other window
2708 RETURN ... Accept current entry and insert in format according to
2709 reftex-cite-format")
2710
2711(defconst reftex-cite-format-default "\\cite{KEY}"
2712 "The default value for reftex-cite-format.
2713Uses the string version of scitex-cite-format.")
2714
2715(defconst reftex-cite-format-1-author-simple
2716 '( "\\cite{KEY}" "AUTHOR \\cite{KEY}" "AUTHOR {\it et al.} \\cite{KEY}")
2717 "Value for reftex-cite format establishing a simple citation with name
2718of the first author.
2719Uses the list version of reftex-cite-format.")
2720
2721(defconst reftex-cite-format-2-authors
2722 '((?\C-m
2723 . ( "\\cite{KEY}" "AUTHOR \\cite{KEY}"
2724 "AUTHOR \\& AUTHOR \\cite{KEY}" "AUTHOR \\etal{} \\cite{KEY}"))
2725 (?\,
2726 . ("\\cite{KEY}" "AUTHOR, \\cite{KEY}"
2727 "AUTHOR \\& AUTHOR, \\cite{KEY}" "AUTHOR \\etal{}, \\cite{KEY}"))
2728 (?\;
2729 . ("\\cite{KEY}" "AUTHOR; \\cite{KEY}"
2730 "AUTHOR \\& AUTHOR; \\cite{KEY}" "AUTHOR \\etal{}; \\cite{KEY}"))
2731 (?\:
2732 . ("\\cite{KEY}" "AUTHOR: \\cite{KEY}"
2733 "AUTHOR \\& AUTHOR: \\cite{KEY}" "AUTHOR \\etal{}: \\cite{KEY}"))
2734 (?\(
2735 . ("(\\cite{KEY})" "AUTHOR (\\cite{KEY})"
2736 "AUTHOR \\& AUTHOR (\\cite{KEY})" "AUTHOR \\etal{} (\\cite{KEY})"))
2737 (?\[
2738 . ("[\\cite{KEY}]" "AUTHOR [\\cite{KEY}]"
2739 "AUTHOR \\& AUTHOR [\\cite{KEY}]" "AUTHOR \\etal{} [\\cite{KEY}]")))
2740 "Value for reftex-cite-format that estabishes an Author/Year citation
2741where the year is supplied from BibTeX. Depending on which character
2742is used during selection to accept the label, an extra ,;: or pair of
2743parenthesis will be inserted.
2744Uses the list-of-cons-cells version of reftex-cite-format.")
2745
2746;; Find bibtex files
2747
2748(defun reftex-get-bibfile-list ()
2749 ;; Return list of bibfiles for current document
2750
2751 ;; Ensure access to scanning info
2752 (reftex-access-scan-info)
2753
2754 (or (symbol-value reftex-bibfile-list-symbol)
2755 (error "No BibTeX files to parse. Add \\bibliography statment to document and reparse.")))
2756
2757(defun reftex-scan-buffer-for-bibliography-statement (bib-list-symbol)
2758 ;; Scan buffer for bibliography macro and store file list in bib-list-symbol.
2759 (let (file-list dir-list)
2760 (setq dir-list
2761 (reftex-split
2762 (concat path-separator "+")
2763 (mapconcat '(lambda(x)
2764 (if (getenv x) (getenv x) ""))
2765 reftex-bibpath-environment-variables
2766 path-separator)))
2767 (goto-char (point-min))
2768 (if (re-search-forward "^[ \t]*\\\\bibliography{[ \t]*\\([^}]+\\)" nil t)
2769 (progn
2770 (setq dir-list
2771 (cons (file-name-directory
2772 (get-text-property (match-beginning 0) 'file))
2773 dir-list))
2774 (setq file-list
2775 (mapcar '(lambda (x) (concat x ".bib"))
2776 (reftex-delete-list
2777 reftex-bibfile-ignore-list
2778 (reftex-split
2779 "[ \t\n]*,[ \t\n]*"
2780 (reftex-no-props (match-string 1)))))))
2781 (message "No \\bibliography command in document."))
2782 (set bib-list-symbol
2783 (if file-list
2784 (reftex-find-files-on-path file-list dir-list
fba437e6 2785 "While parsing \\bibliography:")
a7ec1775
RS
2786 nil))))
2787
2788(defun reftex-find-files-on-path (file-list path-list &optional error-string)
2789 ;; Search for all files in FILE-LIST on the PATH-LIST. Return absolute names.
2790 ;; A missing file throws an exception with the error message ERROR-STRING.
2791 (let (found-list found file)
2792 (while file-list
2793 (setq file (car file-list)
2794 file-list (cdr file-list)
2795 found nil)
2796 (if (file-name-absolute-p file)
2797 (setq found (expand-file-name file))
2798 (let ((dirs path-list))
2799 (while (and dirs (not found))
2800 (if (and (not (string= (car dirs) ""))
2801 (file-exists-p (expand-file-name file (car dirs))))
2802 (setq found (expand-file-name file (car dirs))))
2803 (setq dirs (cdr dirs)))))
2804 (if (and found
2805 (file-exists-p found))
2806 (add-to-list 'found-list (expand-file-name found))
2807 (error "%s No such file %s."
2808 (or error-string "") file)))
2809 (nreverse found-list)))
2810
2811;; Find a certain reference in any of the BibTeX files.
2812
2813(defun reftex-pop-to-bibtex-entry (key file-list
2814 &optional mark-to-kill highlight)
2815 ;; Find BibTeX KEY in any file in FILE-LIST in another window.
2816 ;; If mark-to-kill is non-nil, mark new buffer to kill."
2817
2818 (let* ((re (concat "@[a-zA-Z]+[ \t\n\r]*{[ \t\n\r]*" (regexp-quote key) "[ \t\n\r,]"))
2819 (window-conf (current-window-configuration))
2820 file buf)
2821 (catch 'exit
2822 (switch-to-buffer-other-window (current-buffer))
2823 (while file-list
2824 (setq file (car file-list)
2825 file-list (cdr file-list))
2826 (if (not (setq buf (reftex-get-file-buffer-force file mark-to-kill)))
2827 (error "No such file %s" file))
2828 (switch-to-buffer buf)
2829 (widen)
2830 (goto-char 0)
2831 (if (re-search-forward re nil t)
2832 (progn
2833 (goto-char (match-beginning 0))
2834 (recenter 0)
2835 (if highlight
2836 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
2837 (throw 'exit (selected-window)))))
2838 (set-window-configuration window-conf)
2839 (beep)
2840 (message "No BibTeX entry with citation key %s" key))))
2841
2842;; Parse bibtex buffers
2843
2844(defun reftex-extract-bib-entries (buffers &optional get-word)
2845 ;; Extract bib entries which match regexps from BUFFERS.
2846 ;; BUFFERS is a list of buffers or file names.
2847 ;; Return list with entries."
2848 (let* (re-list first-re rest-re
2849 ;; avoid fontification of lookup buffers
2850 (lazy-lock-minimum-size 1)
2851 (buffer-list (if (listp buffers) buffers (list buffers)))
2852 found-list entry buffer1 buffer alist
2853 key-point start-point end-point)
2854
2855 (setq re-list (reftex-split "[ \t]*&&[ \t]*"
2856 (read-string "RegExp [ && RegExp...]: "
2857 nil 'reftex-cite-regexp-hist)))
2858
2859 (setq first-re (car re-list) ; We'll use the first re to find things,
2860 rest-re (cdr re-list)) ; the other to narrow down.
2861 (if (string-match "\\`[ \t]*\\'" first-re)
2862 (error "Empty regular expression"))
2863
2864 (save-excursion
2865 (save-window-excursion
2866
2867 ;; walk through all bibtex files
2868 (while buffer-list
2869 (setq buffer (car buffer-list)
2870 buffer-list (cdr buffer-list))
2871 (if (and (bufferp buffer)
2872 (buffer-live-p buffer))
2873 (setq buffer1 buffer)
2874 (setq buffer1 (reftex-get-file-buffer-force
2875 buffer (not reftex-keep-temporary-buffers))))
2876 (if (not buffer1)
2877 (error "Cannot find BibTeX file %s" buffer)
2878 (message "Scanning bibliography database %s" buffer1))
2879
2880 (set-buffer buffer1)
2881 (save-excursion
2882 (goto-char (point-min))
2883 (while (re-search-forward first-re nil t)
2884 (catch 'search-again
2885 (setq key-point (point))
2886 (if (not (re-search-backward
2887 "^[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*{" nil t))
2888 (throw 'search-again nil))
2889 (setq start-point (point))
2890 (goto-char (match-end 0))
2891 (condition-case nil
2892 (up-list 1)
2893 ('error (goto-char key-point)
2894 (throw 'search-again nil)))
2895 (setq end-point (point))
2896
2897 ;; Ignore @string, @comment and @c entries or things
2898 ;; outside entries
2899 (if (or (string= (downcase (match-string 1)) "string")
2900 (string= (downcase (match-string 1)) "comment")
2901 (string= (downcase (match-string 1)) "c")
2902 (< (point) key-point)) ; this means match not in {}
2903 (progn
2904 (goto-char key-point)
2905 (throw 'search-again nil)))
2906
2907 ;; Well, we have got a match
2908 (setq entry (concat
2909 (buffer-substring start-point (point)) "\n"))
2910
2911 ;; Check if other regexp match as well
2912 (setq re-list rest-re)
2913 (while re-list
2914 (if (not (string-match (car re-list) entry))
2915 ;; nope - move on
2916 (throw 'search-again nil))
2917 (setq re-list (cdr re-list)))
2918
2919 (setq alist (reftex-parse-bibtex-entry
2920 nil start-point end-point))
2921 (setq alist (cons (cons "&entry" entry) alist))
2922
2923 ;; check for crossref entries
2924 (if (assoc "crossref" alist)
2925 (setq alist
2926 (append
2927 alist (reftex-get-crossref-alist alist))))
2928
2929 ;; format the entry
2930 (setq alist
2931 (cons
2932 (cons "&formatted"
2933 (reftex-format-bib-entry alist))
2934 alist))
2935
2936 ;; add it to the list
2937 (setq found-list (cons alist found-list)))))
2938 (reftex-kill-temporary-buffers))))
2939 (setq found-list (nreverse found-list))
2940
2941 ;; Sorting
2942 (cond
2943 ((eq 'author reftex-sort-bibtex-matches)
2944 (sort found-list 'reftex-bib-sort-author))
2945 ((eq 'year reftex-sort-bibtex-matches)
2946 (sort found-list 'reftex-bib-sort-year))
2947 ((eq 'reverse-year reftex-sort-bibtex-matches)
2948 (sort found-list 'reftex-bib-sort-year-reverse))
2949 (t found-list))))
2950
2951(defun reftex-bib-sort-author (e1 e2)
2952 (let ((al1 (reftex-get-bib-authors e1)) (al2 (reftex-get-bib-authors e2)))
2953 (while (and al1 al2 (string= (car al1) (car al2)))
2954 (setq al1 (cdr al1)
2955 al2 (cdr al2)))
2956 (if (and (stringp (car al1))
2957 (stringp (car al2)))
2958 (string< (car al1) (car al2))
2959 (not (stringp (car al1))))))
2960
2961(defun reftex-bib-sort-year (e1 e2)
2962 (< (string-to-int (cdr (assoc "year" e1)))
2963 (string-to-int (cdr (assoc "year" e2)))))
2964
2965(defun reftex-bib-sort-year-reverse (e1 e2)
2966 (> (string-to-int (or (cdr (assoc "year" e1)) "0"))
2967 (string-to-int (or (cdr (assoc "year" e2)) "0"))))
2968
2969(defun reftex-get-crossref-alist (entry)
2970 ;; return the alist from a crossref entry
2971 (let ((crkey (cdr (assoc "crossref" entry)))
2972 start)
2973 (save-excursion
2974 (save-restriction
2975 (widen)
2976 (if (re-search-forward
2977 (concat "@\\w+{[ \t\n\r]*" (regexp-quote crkey) "[ \t\n\r]*,") nil t)
2978 (progn
2979 (setq start (match-beginning 0))
2980 (condition-case nil
2981 (up-list 1)
2982 ('error nil))
2983 (reftex-parse-bibtex-entry nil start (point)))
2984 nil)))))
2985
2986;; Parse and format individual entries
2987
2988(defun reftex-get-bib-authors (entry)
2989 ;; Return a list with the author names in ENTRY
2990 (let (authors)
2991 (setq authors (reftex-get-bib-field "author" entry))
2992 (if (equal "" authors)
2993 (setq authors (reftex-get-bib-field "editor" entry)))
2994 (while (string-match "\\band\\b[ \t]*" authors)
2995 (setq authors (replace-match "\n" nil t authors)))
2996 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" authors)
2997 (setq authors (replace-match "" nil t authors)))
2998 (while (string-match "^[ \t]+\\|[ \t]+$" authors)
2999 (setq authors (replace-match "" nil t authors)))
3000 (while (string-match "[ \t][ \t]+" authors)
3001 (setq authors (replace-match " " nil t authors)))
3002 (reftex-split "\n" authors)))
3003
3004(defun reftex-parse-bibtex-entry (entry &optional from to)
3005 (let (alist key start field)
3006 (save-excursion
3007 (save-restriction
3008 (if entry
3009 (progn
3010 (switch-to-buffer "*RefTeX-scratch*")
3011 (fundamental-mode)
3012 (erase-buffer)
3013 (insert entry))
3014 (widen)
3015 (narrow-to-region from to))
3016 (goto-char (point-min))
3017
3018 (if (re-search-forward
3019 "@\\(\\w+\\)[ \t\n\r]*{[ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
3020 (setq alist
3021 (list
3022 (cons "&type" (downcase (reftex-no-props (match-string 1))))
3023 (cons "&key" (reftex-no-props (match-string 2))))))
3024 (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
3025 (setq key (reftex-no-props (downcase (match-string 1))))
3026 (cond
3027 ((= (following-char) ?{)
3028 (forward-char 1)
3029 (setq start (point))
3030 (condition-case nil
3031 (up-list 1)
3032 ('error nil)))
3033 ((= (following-char) ?\")
3034 (forward-char 1)
3035 (setq start (point))
3036 (while (and (search-forward "\"" nil t)
3037 (= ?\\ (char-after (- (point) 2))))))
3038 (t
3039 (setq start (point))
3040 (re-search-forward "[ \t\n\r,}]" nil 1)))
3041 (setq field (buffer-substring-no-properties start (1- (point))))
3042 ;; remove extra whitesp
3043 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
3044 (setq field (replace-match " " nil t field)))
3045 ;; remove leading garbage
3046 (if (string-match "^[ \t{]+" field)
3047 (setq field (replace-match "" nil t field)))
3048 ;; remove trailing garbage
3049 (if (string-match "[ \t}]+$" field)
3050 (setq field (replace-match "" nil t field)))
3051 (setq alist (cons (cons key field) alist)))
3052 alist))))
3053
3054(defun reftex-get-bib-field (fieldname entry)
3055 ;; Extract the field FIELDNAME from an ENTRY
3056 (or (cdr (assoc fieldname entry))
3057 ""))
3058
3059(defun reftex-format-bib-entry (entry)
3060 ;; Format a BibTeX ENTRY so that it is nice to look at
3061 (let*
3062 ((rtn nil)
3063 (auth-list (reftex-get-bib-authors entry))
3064 (authors (mapconcat '(lambda (x) x) auth-list ", "))
3065 (year (reftex-get-bib-field "year" entry))
3066 (title (reftex-get-bib-field "title" entry))
3067 (type (reftex-get-bib-field "&type" entry))
3068 (key (reftex-get-bib-field "&key" entry))
3069 (extra
3070 (cond
3071 ((equal type "article")
3072 (concat (reftex-get-bib-field "journal" entry) " "
3073 (reftex-get-bib-field "volume" entry) ", "
3074 (reftex-get-bib-field "pages" entry)))
3075 ((equal type "book")
3076 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
3077 ((equal type "phdthesis")
3078 (concat "PhD: " (reftex-get-bib-field "school" entry)))
3079 ((equal type "mastersthesis")
3080 (concat "Master: " (reftex-get-bib-field "school" entry)))
3081 ((equal type "inbook")
3082 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
3083 ", pp. " (reftex-get-bib-field "pages" entry)))
3084 ((or (equal type "conference")
3085 (equal type "incollection")
3086 (equal type "inproceedings"))
3087 (concat "in: " (reftex-get-bib-field "booktitle" entry)))
3088 (t ""))))
3089 (setq authors
3090 (if (> (length authors) 30)
3091 (concat (substring authors 0 27) "...")
3092 (format "%-30s" authors))
3093 title
3094 (if (> (length title) 70)
3095 (concat (substring title 0 67) "...")
3096 (format "%-70s" title))
3097 extra
3098 (if (> (length extra) 40)
3099 (concat (substring extra 0 37) "...")
3100 (format "%-40s" extra)))
3101 (if (reftex-use-fonts)
3102 (progn
3103 (put-text-property 0 (length authors) 'face 'font-lock-keyword-face
3104 authors)
3105 (put-text-property 0 (length title) 'face 'font-lock-comment-face
3106 title)
3107 (put-text-property 0 (length extra) 'face 'font-lock-reference-face
3108 extra)))
3109 (setq rtn (concat key "\n " authors " " year " " extra
3110 "\n " title "\n\n"))
3111 rtn))
3112
3113;; Make a citation
3114
3115(defun reftex-citation (&optional arg no-insert)
3116 "Make a citation unsing BibTeX database files.
3117After asking for a Regular Expression, it scans the buffers with
3118bibtex entries (taken from the \\bibliography command) and offers the
3119matching entries for selection. The selected entry is formated according
3120to reftex-cite-format and inserted into the buffer.
3121If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
3122The regular expression uses an expanded syntax: && is interpreted as 'and'.
3123Thus, aaaa&&bbb matches entries which contain both aaaa and bbb.
fba437e6 3124When this function is called with point inside the braces of a \\cite
a7ec1775
RS
3125command, it will add another key, ignoring the value of reftex-cite-format.
3126When called with a numeric prefix, that many citations will be made and all
fba437e6 3127put into the same \\cite command.
a7ec1775
RS
3128When called with just C-u as prefix, enforces rescan of buffer for
3129bibliography statement (e.g. if it was changed)."
3130
3131 (interactive "P")
3132
3133 ;; check for recursive edit
3134 (reftex-check-recursive-edit)
3135
3136 ;; if there is just 1 C-u prefix arg, force to rescan buffer
3137 (if (and current-prefix-arg
3138 (listp current-prefix-arg)
3139 (= 4 (prefix-numeric-value arg)))
3140 (reftex-reset-scanning-information))
3141
3142 ;; check if there is already a cite command at point and change cite format
3143 ;; in order to only add another reference in the same cite command.
3144 (let ((pos (point)))
3145 (search-backward "\\" (point-min) 1)
3146 (if (and (looking-at "\\\\[a-zA-Z]*cite\\*?\\(\\[[^]]*\\]\\)*{\\([^}]*\\)")
3147 (>= (match-end 0) pos)
3148 (>= pos (match-beginning 2)))
3149 (progn
3150 (goto-char pos)
3151 (cond
3152 ((or (not arg)
3153 (not (listp arg)))
3154 (setq reftex-cite-format1
3155 (concat
3156 (if (not (or (= (preceding-char) ?{)
3157 (= (preceding-char) ?,)))
3158 ","
3159 "")
3160 "KEY"
3161 (if (not (or (= (following-char) ?})
3162 (= (following-char) ?,)))
3163 ","
3164 ""))))
3165 (t
3166 (setq reftex-cite-format1 "KEY"))))
3167 (setq reftex-cite-format1
3168 (if (symbolp reftex-cite-format)
3169 (symbol-value reftex-cite-format)
3170 reftex-cite-format))
3171 (goto-char pos)))
3172
3173 (let* (key entry cnt rtn ins-string re-list re
3174 ;; scan bibtex files
3175 (lazy-lock-minimum-size 1)
3176 (found-list (reftex-extract-bib-entries
3177 (reftex-get-bibfile-list)))
3178 (found-list-r nil)
3179 (accept-keys
3180 (if (and (listp reftex-cite-format1)
3181 (listp (car reftex-cite-format1)))
3182 (mapcar 'car reftex-cite-format1)
3183 '(?\C-m))))
3184 (if (not found-list)
3185 (error "Sorry, no matches found"))
3186
3187 ;; remember where we came from
3188 (setq reftex-call-back-to-this-buffer (current-buffer))
3189
3190 ;; offer selection
3191 (save-window-excursion
3192 (switch-to-buffer-other-window "*RefTeX Select*")
3193 (erase-buffer)
3194 (mapcar '(lambda (x) (insert (cdr (assoc "&formatted" x))))
3195 found-list)
3196 (if (= 0 (buffer-size))
3197 (error "Sorry, no matches found"))
3198 (setq truncate-lines t)
3199 (goto-char 1)
3200 (if (catch 'exit
3201 (while t
3202 (setq rtn
3203 (reftex-select-item
3204 nil
3205 (concat
3206 "Select: [n]ext [p]rev [r]estrict [q]uit [?]Help ||"
3207 " RETURN "
3208 (condition-case nil
3209 (mapconcat 'char-to-string accept-keys " ")
3210 (error (error "Illegal reftex-cite-format"))))
3211 "^[^ \t\n]"
3212 "\n\n"
3213 4
3214 reftex-citation-help
3215 (cons ?r accept-keys)
3216 nil
3217 'reftex-bibtex-selection-callback nil))
3218 (setq key (car rtn)
3219 cnt (cdr rtn))
3220 (if (not key) (throw 'exit nil))
3221 (cond
3222 ((equal key ?r)
3223 ;; restrict with new regular expression
3224 (setq re-list
3225 (reftex-split "[ \t]*&&[ \t]*"
3226 (read-string "RegExp [ && RegExp...]: "
3227 nil 'reftex-cite-regexp-hist)))
3228 (while re-list
3229 (setq re (car re-list)
3230 re-list (cdr re-list))
3231 (setq found-list-r
3232 (delete ""
3233 (mapcar
3234 '(lambda (x)
3235 (if (string-match re
3236 (cdr (assoc "&entry" x)))
3237 x
3238 ""))
3239 found-list))))
3240 (if found-list-r
3241 (setq found-list found-list-r)
3242 (ding))
3243 (erase-buffer)
3244 (mapcar '(lambda (x) (insert (cdr (assoc "&formatted" x))))
3245 found-list)
3246 (goto-char 1))
3247 ((or (member key accept-keys)
3248 (equal key ?\C-m)
3249 (equal key 'return))
3250 (setq entry (nth cnt found-list))
3251 (throw 'exit t))
3252 (t
3253 (ding)))))
3254 (progn
3255 ;; format the entry
3256 (if (not (integerp key)) (setq key ?\C-m))
3257 (setq ins-string (reftex-format-citation entry key)))
3258 (setq ins-string "")
3259 (message "Quit")))
3260 (kill-buffer "*RefTeX Select*")
3261
3262 (if (not no-insert)
3263 (insert ins-string))
3264 (message "")
3265
3266 ;; Check if the prefix arg was numeric, and call reftex-citation recursively
3267 (if (and (integerp arg)
3268 (> arg 1)
3269 (re-search-backward
3270 "\\\\[a-zA-Z]*cite\\*?\\(\\[[^]]*\\]\\)*{\\([^}]*\\)" nil t))
3271 (progn
3272 (goto-char (match-end 0))
3273 (setq arg (1- arg))
3274 (reftex-citation arg))
3275 (reftex-kill-temporary-buffers))
3276 ;; Return the citation key
3277 (reftex-get-bib-field "&key" entry)))
3278
3279(defun reftex-format-citation (entry key)
3280 ;; Format a citation from the info in the BibTeX ENTRY
3281 (let* ((cite-key (reftex-get-bib-field "&key" entry))
3282 (year (reftex-get-bib-field "year" entry))
3283 (auth-list (reftex-get-bib-authors entry))
3284 (nauthors (length auth-list))
3285 format)
3286
3287 (save-excursion
3288 ;; Find the correct format
3289 (if (and (listp reftex-cite-format1)
3290 (listp (car reftex-cite-format1)))
3291 (if (integerp (car (car reftex-cite-format1)))
3292 (if (assoc key reftex-cite-format1)
3293 (setq format (cdr (assoc key reftex-cite-format1)))
3294 (if (or (equal key ?\C-m)
3295 (equal key 'return))
3296 (setq format (cdr (car reftex-cite-format1)))
3297 (error "Error in reftex-cite-format")))
3298 (error "Error in reftex-cite-format"))
3299 (setq format reftex-cite-format1))
3300
3301 (if (listp format)
3302 (let ((nn (min nauthors (1- (length format)))))
3303 (while (and (> nn 0) (string= "" (nth nn format)))
3304 (setq nn (1- nn)))
3305 (setq format (nth nn format))))
3306 (if (stringp format)
3307 (setq format format)
3308 (setq format "\\cite{KEY}"))
3309
3310 ;; Insert the author names
3311 (while (string-match "\\bAUTHOR\\b" format)
3312 (setq format (replace-match (car auth-list) t t format))
3313 (setq auth-list (cdr auth-list)))
3314 (while (string-match "\\bKEY\\b" format)
3315 (setq format (replace-match cite-key t t format)))
3316 (while (string-match "\\bYEAR\\b" format)
3317 (setq format (replace-match year t t format)))
3318 format)))
3319
3320;; this is slow and not recommended for follow mode
3321(defun reftex-bibtex-selection-callback (cnt)
3322 ;; Callback function to be called from the BibTeX selection, in
3323 ;; order to display context. This function is relatively slow and not
3324 ;; recommended for follow mode, just for individual lookups.
3325 ;; When compiled, this gives a warning about found-list. However,
3326 ;; the calling function binds found-list with let.
3327 (let ((win (selected-window))
3328 (key (reftex-get-bib-field "&key" (nth cnt found-list)))
3329 (bibfile-list (save-excursion
3330 (set-buffer reftex-call-back-to-this-buffer)
3331 (reftex-get-bibfile-list))))
3332 (reftex-pop-to-bibtex-entry key bibfile-list
3333 (not reftex-keep-temporary-buffers) t)
3334 (select-window win)))
3335
3336;;; ===========================================================================
3337;;;
3338;;; Here is the routine used for selection
3339
3340;; Marker for return point from recursive edit
3341(defvar reftex-recursive-edit-marker (make-marker))
3342
3343(defun reftex-check-recursive-edit ()
3344 ;; Check if we are already in a recursive edit. Abort with helpful
3345 ;; message if so.
3346 (if (marker-position reftex-recursive-edit-marker)
3347 (error
3348 (substitute-command-keys
3349 "In unfinished recursive edit. Finish (\\[exit-recursive-edit]) or abort (\\[abort-recursive-edit])."))))
3350
3351(defun reftex-select-item (buffer prompt next-re end-re size help-string
3352 event-list &optional offset
3353 call-back cb-flag)
3354;; Select an item from the buffer BUFFER. Show PROMPT to user, find
3355;; next item with NEXT-RE regular expression, return on any of the
3356;; events listed in EVENT-LIST. The function returns the event along
3357;; with an integer indicating which item was selected. When OFFSET is
3358;; specified, starts at that item in the list. When CALL-BACK is
3359;; given, it is a function which is called with the match of the
3360;; NEXT-RE match and the index of the element.
3361 (let* (key key-sq b e ev cnt cmd
3362 (offset1 (or offset 1)))
3363 (setq ev
3364 (catch 'exit
3365 (save-window-excursion
3366 (if buffer
3367 (switch-to-buffer-other-window buffer))
3368 (if (= 0 (buffer-size))
3369 (throw 'exit nil))
3370 (setq truncate-lines t)
3371 (goto-char 1)
3372 (if (not (re-search-forward next-re nil t offset1))
3373 (progn ; in case the offset is illegal
3374 (setq offset1 1)
3375 (if (not (re-search-forward next-re nil t offset1))
3376 (throw 'exit nil))))
3377 (beginning-of-line 1)
3378 (setq cnt (if offset1 (1- offset1) 0))
3379 (while t
3380 (if (and cb-flag call-back)
3381 (funcall call-back cnt))
3382 (setq b (point)
3383 e (save-excursion
3384 (save-match-data
3385 (re-search-forward end-re nil 1))
3386 (point)))
3387 (reftex-highlight 1 b e)
3388 (if (or (not (pos-visible-in-window-p b))
3389 (not (pos-visible-in-window-p e)))
3390 (recenter (/ (window-height) 2)))
3391 (setq key-sq (read-key-sequence prompt))
3392 (setq key (car
3393 (cond
3394 ((fboundp 'listify-key-sequence) ; Emacs
3395 (listify-key-sequence key-sq))
3396 ((fboundp 'event-to-character) ; XEmacs
3397 (mapcar 'event-to-character key-sq))
3398 (t (error "Please report this problem to dominik@strw.leidenuniv.nl")))))
3399
3400 (setq cmd (key-binding key-sq))
3401
3402 (reftex-unhighlight 0)
3403
3404 (cond
3405
3406 ((or (equal key ?n)
3407 (equal key ?\C-i)
3408 (equal cmd 'next-line))
3409 (if (re-search-forward next-re nil t 2)
3410 (setq cnt (1+ cnt)))
3411 (beginning-of-line 1))
3412
3413 ((equal cmd 'scroll-up)
3414 (setq cnt (1- cnt))
3415 (while (and (pos-visible-in-window-p)
3416 (re-search-forward next-re nil t))
3417 (setq cnt (1+ cnt)))
3418 (beginning-of-line 1)
3419 (recenter 1))
3420
3421 ((or (equal key ?p)
3422 (equal cmd 'previous-line))
3423 (if (re-search-backward next-re nil t)
3424 (setq cnt (1- cnt))))
3425
3426 ((equal cmd 'scroll-down)
3427 (while (and (pos-visible-in-window-p)
3428 (re-search-backward next-re nil t))
3429 (setq cnt (1- cnt)))
3430 (recenter (- (window-height) size 2)))
3431
3432 ((equal key ?q)
3433 (throw 'exit nil))
3434
3435 ((equal key ?\C-g)
3436 (bury-buffer)
3437 (error "Abort"))
3438
3439 ((or (equal key ?\C-m)
3440 (equal key 'return)
3441 (equal cmd 'newline))
3442 (throw 'exit 'return))
3443
3444 ((or (equal key ?C) ; backward compatibility
3445 (equal key ?f))
3446 (setq cb-flag (not cb-flag)))
3447
3448 ((equal key ?\ )
3449 (funcall call-back cnt))
3450
3451 ((equal key ?\?)
3452 (save-window-excursion
3453 (with-output-to-temp-buffer "*RefTeX Help*"
3454 (princ help-string))
3455 (setq unread-command-events
3456 (cons
3457 (cond
3458 ((fboundp 'read-event) ; Emacs
3459 (read-event))
3460 ((fboundp 'next-command-event) ; XEmacs
3461 (next-command-event))
3462 (t (error "Please report this problem to dominik@strw.leidenuniv.nl")))
3463 nil)))
3464 (kill-buffer "*RefTeX Help*"))
3465
3466 ((equal key ?\C-r)
3467 ;; sje - code copied from ispell.el for
3468 ;; performing recursive edit
3469 (set-marker reftex-recursive-edit-marker (point))
3470 (unwind-protect
3471 (progn
3472 (save-window-excursion
3473 (save-excursion
3474 (other-window 1)
3475 (message
3476 (substitute-command-keys
3477 "Recursive edit. Return to selection with \\[exit-recursive-edit]"))
3478 (recursive-edit)))
3479 (if (not (equal (marker-buffer
3480 reftex-recursive-edit-marker)
3481 (current-buffer)))
3482 (error
3483 "Cannot continue RefTeX from this buffer."))
3484 (goto-char reftex-recursive-edit-marker))
3485 (set-marker reftex-recursive-edit-marker nil)))
3486
3487 ((member key event-list)
3488 (throw 'exit key))
3489 (t
3490 (ding)))))))
3491 (message "")
3492 (cons ev cnt)))
3493
3494;;; ===========================================================================
3495;;;
3496;;; View cross references
3497
3498(defun reftex-view-crossref (&optional arg)
fba437e6
RS
3499 "View cross reference of \\ref or \\cite macro at point.
3500If the macro at point is a \\ref, show the corresponding label definition.
3501If it is a \\cite, show the BibTeX database entry.
a7ec1775
RS
3502If there is no such macro at point, search forward to find one.
3503When you call this function several times in direct successtion, point will
3504move to view subsequent cross references further down in the buffer.
3505With argument, actually select the window showing the cross reference."
3506
3507 (interactive "P")
3508
3509 ;; See where we are.
3510 (let* ((pos (point))
3511 (re "\\\\[a-z]*\\(cite\\|ref\\)\\(\\[[^{}]*\\]\\)?{\\([^}]+\\)}")
3512 (my-window (get-buffer-window (current-buffer)))
3513 pop-window cmd args macro label entry key-start point)
3514
3515 (if (save-excursion
3516 (forward-char 1)
3517 (and (search-backward "\\" nil t)
3518 (looking-at re)
3519 (< pos (match-end 0))))
3520 (setq macro (match-string 1)
3521 key-start (match-beginning 3)))
3522
3523 (if (and macro (eq last-command this-command))
3524 (if (and (string= macro "cite")
3525 (skip-chars-forward "^}, \t\n\r")
3526 (= (following-char) ?,))
3527 (setq key-start (1+ (point)))
3528 (setq macro nil)))
3529
3530 (if (not macro)
3531 (if (re-search-forward re nil t)
3532 (setq macro (match-string 1)
3533 key-start (match-beginning 3))
3534 (error "No further cross references in buffer")))
3535
3536 (goto-char key-start)
3537
3538 ;; Ensure access to scanning info
3539 (reftex-access-scan-info)
3540
3541 (cond
3542 ((string= macro "cite")
3543 (setq cmd 'reftex-pop-to-bibtex-entry
3544 args (list
3545 (reftex-no-props (reftex-this-word "^{},"))
3546 (reftex-get-bibfile-list) nil t)))
3547 ((string= macro "ref")
3548 (let ((label (reftex-no-props (reftex-this-word "^{}")))
3549 (entry (assoc label (symbol-value reftex-list-of-labels-symbol))))
3550 (if entry
3551 (setq cmd 'reftex-pop-to-label
3552 args (list label (list (nth 3 entry)) nil t))
3553 (error "Label %s not known - reparse document might help" label))))
3554 (t (error "This should not happen")))
3555 (setq point (point))
3556 (apply cmd args)
3557 (setq pop-window (selected-window))
3558 (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
3559 (select-window my-window)
3560 (goto-char point)
3561 (and arg (select-window pop-window))))
3562
3563(defun reftex-mouse-view-crossref (ev)
fba437e6
RS
3564 "View cross reference of \\ref or \\cite macro where you click.
3565If the macro at point is a \\ref, show the corresponding label definition.
3566If it is a \\cite, show the BibTeX database entry.
a7ec1775 3567If there is no such macro at point, search forward to find one.
a7ec1775
RS
3568With argument, actually select the window showing the cross reference."
3569 (interactive "e")
3570 (mouse-set-point ev)
3571 (reftex-view-crossref current-prefix-arg))
3572
3573;;; ===========================================================================
3574;;;
3575;;; Functions that check out the surroundings
3576
3577(defun reftex-what-macro (which &optional bound)
3578 ;; Find out if point is within the arguments of any TeX-macro.
3579 ;; The return value is either (\"\\\\macro\" . (point)) or a list of them.
3580
3581 ;; If WHICH is nil, immediately return nil.
3582 ;; If WHICH is t, return list of all macros enclosing point.
3583 ;; If WHICH is a list of macros, look only for those macros and return the
3584 ;; name of the first macro in this list found to enclose point.
3585 ;; If the optional BOUND is an integer, bound backwards directed
3586 ;; searches to this point. If it is nil, limit to nearest \\section -
3587 ;; like statement.
3588
3589 ;; This function is pretty stable, but can be fooled if the text contains
3590 ;; things like \\macro{aa}{bb} where \\macro is defined to take only one
3591 ;; argument. As RefTeX cannot know this, the string \"bb\" would still be
3592 ;; considered an argument of macro \\macro.
3593
3594 (catch 'exit
3595 (if (null which) (throw 'exit nil))
3596 (let ((bound (or bound (save-excursion (re-search-backward
3597 reftex-section-regexp nil 1)
3598 (point))))
3599 pos cmd-list cmd)
3600 (save-restriction
3601 (save-excursion
3602 (narrow-to-region (max 1 bound) (point-max))
3603 ;; move back out of the current parenthesis
3604 (while (condition-case nil
3605 (progn (up-list -1) t)
3606 (error nil))
3607 ;; move back over any touching sexps
3608 (while (or (= (preceding-char) ?\])
3609 (= (preceding-char) ?\}))
3610 (backward-sexp))
3611 (setq pos (point))
3612 (if (and (or (= (following-char) ?\[)
3613 (= (following-char) ?\{))
3614 (and (re-search-backward "\\(\\\\[a-zA-Z]+\\)" nil t)
3615 (= (match-end 0) pos)))
3616 (progn
3617 (setq cmd (buffer-substring-no-properties
3618 (match-beginning 0) (match-end 0)))
3619 (if (eq t which)
3620 (setq cmd-list (cons (cons cmd (point)) cmd-list))
3621 (if (member cmd which)
3622 (throw 'exit (cons cmd (point)))))))
3623 (goto-char pos)))
3624 (nreverse cmd-list)))))
3625
3626(defun reftex-what-environment (which &optional bound)
3627 ;; Find out if point is inside a LaTeX environment.
3628 ;; The return value is (e.g.) either (\"equation\" . (point)) or a list of
3629 ;; them.
3630
3631 ;; If WHICH is nil, immediately return nil.
3632 ;; If WHICH is t, return list of all environments enclosing point.
3633 ;; If WHICH is a list of environments, look only for those environments and
3634 ;; return the name of the first environment in this list found to enclose
3635 ;; point.
3636
3637 ;; If the optional BOUND is an integer, bound backwards directed searches to
3638 ;; this point. If it is nil, limit to nearest \\section - like statement.
3639
3640 (catch 'exit
3641 (save-excursion
3642 (if (null which) (throw 'exit nil))
3643 (let ((bound (or bound (save-excursion (re-search-backward
3644 reftex-section-regexp nil 1)
3645 (point))))
3646 env-list end-list env)
3647 (while (re-search-backward "\\\\\\(begin\\|end\\){\\([^}]+\\)}"
3648 bound t)
3649 (setq env (buffer-substring-no-properties
3650 (match-beginning 2) (match-end 2)))
3651 (cond
3652 ((string= (match-string 1) "end")
3653 (add-to-list 'end-list env))
3654 ((member env end-list)
3655 (setq end-list (delete env end-list)))
3656 ((eq t which)
3657 (setq env-list (cons (cons env (point)) env-list)))
3658 ((member env which)
3659 (throw 'exit (cons env (point))))))
3660 (nreverse env-list)))))
3661
3662(defun reftex-word-before-point ()
3663 ;; Return the word before point. Word means here:
3664 ;; Consists of [a-zA-Z0-9.:] and ends at point or whitespace.
3665 (let ((pos (point)))
3666 (save-excursion
3667 (re-search-backward "[^ \t\n\r]" (point-min) 1)
3668 (setq pos (1+ (point)))
3669 (if (re-search-backward "[^a-zA-Z0-9\\\.:]" (point-min) 1)
3670 (forward-char 1))
3671 (buffer-substring-no-properties (point) pos))))
3672
3673;; ============================================================================
3674;;
3675;; Some generally useful functions
3676
3677(defun reftex-no-props (string)
3678 ;; Return STRING with all text properties removed
3679 (and (stringp string)
3680 (set-text-properties 0 (length string) nil string))
3681 string)
3682
3683(defun reftex-split (regexp string)
3684 ;; Split like perl
3685 (let ((start 0) list)
3686 (while (string-match regexp string start)
3687 (setq list (cons (substring string start (match-beginning 0)) list))
3688 (setq start (match-end 0)))
3689 (setq list (nreverse (cons (substring string start) list)))))
3690
3691(defun reftex-allow-for-ctrl-m (string)
3692 ;; convert STRING into a regexp, allowing ^M for \n
3693 (let ((start -2))
3694 (setq string (regexp-quote string))
3695 (while (setq start (string-match "[\n\r]" string (+ 3 start)))
3696 (setq string (replace-match "[\n\r]" nil t string)))
3697 string))
3698
3699(defun reftex-delete-list (elt-list list)
3700 ;; like delete, but with a list of things to delete
3701 ;; (original code from Rory Molinari)
3702 (while elt-list
3703 (setq list (delete (car elt-list) list)
3704 elt-list (cdr elt-list)))
3705 list)
3706
3707(defun reftex-get-buffer-visiting (file)
3708 ;; return a buffer visiting FILE
3709 (cond
3710 ((fboundp 'find-buffer-visiting) ; Emacs
3711 (find-buffer-visiting file))
3712 ((boundp 'find-file-compare-truenames) ; XEmacs
3713 (let ((find-file-compare-truenames t))
3714 (get-file-buffer file)))
3715 (t (error "Please report this problem to dominik@strw.leidenuniv.nl"))))
3716
3717(defun reftex-get-file-buffer-force (file &optional mark-to-kill)
3718 ;; Return a buffer visiting file. Make one, if necessary.
3719 ;; If neither such a buffer no the file exist, return nil.
3720 ;; If MARK-TO-KILL in non-nil, put any new buffers into the kill list."
3721
3722 (let ((buf (reftex-get-buffer-visiting file)))
3723 (cond
3724 (buf buf)
3725 ((file-exists-p file)
3726 (setq buf (find-file-noselect file))
3727 (if mark-to-kill
3728 (add-to-list 'reftex-buffers-to-kill buf))
3729 buf)
3730 (t nil))))
3731
3732(defun reftex-splice-symbols-into-list (list alist)
3733 ;; Splice the association in ALIST of any symbols in LIST into the list.
3734 ;; Return new list.
3735 (let (rtn tmp)
3736 (while list
3737 (while (and (not (null (car list)))
3738 (symbolp (car list)))
3739 (setq tmp (car list))
3740 (cond
3741 ((assoc tmp alist)
3742 (setq list (append (cdr (cdr (assoc tmp alist))) (cdr list))))
3743 (t
3744 (error "Cannot treat symbol %s in reftex-label-alist"
3745 (symbol-name tmp)))))
3746 (setq rtn (cons (car list) rtn)
3747 list (cdr list)))
3748 (nreverse rtn)))
3749
3750(defun reftex-uniquify (alist &optional keep-list)
3751 ;; Return a list of all elements in ALIST, but each car only once
3752 ;; Elements of KEEP-LIST are not removed even if duplicate
3753 (let (new elm)
3754 (while alist
3755 (setq elm (car alist)
3756 alist (cdr alist))
3757 (if (or (member (car elm) keep-list)
3758 (not (assoc (car elm) new)))
3759 (setq new (cons elm new))))
3760 (setq new (nreverse new))
3761 new))
3762
3763(defun reftex-use-fonts ()
3764 ;; Return t if we can and want to use fonts
3765 (and window-system
3766 reftex-use-fonts
3767 (boundp 'font-lock-keyword-face)))
3768
3769;; Highlighting uses overlays. If this is for XEmacs, we need to load
3770;; the overlay library, available in version 19.15
3771(and (not (fboundp 'make-overlay))
3772 (condition-case nil
3773 (require 'overlay)
3774 ('error
3775 (error "RefTeX needs overlay emulation (available in XEmacs 19.15)"))))
3776
3777;; We keep a vector with several different overlays to do our highlighting.
3778(defvar reftex-highlight-overlays [nil nil])
3779
3780;; Initialize the overlays
3781(aset reftex-highlight-overlays 0 (make-overlay 1 1))
3782(overlay-put (aref reftex-highlight-overlays 0) 'face 'highlight)
3783(aset reftex-highlight-overlays 1 (make-overlay 1 1))
3784(overlay-put (aref reftex-highlight-overlays 1) 'face 'highlight)
3785
3786;; Two functions for activating and deactivation highlight overlays
3787(defun reftex-highlight (index begin end &optional buffer)
3788 "Highlight a region with overlay INDEX."
3789 (move-overlay (aref reftex-highlight-overlays index)
3790 begin end (or buffer (current-buffer))))
3791(defun reftex-unhighlight (index)
3792 "Detatch overlay INDEX."
3793 (delete-overlay (aref reftex-highlight-overlays index)))
3794
3795(defun reftex-highlight-shall-die ()
3796 ;; Function used in pre-command-hook to remove highlights
3797 (remove-hook 'pre-command-hook 'reftex-highlight-shall-die)
3798 (reftex-unhighlight 0))
3799
3800;;; ---------------------------------------------------------------------------
3801;;;
3802;;; Cursor position after insertion of forms
3803
3804(defun reftex-position-cursor ()
3805 ;; Search back to question mark, delete it, leave point there
3806 (if (search-backward "\?" (- (point) 100) t)
3807 (delete-char 1)))
3808
3809(defun reftex-item ()
3810 "Insert an \\item and provide a label if the environments supports that."
3811 (interactive)
3812 (let ((env (car
3813 (reftex-what-environment '("itemize" "enumerate" "eqnarray")))))
3814
3815 (if (and env (not (bolp))) (newline))
3816
3817 (cond
3818
3819 ((string= env "eqnarray")
3820 (if (not (bolp))
3821 (newline))
3822 (reftex-label env)
3823 (insert "\n & & ")
3824 (beginning-of-line 1))
3825
3826 ((string= env "itemize")
3827 (newline)
3828 (insert "\\item "))
3829
3830 ((string= env "enumerate")
3831 (newline)
3832 (insert "\\item")
3833 (reftex-label env)
3834 (insert " "))
3835 (t
3836 (error "\\item command does not make sense here...")))))
3837
3838;;; ---------------------------------------------------------------------------
3839;;; ---------------------------------------------------------------------------
3840;;; ---------------------------------------------------------------------------
3841;;;
3842;;; Data Section: Definition of large constants
3843
3844
3845(defconst reftex-label-alist-builtin
3846 '(
3847 (LaTeX
3848 "LaTeX default environments"
3849 ("section" ?s "sec:" "~\\ref{%s}" t
3850 ("Part" "Chapter" "Chap." "Section" "Sec." "Sect." "Paragraph" "Par."
3851 "\\S" "Teil" "Kapitel" "Kap." "Abschnitt" ))
3852
3853 ("enumerate" ?n "item:" "~\\ref{%s}" "\\\\item\\(\\[[^]]*\\]\\)?"
3854 ("Item" "Punkt"))
3855
3856 ("equation" ?e "eq:" "~(\\ref{%s})" t
3857 ("Equation" "Eq." "Eqn." "Gleichung" "Gl."))
3858 ("eqnarray" ?e "eq:" nil "\\\\begin{eqnarray}\\|\\\\\\\\")
3859
3860 ("figure" ?f "fig:" "~\\ref{%s}" "\\\\caption\\(\\[[^]]*\\]\\)?{"
3861 ("Figure" "Fig." "Abbildung" "Abb."))
3862 ("figure*" ?f nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")
3863
3864 ("table" ?t "tab:" "~\\ref{%s}" "\\\\caption\\(\\[[^]]*\\]\\)?{"
3865 ("Table" "Tab." "Tabelle"))
3866 ("table*" ?t nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")
3867
3868 ("any" ?\ " " "\\ref{%s}" nil))
3869
3870 (Sideways
3871 "Sidewaysfigure and sidewaystable"
3872 ("sidewaysfigure" ?f nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{")
3873 ("sidewaystable" ?t nil nil "\\\\caption\\(\\[[^]]*\\]\\)?{"))
3874
3875 (AMSTeX
3876 "AMS-LaTeX: amsmath package environents"
3877 ("align" ?e "eq:" "~\\eqref{%s}" "\\\\begin{align}\\|\\\\\\\\")
3878 ("gather" ?e "eq:" nil "\\\\begin{gather}\\|\\\\\\\\")
3879 ("multline" ?e "eq:" nil t)
3880 ("flalign" ?e "eq:" nil "\\\\begin{flalign}\\|\\\\\\\\")
3881 ("alignat" ?e "eq:" nil "\\\\begin{alignat}{[0-9]*}\\|\\\\\\\\"))
3882
3883 (AASTeX
3884 "AAS deluxetable environment"
3885 ("deluxetable" ?t "tab:" nil "\\\\caption{")))
3886 "The default label environment descriptions.")
3887
3888;;; ---------------------------------------------------------------------------
3889;;;
3890;;; Functions to compile the tables, reset the mode etc.
3891
3892(defun reftex-reset-mode ()
3893 "Reset RefTeX Mode. Required to implement changes to some list variables.
3894This function will compile the information in reftex-label-alist and similar
3895variables. It is called when RefTeX is first used, and after changes to
3896these variables via reftex-add-to-label-alist."
3897 (interactive)
3898
3899 ; record that we have done this
3900 (setq reftex-tables-dirty nil)
3901
3902 ;; To update buffer-local variables
3903 (hack-local-variables)
3904 (message "updating internal tables...")
3905 (reftex-compute-ref-cite-tables)
3906 (message "updating internal tables... done")
3907 (reftex-reset-scanning-information))
3908
3909(defun reftex-reset-scanning-information ()
3910 "Reset the symbols containing information from buffer scanning.
3911This enforces rescanning the buffer on next use."
3912 (if (and (string= reftex-last-toc-master (reftex-TeX-master-file))
3913 (get-buffer "*toc*"))
3914 (kill-buffer "*toc*"))
3915 (let ((symlist reftex-multifile-symbols)
3916 symbol)
3917 (while symlist
3918 (setq symbol (car symlist)
3919 symlist (cdr symlist))
3920 (if (and (symbolp (symbol-value symbol))
3921 (not (null (symbol-value symbol))))
3922 (set (symbol-value symbol) nil)))))
3923
3924(defun reftex-compute-ref-cite-tables ()
3925 ;; Update ref and cite tables
3926
3927 (interactive)
3928
3929 ;; Compile information in reftex-label-alist
3930 (let ((tmp (reftex-uniquify (reftex-splice-symbols-into-list
3931 (append
3932 reftex-label-alist
3933 reftex-label-alist-external-add-ons
3934 reftex-default-label-alist-entries)
3935 reftex-label-alist-builtin)
3936 '(nil)))
3937 entry env-or-mac typekeychar typekey prefix regexp
3938 fmt wordlist cmd qh-list)
3939
3940 (setq reftex-words-to-typekey-alist nil
3941 reftex-typekey-list nil
3942 reftex-typekey-to-format-alist nil
3943 reftex-typekey-to-prefix-alist nil
3944 reftex-env-or-mac-alist nil
3945 reftex-label-env-list nil
3946 reftex-label-mac-list nil)
3947 (while tmp
3948 (catch 'next-entry
3949 (setq entry (car tmp)
3950 env-or-mac (car entry)
3951 entry (cdr entry)
3952 tmp (cdr tmp))
3953 (if (null env-or-mac)
3954 (setq env-or-mac ""))
3955 (if (stringp (car entry))
3956 ;; This is before version 2.00 - convert entry to new format
3957 ;; This is just to keep old users happy
3958 (setq entry (cons (string-to-char (car entry))
3959 (cons (concat (car entry) ":")
3960 (cdr entry)))))
3961 (setq typekeychar (nth 0 entry)
3962 typekey (char-to-string typekeychar)
3963 prefix (nth 1 entry)
3964 fmt (nth 2 entry)
3965 regexp (nth 3 entry)
3966 wordlist (nth 4 entry))
3967 (if (stringp wordlist)
3968 ;; This is before version 2.04 - convert to new format
3969 (setq wordlist (nthcdr 4 entry)))
3970 (if typekey
3971 (add-to-list 'reftex-typekey-list typekey))
3972 (if (and typekey prefix)
3973 (add-to-list 'reftex-typekey-to-prefix-alist (cons typekey prefix)))
3974 (cond
3975 ((string-match "\\`\\\\" env-or-mac)
3976 ;; It's a macro
3977 (add-to-list 'reftex-label-mac-list env-or-mac))
3978 (t
3979 (or (string= env-or-mac "any")
3980 (string= env-or-mac "")
3981 (add-to-list 'reftex-label-env-list env-or-mac))))
3982 (and fmt
3983 (not (assoc typekey reftex-typekey-to-format-alist))
3984 (setq reftex-typekey-to-format-alist
3985 (cons (cons typekey fmt)
3986 reftex-typekey-to-format-alist)))
3987 (and (not (string= env-or-mac "any"))
3988 (not (string= env-or-mac ""))
3989 (not (assoc env-or-mac reftex-env-or-mac-alist))
3990 (setq reftex-env-or-mac-alist
3991 (cons (list env-or-mac typekey regexp)
3992 reftex-env-or-mac-alist)))
3993 (while (and wordlist (stringp (car wordlist)))
3994 (or (assoc (car wordlist) reftex-words-to-typekey-alist)
3995 (setq reftex-words-to-typekey-alist
3996 (cons (cons (downcase (car wordlist)) typekey)
3997 reftex-words-to-typekey-alist)))
3998 (setq wordlist (cdr wordlist)))
3999 (cond
4000 ((string= "" env-or-mac) nil)
4001 ((assoc typekey qh-list)
4002 (setcdr (assoc typekey qh-list)
4003 (concat (cdr (assoc typekey qh-list)) " " env-or-mac)))
4004 (t
4005 (setq qh-list (cons (cons typekey env-or-mac) qh-list))))))
4006
4007 (setq qh-list (nreverse qh-list))
4008 (setq reftex-typekey-to-prefix-alist
4009 (nreverse reftex-typekey-to-prefix-alist))
4010 (setq reftex-type-query-prompt
4011 (concat "Label type: "
4012 (mapconcat '(lambda(x)
4013 (format "[%s]" (car x)))
4014 qh-list " ")
4015 " (?=Help)"))
4016 (setq reftex-type-query-help
4017 (concat "SELECT A LABEL TYPE:\n--------------------\n"
4018 (mapconcat '(lambda(x)
4019 (format " [%s] %s"
4020 (car x) (cdr x)))
4021 qh-list "\n")))))
4022
4023;;; Keybindings --------------------------------------------------------------
4024
4025(define-key reftex-mode-map "\C-c-" 'reftex-item)
4026(define-key reftex-mode-map "\C-c=" 'reftex-toc)
4027(define-key reftex-mode-map "\C-c(" 'reftex-label)
4028(define-key reftex-mode-map "\C-c)" 'reftex-reference)
4029(define-key reftex-mode-map "\C-c[" 'reftex-citation)
4030(define-key reftex-mode-map "\C-c&" 'reftex-view-crossref)
4031
4032;; If the user requests so, she can have a few more bindings:
4033(cond
4034 (reftex-extra-bindings
4035 (define-key reftex-mode-map "\C-ct" 'reftex-toc)
4036 (define-key reftex-mode-map "\C-cl" 'reftex-label)
4037 (define-key reftex-mode-map "\C-cr" 'reftex-reference)
4038 (define-key reftex-mode-map "\C-cc" 'reftex-citation)
4039 (define-key reftex-mode-map "\C-cv" 'reftex-view-crossref)
4040 (define-key reftex-mode-map "\C-cg" 'reftex-grep-document)
4041 (define-key reftex-mode-map "\C-cs" 'reftex-search-document)))
4042
4043;;; Menus --------------------------------------------------------------------
4044
4045;; Define a menu for the menu bar if Emacs is running under X
4046
4047(require 'easymenu)
4048
4049(easy-menu-define
4050 reftex-mode-menu reftex-mode-map
4051 "Menu used in RefTeX mode"
4052 '("Ref"
4053 ["Table of Contents" reftex-toc t]
4054 "----"
fba437e6
RS
4055 ["\\label" reftex-label t]
4056 ["\\ref" reftex-reference t]
4057 ["\\cite" reftex-citation t]
a7ec1775
RS
4058 ["View crossref" reftex-view-crossref t]
4059 "----"
4060 ("Search and Replace"
4061 ["Search whole document" reftex-search-document t]
4062 ["Replace in document" reftex-query-replace-document t]
4063 ["Grep on document" reftex-grep-document t]
4064 "----"
4065 ["Find duplicate labels" reftex-find-duplicate-labels t]
4066 ["Change label and refs" reftex-change-label t]
4067 "----"
4068 ["Create TAGS file" reftex-create-tags-file t])
4069 "----"
4070 ["Parse document" reftex-parse-document t]
4071 ["Reset RefTeX Mode" reftex-reset-mode t]
4072 ["Customize RefTeX" reftex-customize t]))
4073
4074;;; Run Hook ------------------------------------------------------------------
4075
4076(run-hooks 'reftex-load-hook)
4077
4078;;; That's it! ----------------------------------------------------------------
4079
4080; Make sure tabels are compiled
4081(message "updating internal tables...")
4082(reftex-compute-ref-cite-tables)
4083(setq reftex-tables-dirty nil)
4084
4085(provide 'reftex)
4086
4087;;;============================================================================
4088
4089;;; reftex.el end here