(fill-region-as-paragraph): Fix the test for any
[bpt/emacs.git] / lisp / textmodes / reftex.el
1 ;; reftex.el --- Minor mode for doing \label, \ref and \cite in LaTeX
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 ;;
28 ;; RefTeX is a minor mode with distinct support for \ref, \label and
29 ;; \cite commands in (multi-file) LaTeX documents.
30 ;; Labels are created semi-automatically. Definition context of labels is
31 ;; provided when creating a reference. Citations are simplified with
32 ;; efficient database lookup. A table of contents buffer provides easy
33 ;; access to any part of a document.
34 ;;
35 ;; To turn RefTeX Minor Mode on and off in a particular buffer, use
36 ;; `M-x reftex-mode'.
37 ;;
38 ;; To turn on RefTeX Minor Mode for all LaTeX files, add one of the
39 ;; following lines to your .emacs file:
40 ;;
41 ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
42 ;; (add-hook 'latex-mode-hook 'turn-on-reftex) ; with Emacs latex mode
43 ;;
44 ;; For default key bindings, see further down in this documentation.
45 ;;
46 ;;---------------------------------------------------------------------------
47 ;;
48 ;; CONTENTS
49 ;; --------
50 ;;
51 ;; Overview............................ All you need to know to get started.
52 ;;
53 ;; Configuration....................... How to configure RefTeX.
54 ;; Configuration Examples........... Tutorial examples.
55 ;; Hooks............................ Available hooks.
56 ;; Configuration Variables.......... Complete listing.
57 ;; Key Bindings........................ A list of default bindings.
58 ;; Multifile Documents................. Documents spread over many files.
59 ;; References to Other Documents....... RefTeX and the LaTeX package `xr'.
60 ;; Optimizations for Large Documents... How to improve speed and memory use.
61 ;; Related Packages.................... Other Emacs packages.
62 ;; Known Bugs and Work-Arounds......... First aid.
63 ;; Author.............................. Who wrote RefTeX and who helped.
64 ;;---------------------------------------------------------------------------
65 ;;
66 ;; OVERVIEW
67 ;; ========
68 ;;
69 ;; 1. USING \label AND \ref. Labels and references are one of the strong
70 ;; points of LaTeX. But, in documents with hundreds of equations,
71 ;; figures, tables etc. it becomes quickly impossible to find good label
72 ;; names and to actually remember them. Then, also completion of labels
73 ;; is not enough. One actually needs to see the context of the label
74 ;; definition to find the right one.
75 ;;
76 ;; - RefTeX distinguishes labels for different environments. It always
77 ;; knows if a certain label references a figure, table etc.. You can
78 ;; configure RefTeX to recognize any additional labeled environments
79 ;; you have defined yourself.
80 ;;
81 ;; - RefTeX defines automatically unique labels. Type `C-c ('
82 ;; (`reftex-label') to insert a label at point. RefTeX will either
83 ;; - derive a label from context (default for section labels)
84 ;; - insert a simple label consisting of a prefix and a number
85 ;; (default for equations,enumerate items, and footnotes) or
86 ;; - prompt for a label string (figures and tables).
87 ;; Which labels are created how can be controlled with the variable
88 ;; `reftex-insert-label-flags'.
89 ;;
90 ;; - Referencing labels is a snap and I promise you'll love it. In
91 ;; order to make a reference, type `C-c )' (`reftex-reference'). This
92 ;; shows an outline of the document with all labels of a certain type
93 ;; (figure, equation,...) and context of the label definition.
94 ;; Selecting one of the labels inserts a \ref macro into the original
95 ;; buffer. Online help during the selection is available with `?'.
96 ;;
97 ;; 2. CITATIONS. After typing `C-c [' (`reftex-citation'), RefTeX will let
98 ;; you specify a regexp to search in current BibTeX database files (as
99 ;; specified in the \bibliography command) and pull out a formatted list
100 ;; of matches for you to choose from. The list is *formatted* and
101 ;; sorted, thus much easier to read than the raw database entries. The
102 ;; text inserted into the buffer is by default just `\cite{KEY}', but
103 ;; can also contain author names and the year in a configurable way.
104 ;; See documentation of the variable `reftex-cite-format'.
105 ;;
106 ;; 3. TABLE OF CONTENTS. Typing `C-c =' (`reftex-toc') will show a table
107 ;; of contents of the document. From that buffer, you can jump quickly
108 ;; to every part of your document. This is similar to imenu, only it
109 ;; works for entire multifile documents and uses the keyboard rather
110 ;; than the mouse. The initial version of this function was contributed
111 ;; by Stephen Eglen.
112 ;;
113 ;; 4. MULTIFILE DOCUMENTS are fully supported by RefTeX. Such documents
114 ;; consist of a master file and many other files being included via
115 ;; \input or \include. RefTeX will provide cross referencing
116 ;; information from all files which are part of the document. See
117 ;; `RefTeX and Multifile Documents' further down in the documentation
118 ;; for more information on this topic.
119 ;;
120 ;; 5. DOCUMENT PARSING. RefTeX needs to parse the document in order to
121 ;; find labels and other information. It will do it automatically once,
122 ;; when you start working with a document. Re-parsing should not be
123 ;; necessary too often since RefTeX updates its lists internally when
124 ;; you make a new label with `reftex-label'. To enforce reparsing,
125 ;; call any of the functions `reftex-citation', `reftex-label',
126 ;; `reftex-reference', `reftex-toc' with a raw C-u prefix, or press the
127 ;; `r' key in the label menu and table of contents buffer.
128 ;;---------------------------------------------------------------------------
129 ;;
130 ;; CONFIGURATION
131 ;; =============
132 ;;
133 ;; RefTeX needs to be configured if you use labels to mark environments
134 ;; defined by yourself (e.g. with `\newenvironment') or in packages not
135 ;; included in the standard LaTeX distribution. RefTeX's default settings
136 ;; make it recognize practically all labeled environments and macros
137 ;; discussed in `The LaTeX Companion' by Goossens, Mittelbach & Samarin,
138 ;; Addison-Wesley 1994. These are:
139 ;;
140 ;; - figure, figure*, table, table*, equation, eqnarray, enumerate,
141 ;; the \footnote macro (this is the LaTeX core stuff)
142 ;; - align, gather, multline, flalign, alignat, xalignat, xxalignat,
143 ;; subequations (from AMS-LaTeX's amsmath.sty package)
144 ;; - the \endnote macro (from endnotes.sty)
145 ;; - Beqnarray (fancybox.sty)
146 ;; - floatingfig (floatfig.sty)
147 ;; - longtable (longtable.sty)
148 ;; - figwindow, tabwindow (picinpar.sty)
149 ;; - sidewaysfigure, sidewaystable (rotating.sty)
150 ;; - subfigure, subfigure*, the \subfigure macro (subfigure.sty)
151 ;; - supertabular (supertab.sty)
152 ;; - wrapfigure (wrapfig.sty)
153 ;;
154 ;; If you want to use any other labeled environments or macros, you need
155 ;; to configure RefTeX.
156 ;;
157 ;; Per Abrahamsens custom.el package provides a simple way to do
158 ;; configuration. To try it out, use `M-x reftex-customize'.
159 ;;
160 ;; CONFIGURATION EXAMPLES
161 ;; ----------------------
162 ;;
163 ;; Suppose you are working with AMS-LaTeX amsmath package (with its math
164 ;; environments like `align', `multline' etc.). RefTeX is preconfigured to
165 ;; recognize these - so there is nothing you have to do.
166 ;;
167 ;; Suppose you are also using `\newtheorem' in LaTeX in order to define two
168 ;; new environments `theorem' and `axiom'
169 ;;
170 ;; \newtheorem{axiom}{Axiom}
171 ;; \newtheorem{theorem}{Theorem}
172 ;;
173 ;; to be used like this:
174 ;;
175 ;; \begin{axiom}
176 ;; \label{ax:first}
177 ;; ....
178 ;; \end{axiom}
179 ;;
180 ;; So we need to tell RefTeX that `theorem' and `axiom' are new labeled
181 ;; environments which define their own label categories. Here is how:
182 ;;
183 ;; (setq reftex-label-alist
184 ;; '(("axiom" ?a "ax:" "~\\ref{%s}" nil ("Axiom" "Ax."))
185 ;; ("theorem" ?h "thr:" "~\\ref{%s}" t ("Theorem" "Theor." "Th."))))
186 ;;
187 ;; The type indicator characters ?a and ?h are used for prompts when RefTeX
188 ;; queries for a label type. Note that `h' was chosen for `theorem' since
189 ;; `t' is already taken by `table'. Note that also `s', `f', `e', `i', `n'
190 ;; are already used for standard environments.
191 ;; The automatic labels for Axioms and Theorems will look like "ax:23" or
192 ;; "thr:24".
193 ;; The "\ref{%s}" is a format string indicating how to insert references to
194 ;; these labels.
195 ;; The next item indicates how to grab context of the label definition.
196 ;; - t means to get it from a default location (from the beginning of a
197 ;; \macro or after the \begin statement). t is *not* a good choice for
198 ;; eqnarray and similar environments.
199 ;; - nil means to use the text right after the label definition.
200 ;; - For more complex ways of getting context, see the docstring of
201 ;; `reftex-label-alist'.
202 ;; The strings at the end of each entry are used to guess the correct label
203 ;; type from the word before point when creating a reference. E.g. if you
204 ;; write: "As we have shown in Theorem" and then press `C-c )', RefTeX will
205 ;; know that you are looking for a theorem label and restrict the menu to
206 ;; only these labels without even asking.
207 ;;
208 ;; Depending on how you would like the label insertion and selection for
209 ;; the new environments to work, you might want to add the letters "a" and
210 ;; "h" to some of the flags in the following variables:
211 ;;
212 ;; reftex-insert-label-flags reftex-label-menu-flags
213 ;;
214 ;; Suppose you want to make figures not directly with the figure
215 ;; environment, but with a macro like
216 ;;
217 ;; \newcommand{\myfig}[5][tbp]{%
218 ;; \begin{figure}[#1]
219 ;; \epsimp[#5]{#2}
220 ;; \caption{#3}
221 ;; \label{#4}
222 ;; \end{figure}}
223 ;;
224 ;; which would be called like
225 ;;
226 ;; \myfig[htp]{filename}{caption text}{label}{1}
227 ;;
228 ;; Now we also need to tell RefTeX that the 4th argument of the \myfig
229 ;; macro is a figure label, and where to find the context.
230 ;;
231 ;; (setq reftex-label-alist
232 ;; '(("axiom" ?a "ax:" "~\\ref{%s}" nil ("Axiom" "Ax."))
233 ;; ("theorem" ?h "thr:" "~\\ref{%s}" t ("Theorem" "Theor." "Th."))
234 ;; ("\\myfig[]{}{}{*}{}" ?f nil nil 3)))
235 ;;
236 ;; The empty pairs of brackets indicate the different arguments of the
237 ;; \myfig macro. The `*' marks the label argument. `?f' indicates that
238 ;; this is a figure label which will be listed together with labels from
239 ;; normal figure environments. The nil entries for prefix and reference
240 ;; format mean to use the defaults for figure labels. The `3' for the
241 ;; context method means to grab the 3rd macro argument - the caption.
242 ;;
243 ;; As a side effect of this configuration, `reftex-label' will now insert
244 ;; the required naked label (without the \label macro) when point is
245 ;; directly after the opening parenthesis of a \myfig macro argument.
246 ;;
247 ;; -----
248 ;;
249 ;; If you are writing in a language different from English you might want
250 ;; to add magic words for that language. Here is a German example:
251 ;;
252 ;; (setq reftex-label-alist
253 ;; '((nil ?s nil nil nil ("Kapitel" "Kap." "Abschnitt" "Teil"))
254 ;; (nil ?e nil nil nil ("Gleichung" "Gl."))
255 ;; (nil ?t nil nil nil ("Tabelle"))
256 ;; (nil ?f nil nil nil ("Figur" "Abbildung" "Abb."))
257 ;; (nil ?n nil nil nil ("Anmerkung" "Anm."))
258 ;; (nil ?i nil nil nil ("Punkt"))))
259 ;;
260 ;; Using nil as first item in each entry makes sure that this entry does
261 ;; not replace the original entry for that label type, but just adds magic
262 ;; words.
263 ;;
264 ;; -----
265 ;;
266 ;; Normally, RefTeX inserts equation references with parenthesis like
267 ;; "~(\ref{KEY})". If you want to change this to square brackets, use
268 ;;
269 ;; (setq reftex-label-alist '((nil ?e nil "~[\\ref{%s}]" nil nil)))
270 ;;
271 ;; In order to use the AMS-LaTeX \eqref macro instead, either of the
272 ;; following lines does the job.
273 ;;
274 ;; (setq reftex-label-alist '((nil ?e nil "~\\eqref{%s}" nil nil)))
275 ;; (setq reftex-label-alist '(AMSTeX))
276 ;;
277 ;; ----
278 ;;
279 ;; By default, citations are inserted simply as \cite{KEY}. You can have
280 ;; more complex citation commands with many available packages, most
281 ;; notably the harvard and natbib packages. RefTeX can be configured to
282 ;; support these and other styles by setting the variable
283 ;; `reftex-cite-format'. E.g., for the natbib package you would use
284 ;;
285 ;; (setq reftex-cite-format 'natbib)
286 ;;
287 ;; This can also be done as a file variable. For the full list of builtin
288 ;; options, try `M-x customize-variable RET reftex-cite-format RET'.
289 ;;
290 ;; HOOKS
291 ;; -----
292 ;; - Loading reftex.el runs the hook `reftex-load-hook'.
293 ;; - Turning on reftex-mode runs `reftex-mode-hook'.
294 ;; - Files visited literally are processed with
295 ;; `reftex-initialize-temporary-buffers' if that is a list of functions.
296 ;;
297 ;; CONFIGURATION VARIABLES
298 ;; -----------------------
299 ;;
300 ;; The best way to learn about all configuration variables is via the
301 ;; browser interface of the custom library. For reference, I am giving
302 ;; here a complete list.
303 ;;
304 ;; ;; Defining label environments
305 ;; reftex-default-label-alist-entries
306 ;; reftex-label-alist
307 ;; reftex-section-levels
308 ;; reftex-default-context-regexps
309 ;; reftex-use-text-after-label-as-context
310 ;; ;; Label insertion
311 ;; reftex-insert-label-flags
312 ;; reftex-derive-label-parameters
313 ;; reftex-label-illegal-re
314 ;; reftex-abbrev-parameters
315 ;; ;; Label referencing
316 ;; reftex-label-menu-flags
317 ;; reftex-level-indent
318 ;; reftex-refontify-context
319 ;; reftex-guess-label-type
320 ;; ;; BibteX citation configuration
321 ;; reftex-bibpath-environment-variables
322 ;; reftex-bibfile-ignore-list
323 ;; reftex-sort-bibtex-matches
324 ;; reftex-cite-format
325 ;; reftex-comment-citations
326 ;; reftex-cite-comment-format
327 ;; reftex-cite-punctuation
328 ;; ;; Table of contents configuration
329 ;; reftex-toc-follow-mode
330 ;; ;; Fine-tuning the parser
331 ;; reftex-keep-temporary-buffers
332 ;; reftex-initialize-temporary-buffers
333 ;; reftex-enable-partial-scans
334 ;; reftex-save-parse-info
335 ;; ;; Miscellaneous configurations
336 ;; reftex-extra-bindings
337 ;; reftex-plug-into-AUCTeX
338 ;; reftex-use-fonts
339 ;; reftex-auto-show-entry
340 ;; reftex-load-hook
341 ;; reftex-mode-hook
342 ;;-------------------------------------------------------------------------
343 ;;
344 ;; KEY BINDINGS
345 ;; ============
346 ;;
347 ;; All RefTeX commands can be reached from its menu, the `Ref' menu on the
348 ;; menu bar. More frequently used commands have key bindings:
349 ;;
350 ;; C-c = reftex-toc
351 ;; C-c ( reftex-label
352 ;; C-c ) reftex-reference
353 ;; C-c [ reftex-citation
354 ;; C-c & reftex-view-crossref
355 ;;
356 ;; These keys are chosen to avoid interfering with AUCTeX's settings.
357 ;; Personally, I also bind some functions in the C-c LETTER map for
358 ;; easier access:
359 ;;
360 ;; C-c t reftex-toc
361 ;; C-c l reftex-label
362 ;; C-c r reftex-reference
363 ;; C-c c reftex-citation
364 ;; C-c v reftex-view-crossref
365 ;; C-c s reftex-search-document
366 ;; C-c g reftex-grep-document
367 ;;
368 ;; If you want to copy those as well, set in your .emacs file:
369 ;;
370 ;; (setq reftex-extra-bindings t)
371 ;;
372 ;; It is possible to bind the function for viewing cross references to a
373 ;; mouse event. Something like the following will do the trick:
374 ;;
375 ;; (add-hook 'reftex-load-hook
376 ;; '(lambda ()
377 ;; (define-key reftex-mode-map [(shift mouse-2)]
378 ;; 'reftex-mouse-view-crossref)))
379 ;;-------------------------------------------------------------------------
380 ;;
381 ;; REFTEX AND MULTIFILE DOCUMENTS
382 ;; ==============================
383 ;;
384 ;; The following is relevant when using RefTeX for multi-file documents:
385 ;;
386 ;; o RefTeX has full support for multifile documents. You can edit parts
387 ;; of several (multifile) documents at the same time without conflicts.
388 ;; RefTeX provides functions to run `grep', `search' and `query-replace'
389 ;; on all files which are part of a multifile document.
390 ;;
391 ;; o All files belonging to a multifile document should have a File
392 ;; Variable (`TeX-master' for AUCTeX or `tex-main-file' for the standard
393 ;; Emacs LaTeX mode) set to the name of the master file. See the
394 ;; documentation of your (La)TeX mode and the Emacs documentation on
395 ;; file variables: [Emacs/Customization/Variables/File Variables].
396 ;;
397 ;; o The context of a label definition must be found in the same file as
398 ;; the label itself in order to be processed correctly by RefTeX. The
399 ;; only exception is that section labels referring to a section statement
400 ;; outside the current file can still use that section title as context.
401 ;;-------------------------------------------------------------------------
402 ;;
403 ;; REFERENCES TO OTHER DOCUMENTS
404 ;; =============================
405 ;;
406 ;; RefTeX supports the LaTeX package `xr', which makes it possible to
407 ;; reference labels defined in another document. See the documentation on
408 ;; `xr' for details.
409 ;; When the document is set up to work with `xr', you can use the `x' key
410 ;; in the reference label menu to switch to the label menu of an external
411 ;; document and select any labels from there. In the *toc* buffer, the
412 ;; `x' key can be used to switch to the table of contents of an external
413 ;; document.
414 ;;
415 ;; For this kind of inter-document cross references, saving of parsing
416 ;; information can mean a large speed-up.
417 ;;
418 ;; (setq reftex-save-parse-info t)
419 ;;
420 ;;-------------------------------------------------------------------------
421 ;;
422 ;; OPTIMIZATIONS FOR LARGE DOCUMENTS
423 ;; =================================
424 ;;
425 ;; The default settings of RefTeX ensure a safe ride for beginners and
426 ;; casual users. However, when using RefTeX for a large project and/or on
427 ;; a small computer, there are ways to improve speed or memory usage.
428 ;;
429 ;; o RefTeX will load other parts of a multifile document as well as BibTeX
430 ;; database files for lookup purposes. These buffers are kept, so that
431 ;; subsequent use of the same files is fast. If you can't afford keeping
432 ;; these buffers around, and if you can live with a speed penalty, try
433 ;;
434 ;; (setq reftex-keep-temporary-buffers nil)
435 ;;
436 ;; o The `C-u' prefix on the major RefTeX commands `reftex-label',
437 ;; `reftex-reference', `reftex-citation' and `reftex-toc' initiates
438 ;; re-parsing of the entire document in order to update the parsing
439 ;; information. For a large document this can be unnecessary, in
440 ;; particular if only one file has changed. RefTeX can be configured to
441 ;; do partial scans instead of full ones. `C-u' re-parsing then does
442 ;; apply only to the current buffer and files included from it.
443 ;; Likewise, the `r' key in both the label menu and the table-of-contents
444 ;; buffer will only prompt scanning of the file in which the label or
445 ;; section macro near the cursor was defined. Re-parsing of the entire
446 ;; document is still available by using `C-u C-u' as a prefix, or the
447 ;; capital `R' key in the menus. To use this feature, try
448 ;;
449 ;; (setq reftex-enable-partial-scans t)
450 ;;
451 ;; o Even with partial scans enabled, RefTeX still has to make one full
452 ;; scan, when you start working with a document. To avoid this, parsing
453 ;; information can stored in a file. The file `MASTER.rel' is used for
454 ;; storing information about a document with master file `MASTER.tex'.
455 ;; It is written each time RefTeX parses (part of) the document, and
456 ;; restored when you begin working with a document in a new editing
457 ;; session. To use this feature, put into .emacs:
458 ;;
459 ;; (setq reftex-save-parse-info t)
460 ;;----------------------------------------------------------------------------
461 ;;
462 ;; RELATED PACKAGES
463 ;; ================
464 ;;
465 ;; AUCTeX
466 ;; ------
467 ;; If you are writing TeX or LaTeX documents with Emacs, you should have
468 ;; a look at AUCTeX, the definitive package to work with TeX and LaTeX.
469 ;; Information on AUCTeX can be found here:
470 ;;
471 ;; http://www.sunsite.auc.dk/auctex/
472 ;;
473 ;; Instead of using the RefTeX functions described above directly, you can
474 ;; also use them indirectly, through AUCTeX (version 9.8a or later).
475 ;; RefTeX provides several interface functions which can be used as
476 ;; replacement for corresponding AUCTeX functions dealing with labels and
477 ;; citations. In this way you can work normally with AUCTeX and use RefTeX
478 ;; internals to create and complete labels and citation keys.
479 ;;
480 ;; `reftex-label' can be used as the `LaTeX-label-function' which does
481 ;; label insertion when new environments are created with `C-c C-e'.
482 ;;
483 ;; `reftex-arg-label', `reftex-arg-ref' and `reftex-arg-cite' can replace
484 ;; the corresponding `TeX-arg-...' functions. E.g. when you insert a label
485 ;; macro with `C-c RET label RET', RefTeX will be transparently used to
486 ;; create the label.
487 ;;
488 ;; In order to plug all 4 functions into AUCTeX, use:
489 ;;
490 ;; (setq reftex-plug-into-AUCTeX t)
491 ;;
492 ;; You may also choose to plug in only some of these functions. See the
493 ;; docstring of `reftex-plug-into-AUCTeX'.
494 ;;
495 ;; AUCTeX can support RefTeX via style files. A style file may contain
496 ;; calls to `reftex-add-to-label-alist' which defines additions to
497 ;; `reftex-label-alist'. The argument taken by this function must have the
498 ;; same format as `reftex-label-alist'. The `amsmath.el' style file of
499 ;; AUCTeX (>9.7p) for example contains the following:
500 ;;
501 ;; (TeX-add-style-hook "amsmath"
502 ;; (function
503 ;; (lambda ()
504 ;; (if (featurep 'reftex)
505 ;; (reftex-add-to-label-alist '(AMSTeX))))))
506 ;;
507 ;; while a package `myprop' defining a proposition environment with
508 ;; \newtheorem might use
509 ;;
510 ;; (TeX-add-style-hook "myprop"
511 ;; (function
512 ;; (lambda ()
513 ;; (if (featurep 'reftex)
514 ;; (reftex-add-to-label-alist
515 ;; '(("proposition" ?p "prop:" "~\\ref{%s}" t
516 ;; ("Proposition" "Prop."))))))))
517 ;;
518 ;; Bib-cite.el
519 ;; -----------
520 ;; Once you have written a document with labels, refs and citations, it can
521 ;; be nice to read such a file like a hypertext document. RefTeX has some
522 ;; support for that (`reftex-view-crossref', `reftex-search-document'). A
523 ;; more elegant interface with mouse support and links into Hyperbole is
524 ;; provided (among other things) by Peter S. Galbraith's `bib-cite.el'.
525 ;; There is some overlap in the functionalities of Bib-cite and RefTeX.
526 ;; Bib-cite.el comes bundled with AUCTeX. You can also get the latest
527 ;; version from
528 ;;
529 ;; ftp://ftp.phys.ocean.dal.ca/users/rhogee/elisp/bib-cite.el
530 ;;---------------------------------------------------------------------------
531 ;;
532 ;; KNOWN BUGS AND WORK-AROUNDS
533 ;; ===========================
534 ;;
535 ;; o \input, \include, \bibliography and \section (etc.) statements have
536 ;; to be first on a line (except for white space).
537 ;;
538 ;; o RefTeX sees also labels in regions commented out and will refuse to
539 ;; make duplicates of such a label. This is considered to be a feature.
540 ;;
541 ;; o When using partial scans (`reftex-enable-partial-scans'), the section
542 ;; numbers in the table of contents may eventually become wrong. A full
543 ;; scan will fix this.
544 ;;
545 ;; o RefTeX keeps only a global copy of the configuration variables.
546 ;; Also, any additions from style files go into a global variable.
547 ;; Practically, this should not be a problem. Theoretically, it could
548 ;; give conflicts if two documents used environments with identical
549 ;; names, but different associated label types.
550 ;;
551 ;; o When using packages which make the buffer representation of a file
552 ;; different from its disk representation (e.g. x-symbol, isotex,
553 ;; iso-cvt) you may find that RefTeX's parsing information sometimes
554 ;; reflects the disk state of a file. This happens only in *unvisited*
555 ;; parts of a multifile document, because RefTeX visits these files
556 ;; literally for speed reasons. Then both short context and section
557 ;; headings may look different from what you usually see on your screen.
558 ;; In rare cases `reftex-toc' may have problems to jump to an affected
559 ;; section heading. There are three possible ways to deal with this:
560 ;;
561 ;; - (setq reftex-keep-temporary-buffers t)
562 ;; This implies that RefTeX will load all parts of a multifile
563 ;; document into Emacs (i.e. there will be no temporary buffers).
564 ;; - (setq reftex-initialize-temporary-buffers t)
565 ;; This means full initialization of temporary buffers. It involves
566 ;; a penalty when the same file is used for lookup often.
567 ;; - Set `reftex-initialize-temporary-buffers' to a list of hook
568 ;; functions doing a minimal initialization.
569 ;;
570 ;; You might also want to check the variable `reftex-refontify-context'.
571 ;;
572 ;; o Some nasty :-# packages use an additional argument to a \begin macro
573 ;; to specify a label. E.g. Lamport's "pf.sty" uses both
574 ;;
575 ;; \step{LABEL}{CLAIM} and \begin{step+}{LABEL}
576 ;; CLAIM
577 ;; \end{step+}
578 ;;
579 ;; We need to trick RefTeX into swallowing this:
580 ;;
581 ;; ;; Configuration for Lamport's pf.sty
582 ;; (setq reftex-label-alist
583 ;; '(("\\step{*}{}" ?p "st:" "~\\stepref{%s}" 2 ("Step" "St."))
584 ;; ("\\begin{step+}{*}" ?p "st:" "~\\stepref{%s}" 1000)))
585 ;;
586 ;; The first line is just a normal configuration for a macro. For the
587 ;; `step+' environment we actually tell RefTeX to look for the *macro*
588 ;; "\begin{step+}" and interprete the *first* argument (which in reality
589 ;; is a second argument to the macro \begin) as a label of type ?p.
590 ;; Argument count for this macro starts only after the {step+}, also
591 ;; when specifying how to get context.
592 ;;
593 ;; o In XEmacs 19.15, the overlay library has a bug. RefTeX does not
594 ;; suffer from it, but since it loads the library, other packages like
595 ;; GNUS will switch from extents to overlays and hit the bug. Upgrade
596 ;; to XEmacs 20, or fix the overlay library (in line 180 of overlay.el,
597 ;; change `(list before after)' to `(cons before after)').
598 ;;---------------------------------------------------------------------------
599 ;;
600 ;; AUTHOR
601 ;; ======
602 ;;
603 ;; Carsten Dominik <dominik@strw.LeidenUniv.nl>
604 ;;
605 ;; with contributions from Stephen Eglen
606 ;;
607 ;; The newest version of RefTeX can be found at
608 ;;
609 ;; http://www.strw.leidenuniv.nl/~dominik/Tools/
610 ;; ftp://strw.leidenuniv.nl/pub/dominik/
611 ;;
612 ;; THANKS TO:
613 ;; ---------
614 ;; At least the following people have invested time to test and bug-fix
615 ;; reftex.el. Some have send patches for fixes or new features, or came
616 ;; up with useful ideas.
617 ;;
618 ;; Stephen Eglen <stephene@cogs.susx.ac.uk>
619 ;; F.E. Burstall <F.E.Burstall@maths.bath.ac.uk>
620 ;; Karl Eichwalder <ke@ke.Central.DE>
621 ;; Laurent Mugnier <mugnier@onera.fr>
622 ;; Rory Molinari <molinari@yunt.math.lsa.umich.edu>
623 ;; Soren Dayton <csdayton@cs.uchicago.edu>
624 ;; Daniel Polani <polani@Informatik.Uni-Mainz.DE>
625 ;; Allan Strand <astrand@trillium.NMSU.Edu>
626 ;; Adrian Lanz <lanz@waho.ethz.ch>
627 ;; Jan Vroonhof <vroonhof@math.ethz.ch>
628 ;; Alastair Burt <alastair.burt@dfki.de>
629 ;; Dieter Kraft <dkraft@acm.org>
630 ;; Robin S. Socha <r.socha@franck.pc.uni-koeln.de>
631 ;;
632 ;; The view crossref feature was inspired by the similar function in
633 ;; Peter S. Galbraith's bib-cite.el.
634 ;;
635 ;; Finally thanks to Uwe Bolick <bolick@physik.tu-berlin.de> who first
636 ;; got me (some years ago) into supporting LaTeX labels and references
637 ;; with an Editor (which was MicroEmacs at the time).
638 ;;
639 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
640 ;;
641 \f
642 ;;; Code:
643
644 (eval-when-compile (require 'cl))
645
646 ;; Stuff that needs to be there when we use defcustom
647 ;; --------------------------------------------------
648
649 (require 'custom)
650
651 (defvar reftex-tables-dirty t
652 "Flag showing if tables need to be re-computed.")
653
654 (eval-and-compile
655 (defun reftex-set-dirty (symbol value)
656 (setq reftex-tables-dirty t)
657 (set symbol value)))
658
659 (eval-and-compile
660 (defmacro reftex-fp (n)
661 (if (fboundp 'forward-point)
662 (list 'forward-point n)
663 (list '+ '(point) n))))
664
665 ;;; Begin of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
666
667 ;; Define the two constants which are needed during compilation
668
669 (eval-and-compile
670 (defconst reftex-label-alist-builtin
671 '(
672 ;; Some aliases, mostly for backward compatibility
673 (Sideways "Alias for -->rotating" (rotating))
674 (AMSTeX "amsmath with eqref macro"
675 ((nil ?e nil "~\\eqref{%s}")
676 amsmath))
677
678 ;; Individual package defaults
679 (amsmath "AMS-LaTeX math environments"
680 (("align" ?e nil nil eqnarray-like)
681 ("gather" ?e nil nil eqnarray-like)
682 ("multline" ?e nil nil t)
683 ("flalign" ?e nil nil eqnarray-like)
684 ("alignat" ?e nil nil alignat-like)
685 ("xalignat" ?e nil nil alignat-like)
686 ("xxalignat" ?e nil nil alignat-like)
687 ("subequations" ?e nil nil t)))
688
689 (endnotes "The \\endnote macro"
690 (("\\endnote[]{}" ?n nil nil 2 ("Endnote"))))
691
692 (fancybox "The Beqnarray environment"
693 (("Beqnarray" ?e nil nil eqnarray-like)))
694
695 (floatfig "The floatingfigure environment"
696 (("floatingfigure" ?f nil nil caption)))
697
698 (longtable "The longtable environment"
699 (("longtable" ?t nil nil caption)))
700
701 (picinpar "The figwindow and tabwindow environments"
702 (("figwindow" ?f nil nil 1)
703 ("tabwindow" ?f nil nil 1)))
704
705 (rotating "Sidewaysfigure and table"
706 (("sidewaysfigure" ?f nil nil caption)
707 ("sidewaystable" ?t nil nil caption)))
708
709 (subfigure "Subfigure environments/macro"
710 (("subfigure" ?f nil nil caption)
711 ("subfigure*" ?f nil nil caption)
712 ("\\subfigure[]{}" ?f nil nil 1)))
713
714 (supertab "Supertabular environment"
715 (("supertabular" ?t nil nil "\\tablecaption{")))
716
717 (wrapfig "The wrapfigure environment"
718 (("wrapfigure" ?f nil nil caption)))
719
720 ;; The LaTeX core stuff
721 (LaTeX "LaTeX default environments"
722 (("section" ?s "sec:" "~\\ref{%s}" (nil . t)
723 ("Part" "Chapter" "Chap." "Section" "Sec." "Sect." "Paragraph" "Par."
724 "\\S" "Teil" "Kapitel" "Kap." "Abschnitt" ))
725
726 ("enumerate" ?i "item:" "~\\ref{%s}" item
727 ("Item" "Punkt"))
728
729 ("equation" ?e "eq:" "~(\\ref{%s})" t
730 ("Equation" "Eq." "Eqn." "Gleichung" "Gl."))
731 ("eqnarray" ?e "eq:" nil eqnarray-like)
732
733 ("figure" ?f "fig:" "~\\ref{%s}" caption
734 ("Figure" "Fig." "Abbildung" "Abb."))
735 ("figure*" ?f nil nil caption)
736
737 ("table" ?t "tab:" "~\\ref{%s}" caption
738 ("Table" "Tab." "Tabelle"))
739 ("table*" ?t nil nil caption)
740
741 ("\\footnote[]{}" ?n "note:" "~\\ref{%s}" 2
742 ("Footnote" "Note"))
743
744 ("any" ?\ " " "\\ref{%s}" nil)))
745
746 )
747 "The default label environment descriptions.
748 Lower-case symbols correspond to a style file of the same name in the LaTeX
749 distribution. Mixed-case symbols are convenience aliases.")
750
751 (defconst reftex-cite-format-builtin
752 '(
753 (default "Default macro \\cite{%l}"
754 "\\cite{%l}")
755 (natbib "The Natbib package"
756 ((?\C-m . "\\cite{%l}")
757 (?t . "\\citet{%l}")
758 (?T . "\\citet*{%l}")
759 (?p . "\\citep{%l}")
760 (?P . "\\citep*{%l}")
761 (?e . "\\citep[e.g.][]{%l}")
762 (?a . "\\citeauthor{%l}")
763 (?y . "\\citeyear{%l}")))
764 (harvard "The Harvard package"
765 ((?\C-m . "\\cite{%l}")
766 (?p . "\\cite{%l}")
767 (?t . "\\citeasnoun{%l}")
768 (?n . "\\citeasnoun{%l}")
769 (?s . "\\possessivecite{%l}")
770 (?e . "\\citeaffixed{%l}{?}")
771 (?y . "\\citeyear{%l}")
772 (?a . "\\citename{%l}")))
773 (chicago "The Chicago package"
774 ((?\C-m . "\\cite{%l}")
775 (?t . "\\citeN{%l}")
776 (?T . "\\shortciteN{%l}")
777 (?p . "\\cite{%l}")
778 (?P . "\\shortcite{%l}")
779 (?a . "\\citeA{%l}")
780 (?A . "\\shortciteA{%l}")
781 (?y . "\\citeyear{key}")))
782 (astron "The Astron package"
783 ((?\C-m . "\\cite{%l}")
784 (?p . "\\cite{%l}" )
785 (?t . "%2a (\\cite{%l})")))
786 (author-year "Do-it-yourself Author-year"
787 ((?\C-m . "\\cite{%l}")
788 (?t . "%2a (%y)\\nocite{%l}")
789 (?p . "(%2a %y\\nocite{%l})")))
790 (locally "Full info in parenthesis"
791 "(%2a %y, %j %v, %P, %e: %b, %u, %s %<)")
792 ;; undocumented feature: `%<' kills white space and punctuation locally.
793 )
794 "Builtin versions of for the citation format.
795 The following conventions are valid for all alist entries:
796 `?\C-m' should always point to a straight \\cite{%l} macro.
797 `?t' should point to a textual citation (citation as a noun).
798 `?p' should point to a parenthetical citation.")
799 )
800
801 ;; Configuration Variables and User Options for RefTeX ------------------
802
803 (defgroup reftex nil
804 "LaTeX label and citation support."
805 :tag "RefTeX"
806 :link '(url-link :tag "Home Page"
807 "http://strw.leidenuniv.nl/~dominik/Tools/")
808 :link '(emacs-commentary-link :tag "Commentary in reftex.el" "reftex.el")
809 :prefix "reftex-"
810 :group 'tex)
811
812 (defun reftex-customize ()
813 "Call the customize function with reftex as argument."
814 (interactive)
815 ;; Depending on the customize version we can call different functions.
816 (cond
817 ((fboundp 'customize-browse)
818 (customize-browse 'reftex))
819 ((fboundp 'customize-group)
820 (customize-group 'reftex))
821 ((fboundp 'customize)
822 (customize 'reftex))
823 (t (error "Custom.el not available"))))
824
825 (defun reftex-show-commentary ()
826 "Use the finder to view the file documentation from `reftex.el'."
827 (interactive)
828 (require 'finder)
829 (finder-commentary "reftex.el"))
830
831 ;; Support for \label and \ref --------------------------------------
832
833 (defgroup reftex-label-support nil
834 "Support for creation, insertion and referencing of labels in LaTeX."
835 :group 'reftex)
836
837 (defgroup reftex-defining-label-environments nil
838 "Definition of environments and macros to do with label."
839 :group 'reftex-label-support)
840
841 ;; Make a constant for the customization stuff
842 (eval-and-compile
843 (defconst reftex-tmp
844 '((const :tag "Default position" t)
845 (const :tag "After label" nil)
846 (number :tag "Macro arg nr" 1)
847 (regexp :tag "Regexp" "")
848 (const :tag "Caption in float" caption)
849 (const :tag "Item in list" item)
850 (const :tag "Eqnarray-like" eqnarray-like)
851 (const :tag "Alignat-like" alignat-like)
852 (symbol :tag "Function" my-func))))
853
854 (defcustom reftex-default-label-alist-entries
855 '(amsmath endnotes fancybox floatfig longtable picinpar
856 rotating subfigure supertab wrapfig LaTeX)
857 "Default label alist specifications. LaTeX should be the last entry.
858 This list describes the default label environments RefTeX should always use.
859 It is probably a mistake to remove the LaTeX symbol from this list.
860
861 The options include:
862 LaTeX The standard LaTeX environments.
863 Sideways The sidewaysfigure and sidewaystable environments.
864 AMSTeX The math environments in the AMS-LaTeX amsmath package.
865
866 For the full list of options, try
867
868 M-x customize-variable RET reftex-default-label-alist-entries RET."
869 :group 'reftex-defining-label-environments
870 :set 'reftex-set-dirty
871 :type `(set
872 :indent 4
873 :inline t
874 :greedy t
875 ,@(mapcar
876 (function
877 (lambda (x)
878 (list 'const ':tag (concat (symbol-name (nth 0 x))
879 ": " (nth 1 x))
880 (nth 0 x))))
881 reftex-label-alist-builtin)))
882
883 (defcustom reftex-label-alist nil
884 "Alist with information on environments for \\label-\\ref use.
885
886 This docstring is easier to understand after reading the configuration
887 examples in `reftex.el'. Looking at the builtin defaults in the constant
888 `reftex-label-alist-builtin' may also be instructive.
889
890 Set this variable to define additions and changes to the default. The only
891 things you MUST NOT change is that `?s' is the type indicator for section
892 labels, and SPC for the `any' label type. These are hard-coded at other
893 places in the code.
894
895 Each list entry describes either an environment carrying a counter for use
896 with \\label and \\ref, or a LaTeX macro defining a label as (or inside)
897 one of its arguments. The elements of each list entry are:
898
899 0. Name of the environment (like \"table\") or macro (like \"\\\\myfig\").
900 For macros, indicate the macro arguments for best results, as in
901 \"\\\\myfig[]{}{}{*}{}\". Use square brackets for optional arguments,
902 a star to mark the label argument, if any. The macro does not have to
903 have a label argument - you could also use \\label{..} inside one of
904 its arguments.
905 Special names: `section' for section labels, `any' to define a group
906 which contains all labels.
907 This may also be nil if the entry is only meant to change some settings
908 associated with the type indicator character (see below).
909
910 1. Type indicator character, like `?t', must be a printable ASCII character.
911 The type indicator is a single character which defines a label type.
912 Any label inside the environment or macro is assumed to belong to this
913 type. The same character may occur several times in this list, to cover
914 cases in which different environments carry the same label type (like
915 `equation' and `eqnarray').
916
917 2. Label prefix string, like \"tab:\".
918 The prefix is a short string used as the start of a label. It may be the
919 empty string. The prefix may contain the following `%' escapes:
920 %f Current file name with directory and extension stripped.
921 %F Current file name relative to directory of master file.
922 %u User login name, on systems which support this.
923
924 Example: In a file `intro.tex', \"eq:%f:\" will become \"eq:intro:\").
925
926 3. Format string for reference insert in buffer. `%s' will be replaced by
927 the label.
928 When the format starts with `~', whitespace before point will be removed
929 so that the reference cannot be separated from the word before it.
930
931 4. Indication on how to find the short context.
932 - If nil, use the text following the \\label{...} macro.
933 - If t, use
934 - the section heading for section labels.
935 - text following the \\begin{...} statement of environments.
936 (not a good choice for environments like eqnarray or enumerate,
937 where one has several labels in a single environment).
938 - text after the macro name (stearting with the first arg) for macros.
939 - If an integer, use the nth argument of the macro. As a special case,
940 1000 means to get text after the last macro argument.
941 - If a string, use as regexp to search *backward* from the label. Context
942 is then the text following the end of the match. E.g. putting this to
943 \"\\\\\\\\caption[[{]\" will use the caption in a figure or table
944 environment.
945 \"\\\\\\\\begin{eqnarray}\\\\|\\\\\\\\\\\\\\\\\" works for eqnarrays.
946 - If any of `caption', `item', `eqnarray-like', `alignat-like', this
947 symbol will internally be translated into an appropriate regexp
948 (see also the variable `reftex-default-context-regexps').
949 - If a function, call this function with the name of the environment/macro
950 as argument. On call, point will be just after the \\label macro. The
951 function is expected to return a suitable context string. It should
952 throw an exception (error) when failing to find context.
953 As an example, here is a function returning the 10 chars following
954 the label macro as context:
955
956 (defun my-context-function (env-or-mac)
957 (if (> (point-max) (+ 10 (point)))
958 (buffer-substring (point) (+ 10 (point)))
959 (error \"Buffer too small\")))
960
961 Label context is used in two ways by RefTeX: For display in the label
962 menu, and to derive a label string. If you want to use a different
963 method for each of these, specify them as a dotted pair.
964 E.g. `(nil . t)' uses the text after the label (nil) for display, and
965 text from the default position (t) to derive a label string. This is
966 actually used for section labels.
967
968 Setting the variable `reftex-use-text-after-label-as-context' to t
969 overrides the setting here.
970
971 5. List of magic words which identify a reference to be of this type.
972 If the word before point is equal to one of these words when calling
973 `reftex-reference', the label list offered will be automatically
974 restricted to labels of the correct type.
975
976 If the type indicator characters of two or more entries are the same, RefTeX
977 will use
978 - the first non-nil format and prefix
979 - the magic words of all involved entries.
980
981 Any list entry may also be a symbol. If that has an association in
982 `reftex-label-alist-builtin', the cdr of that association is spliced into the
983 list. However, builtin defaults should normally be set here but with the
984 variable `reftex-default-label-alist-entries."
985 :group 'reftex-defining-label-environments
986 :set 'reftex-set-dirty
987 :type
988 `(repeat
989 (choice
990 :value ("" ?a nil nil nil nil)
991 (list :tag "Detailed label alist entry"
992 :value ("" ?a nil nil nil nil)
993 (choice :tag "Environment or \\macro "
994 (const :tag "Ignore, just use typekey" nil)
995 (string ""))
996 (character :tag "Typekey character " ?a)
997 (choice :tag "Label prefix string "
998 (const :tag "Default" nil)
999 (string :tag "String" "lab:"))
1000 (choice :tag "Label reference format"
1001 (const :tag "Default" nil)
1002 (string :tag "String" "~\\ref{%s}"))
1003 (choice :tag "Context"
1004 (choice
1005 :tag "1 method"
1006 ,@reftex-tmp)
1007 (cons :tag "Split methods"
1008 (choice
1009 :tag " Display context "
1010 ,@reftex-tmp)
1011 (choice
1012 :tag " Derive label context"
1013 ,@reftex-tmp)))
1014 (repeat :tag "List of Magic Words" (string)))
1015 (choice
1016 :tag "Package"
1017 :value AMSTeX
1018 ,@(mapcar
1019 (function
1020 (lambda (x)
1021 (list 'const ':tag (concat (symbol-name (nth 0 x))); ": " (nth 1 x))
1022 (nth 0 x))))
1023 reftex-label-alist-builtin)))))
1024
1025 ;; LaTeX section commands and level numbers
1026 (defcustom reftex-section-levels
1027 '(
1028 ("part" . 0)
1029 ("chapter" . 1)
1030 ("section" . 2)
1031 ("subsection" . 3)
1032 ("subsubsection" . 4)
1033 ("paragraph" . 5)
1034 ("subparagraph" . 6)
1035 ("subsubparagraph" . 7)
1036 )
1037 "Commands and levels used for defining sections in the document.
1038 The car of each cons cell is the name of the section macro. The cdr is a
1039 number indicating its level."
1040 :group 'reftex-defining-label-environments
1041 :set 'reftex-set-dirty
1042 :type '(repeat
1043 (cons (string :tag "sectioning macro" "")
1044 (number :tag "level " 0))))
1045
1046 (defcustom reftex-default-context-regexps
1047 '((caption . "\\\\\\(rot\\)?caption\\*?[[{]")
1048 (item . "\\\\item\\(\\[[^]]*\\]\\)?")
1049 (eqnarray-like . "\\\\begin{%s}\\|\\\\\\\\")
1050 (alignat-like . "\\\\begin{%s}{[0-9]*}\\|\\\\\\\\"))
1051 "Alist with default regular expressions for finding context.
1052 The form (format regexp (regexp-quote environment)) is used to calculate
1053 the final regular expression - so %s will be replaced with the environment
1054 or macro."
1055 :group 'reftex-defining-label-environments
1056 :type '(repeat (cons (symbol) (regexp))))
1057
1058 (defcustom reftex-use-text-after-label-as-context nil
1059 "*t means, grab context from directly after the \\label{..} macro.
1060 This is the fastest method for obtaining context of the label definition, but
1061 requires discipline when placing labels. Setting this variable to t takes
1062 precedence over the individual settings in `reftex-label-alist'.
1063 This variable may be set to t, nil, or a string of label type letters
1064 indicating the label types for which it should be true."
1065 :group 'reftex-defining-label-environments
1066 :set 'reftex-set-dirty
1067 :type '(choice
1068 (const :tag "on" t) (const :tag "off" nil)
1069 (string :tag "Selected label types")))
1070
1071 ;; Label insertion
1072
1073 (defgroup reftex-making-and-inserting-labels nil
1074 "Options on how to create new labels."
1075 :group 'reftex-label-support)
1076
1077 (defcustom reftex-insert-label-flags '("s" "sft")
1078 "Flags governing label insertion. First flag DERIVE, second flag PROMPT.
1079
1080 If DERIVE is t, RefTeX will try to derive a sensible label from context.
1081 A section label for example will be derived from the section heading.
1082 The conversion of the context to a legal label is governed by the
1083 specifications given in `reftex-derive-label-parameters'.
1084 If RefTeX fails to derive a label, it will prompt the user.
1085 If DERIVE is nil, the label generated will consist of the prefix and a
1086 unique number, like `eq:23'.
1087
1088 If PROMPT is t, the user will be prompted for a label string. The prompt will
1089 already contain the prefix, and (if DERIVE is t) a default label derived from
1090 context. When PROMPT is nil, the default label will be inserted without
1091 query.
1092
1093 So the combination of DERIVE and PROMPT controls label insertion. Here is a
1094 table describing all four possibilities:
1095
1096 DERIVE PROMPT ACTION
1097 -------------------------------------------------------------------------
1098 nil nil Insert simple label, like eq:22 or sec:13. No query.
1099 nil t Prompt for label.
1100 t nil Derive a label from context and insert without query.
1101 t t Derive a label from context and prompt for confirmation.
1102
1103 Each flag may be set to t, nil, or a string of label type letters
1104 indicating the label types for which it should be true.
1105 Thus, the combination may be set differently for each label type. The
1106 default settings \"s\" and \"sft\" mean: Derive section labels from headings
1107 (with confirmation). Prompt for figure and table labels. Use simple labels
1108 without confirmation for everything else."
1109 :group 'reftex-making-and-inserting-labels
1110 :type '(list (choice :tag "Derive label from context"
1111 (const :tag "always" t)
1112 (const :tag "never" nil)
1113 (string :tag "selected label types" ""))
1114 (choice :tag "Prompt for label string "
1115 :entry-format " %b %v"
1116 (const :tag "always" t)
1117 (const :tag "never" nil)
1118 (string :tag "selected label types" ""))))
1119
1120 (defcustom reftex-derive-label-parameters '(3 20 t 1 "-"
1121 ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is"))
1122 "Parameters for converting a string into a label.
1123 NWORDS Number of words to use.
1124 MAXCHAR Maximum number of characters in a label string.
1125 ILLEGAL nil: Throw away any words containing characters illegal in labels.
1126 t: Throw away only the illegal characters, not the whole word.
1127 ABBREV nil: Never abbreviate words.
1128 t: Always abbreviate words (see `reftex-abbrev-parameters').
1129 not t and not nil: Abbreviate words if necessary to shorten
1130 label string below MAXCHAR.
1131 SEPARATOR String separating different words in the label.
1132 IGNOREWORDS List of words which should not be part of labels."
1133 :group 'reftex-making-and-inserting-labels
1134 :type '(list (integer :tag "Number of words " 3)
1135 (integer :tag "Maximum label length " 20)
1136 (choice :tag "Illegal characters in words"
1137 (const :tag "throw away entire word" nil)
1138 (const :tag "throw away single chars" t))
1139 (choice :tag "Abbreviate words "
1140 (const :tag "never" nil)
1141 (const :tag "always" t)
1142 (const :tag "when label is too long" 1))
1143 (string :tag "Separator between words " "-")
1144 (repeat :tag "Ignore words"
1145 :entry-format " %i %d %v"
1146 (string :tag ""))))
1147
1148 (defcustom reftex-label-illegal-re "[\000-\040\177-\377\\\\#$%&~^_{}]"
1149 "Regexp matching characters not legal in labels.
1150 For historic reasons, this character class comes *with* the [] brackets."
1151 :group 'reftex-making-and-inserting-labels
1152 :type '(regexp :tag "Character class"))
1153
1154 (defcustom reftex-abbrev-parameters '(4 2 "^saeiou" "aeiou")
1155 "Parameters for abbreviation of words.
1156 MIN-CHARS Minimum number of characters remaining after abbreviation.
1157 MIN-KILL Minimum number of characters to remove when abbreviating words.
1158 BEFORE Character class before abbrev point in word.
1159 AFTER Character class after abbrev point in word."
1160 :group 'reftex-making-and-inserting-labels
1161 :type '(list
1162 (integer :tag "Minimum chars per word" 4)
1163 (integer :tag "Shorten by at least " 2)
1164 (string :tag "cut before char class " "^saeiou")
1165 (string :tag "cut after char class " "aeiou")))
1166
1167 ;; Label referencing
1168
1169 (defgroup reftex-referencing-labels nil
1170 "Options on how to reference labels."
1171 :group 'reftex-label-support)
1172
1173 (eval-and-compile
1174 (defconst reftex-tmp
1175 '((const :tag "on" t)
1176 (const :tag "off" nil)
1177 (string :tag "Selected label types"))))
1178
1179 (defcustom reftex-label-menu-flags '(t t nil nil nil nil t nil)
1180 "List of flags governing the label menu makeup.
1181 The flags are:
1182
1183 TABLE-OF-CONTENTS Show the labels embedded in a table of context.
1184 SECTION-NUMBERS Include section numbers (like 4.1.3) in table of contents.
1185 COUNTERS Show counters. This just numbers the labels in the menu.
1186 NO-CONTEXT Non-nil means do NOT show the short context.
1187 FOLLOW Follow full context in other window.
1188 SHOW-COMMENTED Show labels from regions which are commented out.
1189 MATCH-IN-TOC Searches in label menu will also match in toc lines.
1190 SHOW FILES Show Begin and end of included files.
1191
1192 Each of these flags can be set to t or nil, or to a string of type letters
1193 indicating the label types for which it should be true. These strings work
1194 like character classes in regular expressions. Thus, setting one of the
1195 flags to \"sf\" makes the flag true for section and figure labels, nil
1196 for everything else. Setting it to \"^ft\" makes it the other way round.
1197
1198 Most options can also be switched from the label menu itself - so if you
1199 decide here to not have a table of contents in the label menu, you can still
1200 get one interactively during selection from the label menu."
1201 :group 'reftex-referencing-labels
1202 :type
1203 `(list
1204 (choice :tag "Embed in table of contents " ,@reftex-tmp)
1205 (choice :tag "Show section numbers " ,@reftex-tmp)
1206 (choice :tag "Show individual counters " ,@reftex-tmp)
1207 (choice :tag "Hide short context " ,@reftex-tmp)
1208 (choice :tag "Follow context in other window " ,@reftex-tmp)
1209 (choice :tag "Show commented labels " ,@reftex-tmp)
1210 (choice :tag "Searches match in toc lines " ,@reftex-tmp)
1211 (choice :tag "Show begin/end of included files" ,@reftex-tmp)))
1212
1213 (defcustom reftex-level-indent 2
1214 "*Number of spaces to be used for indentation per section level."
1215 :group 'reftex-referencing-labels
1216 :type '(integer))
1217
1218 (defcustom reftex-refontify-context 1
1219 "*Non-nil means, re-fontify the context in the label menu with font-lock.
1220 This slightly slows down the creation of the label menu. It is only necessay
1221 when you definitely want the context fontified.
1222
1223 This option may have 3 different values:
1224 nil Never refontify.
1225 t Always refontify.
1226 1 Refontify when absolutly necessary, e.g. when with the x-symbol package.
1227 The option is ignored when `reftex-use-fonts' is nil."
1228 :group 'reftex-referencing-labels
1229 :type '(choice
1230 (const :tag "Never" nil)
1231 (const :tag "Always" t)
1232 (const :tag "When necessary" 1)))
1233
1234 (defcustom reftex-guess-label-type t
1235 "*Non-nil means, `reftex-reference' will try to guess the label type.
1236 To do that, RefTeX will look at the word before the cursor and compare it with
1237 the words given in `reftex-label-alist'. When it finds a match, RefTeX will
1238 immediately offer the correct label menu - otherwise it will prompt you for
1239 a label type. If you set this variable to nil, RefTeX will always prompt."
1240 :group 'reftex-referencing-labels
1241 :type '(boolean))
1242
1243 ;; BibteX citation configuration ----------------------------------------
1244
1245 (defgroup reftex-citation-support nil
1246 "Support for referencing bibliographic data with BibTeX."
1247 :group 'reftex)
1248
1249 (defcustom reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB")
1250 "*List of env vars which might contain the path to BibTeX database files."
1251 :group 'reftex-citation-support
1252 :set 'reftex-set-dirty
1253 :type '(repeat (string :tag "Environment variable")))
1254
1255 (defcustom reftex-bibfile-ignore-list nil
1256 "*List of files in \\bibliography{..} RefTeX should *not* parse.
1257 The file names have to be in the exact same form as in the bibliography
1258 macro - i.e. without the `.bib' extension.
1259 Intended for files which contain only `@string' macro definitions and the
1260 like, which are ignored by RefTeX anyway."
1261 :group 'reftex-citation-support
1262 :set 'reftex-set-dirty
1263 :type '(repeat (string :tag "File name")))
1264
1265 (defcustom reftex-sort-bibtex-matches 'reverse-year
1266 "*Sorting of the entries found in BibTeX databases by reftex-citation.
1267 Possible values:
1268 nil Do not sort entries.
1269 'author Sort entries by author name.
1270 'year Sort entries by increasing year.
1271 'reverse-year Sort entries by decreasing year."
1272 :group 'reftex-citation-support
1273 :type '(choice (const :tag "not" nil)
1274 (const :tag "by author" author)
1275 (const :tag "by year" year)
1276 (const :tag "by year, reversed" reverse-year)))
1277
1278 (defcustom reftex-cite-format 'default
1279 "*The format of citations to be inserted into the buffer.
1280 It can be a string or an alist. In the simplest case this is just
1281 the string \"\\cite{%l}\", which is also the default. See the
1282 definition of `reftex-cite-format-builtin' for more complex examples.
1283
1284 If `reftex-cite-format' is a string, it will be used as the format.
1285 In the format, the following percent escapes will be expanded.
1286
1287 %l The BibTeX label of the citation.
1288 %a List of author names, see also `reftex-cite-punctuation.
1289 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
1290 %A First author name only.
1291 %e Works like %a, but on list of editor names. (%2e and %E work a well)
1292
1293 It is also possible to access all other BibTeX database fields:
1294 %b booktitle %c chapter %d edition %h howpublished
1295 %i institution %j journal %k key %m month
1296 %n number %o organization %p pages %P first page
1297 %r address %s school %u publisher %t title
1298 %v volume %y year
1299
1300 Usually, only %l is needed. Try, however, (setq reftex-comment-citations t).
1301
1302 If `reftex-cite-format' is an alist of characters and strings, the user
1303 will be prompted for a character to select one of the possible format
1304 strings.
1305 In order to configure this variable, you can either set
1306 `reftex-cite-format' directly yourself or set it to the SYMBOL of one of
1307 the predefined styles (see `reftex-cite-format-builtin'). E.g.:
1308 (setq reftex-cite-format 'harvard)"
1309 :group 'reftex-citation-support
1310 :type
1311 `(choice
1312 :format "%{%t%}: \n%[Value Menu%] %v"
1313 (radio :tag "Symbolic Builtins"
1314 :indent 4
1315 :value default
1316 ,@(mapcar
1317 (function
1318 (lambda (x)
1319 (list 'const ':tag (concat (symbol-name (nth 0 x))
1320 ": " (nth 1 x))
1321 (nth 0 x))))
1322 reftex-cite-format-builtin))
1323 (string :tag "format string" "\\cite{%l}")
1324 (repeat :tag "key-ed format strings"
1325 :value ((?\r . "\\cite{%l}")
1326 (?t . "\\cite{%l}") (?p . "\\cite{%l}"))
1327 (cons (character :tag "Key character" ?\r)
1328 (string :tag "Format string" "")))))
1329
1330 (defcustom reftex-comment-citations nil
1331 "*Non-nil means add a comment for each citation describing the full entry.
1332 The comment is formatted according to `reftex-cite-comment-format'."
1333 :group 'reftex-citation-support
1334 :type '(boolean))
1335
1336 (defcustom reftex-cite-comment-format
1337 "%% %2a %y, %j %v, %P, %e: %b, %u, %s %<\n"
1338 "Citation format used for commented citations. Must NOT contain %l."
1339 :group 'reftex-citation-support
1340 :type '(string))
1341
1342 (defcustom reftex-cite-punctuation '(", " " \\& " " {\\it et al.}")
1343 "Punctuation for formatting of name lists in citations.
1344 This is a list of 3 strings.
1345 1. normal names separator, like \", \" in Jones, Brown and Miller
1346 2. final names separator, like \" and \" in Jones, Brown and Miller
1347 3. The \"et al\" string, like \" {...}\" in Jones {\\it et al.}"
1348 :group 'reftex-citation-support
1349 :type '(list
1350 (string :tag "Separator for names ")
1351 (string :tag "Separator for last name in list")
1352 (string :tag "string used as et al. ")))
1353
1354 ;; Table of contents configuration --------------------------------------
1355
1356 (defgroup reftex-table-of-contents-browser nil
1357 "A multifile table of contents browser."
1358 :group 'reftex)
1359
1360 (defcustom reftex-toc-follow-mode nil
1361 "*Non-nil means, point in *toc* buffer will cause other window to follow.
1362 The other window will show the corresponding part of the document.
1363 This flag can be toggled from within the *toc* buffer with the `f' key."
1364 :group 'reftex-table-of-contents-browser
1365 :type '(boolean))
1366
1367 ;; Tuning the parser ----------------------------------------------------
1368
1369 (defgroup reftex-optimizations-for-large-documents nil
1370 "Configuration of parser speed and memory usage."
1371 :group 'reftex)
1372
1373 (defcustom reftex-keep-temporary-buffers 1
1374 "*Non-nil means, keep buffers created for parsing and lookup.
1375 RefTeX sometimes needs to visit files related to the current document.
1376 We distinguish files visited for
1377 PARSING: Parts of a multifile document loaded when (re)-parsing the document.
1378 LOOKUP: BibTeX database files and TeX files loaded to find a reference,
1379 to display label context, etc.
1380 The created buffers can be kept for later use, or be thrown away immediately
1381 after use, depending on the value of this variable:
1382
1383 nil Throw away as much as possible.
1384 t Keep everything.
1385 1 Throw away buffers created for parsing, but keep the ones created
1386 for lookup.
1387
1388 If a buffer is to be kept, the file is visited normally (which is potentially
1389 slow but will happen only once).
1390 If a buffer is to be thrown away, the initialization of the buffer depends
1391 upon the variable `reftex-initialize-temporary-buffers'."
1392 :group 'reftex-miscellaneous-configurations
1393 :type '(choice
1394 (const :tag "Throw away everything" nil)
1395 (const :tag "Keep everything" t)
1396 (const :tag "Keep lookup buffers only" 1)))
1397
1398 (defcustom reftex-initialize-temporary-buffers nil
1399 "*Non-nil means do initializations even when visiting file temporarily.
1400 When nil, RefTeX may turn off find-file hooks and other stuff to briefly
1401 visit a file.
1402 When t, the full default initializations are done (find-file-hook etc.).
1403 Instead of t or nil, this variable may also be a list of hook functions to
1404 do a minimal initialization."
1405 :group 'reftex-miscellaneous-configurations
1406 :type '(choice
1407 (const :tag "Read files literally" nil)
1408 (const :tag "Fully initialize buffers" t)
1409 (repeat :tag "Hook functions" :value (nil)
1410 (function-item))))
1411
1412 (defcustom reftex-enable-partial-scans nil
1413 "*Non-nil means, re-parse only 1 file when asked to re-parse.
1414 Re-parsing is normally requested with a `C-u' prefix to many RefTeX commands,
1415 or with the `r' key in menus. When this option is t in a multifile document,
1416 we will only parse the current buffer, or the file associated with the label
1417 or section heading near point in a menu. Requesting re-parsing of an entire
1418 multifile document then requires a `C-u C-u' prefix or the capital `R' key
1419 in menus."
1420 :group 'reftex-optimizations-for-large-documents
1421 :type 'boolean)
1422
1423 (defcustom reftex-save-parse-info nil
1424 "*Non-nil means, save information gathered with parsing in a file.
1425 The file MASTER.rel in the same directory as MASTER.tex is used to save the
1426 information. When this variable is t,
1427 - accessing the parsing information for the first time in an editing session
1428 will read that file (if available) instead of parsing the document.
1429 - each time (part of) the document is rescanned, a new version of the file
1430 is written."
1431 :group 'reftex-optimizations-for-large-documents
1432 :type 'boolean)
1433
1434 ;; Miscellaneous configurations -----------------------------------------
1435
1436 (defgroup reftex-miscellaneous-configurations nil
1437 "Collection of further configurations."
1438 :group 'reftex)
1439
1440 (defcustom reftex-extra-bindings nil
1441 "Non-nil means, make additional key bindings on startup.
1442 These extra bindings are located in the users `C-c letter' map."
1443 :group 'reftex-miscellaneous-configurations
1444 :type '(boolean))
1445
1446 (defcustom reftex-plug-into-AUCTeX nil
1447 "*Plug-in flags for AUCTeX interface.
1448 This variable is a list of 4 boolean flags. When a flag is non-nil, it
1449 means:
1450
1451 Flag 1: use `reftex-label' as `LaTeX-label-function'.
1452 Flag 2: use `reftex-arg-label' as `TeX-arg-label'
1453 Flag 3: use `reftex-arg-ref' as `TeX-arg-ref'
1454 Flag 4: use `reftex-arg-cite' as `TeX-arg-cite'
1455
1456 You may also set the variable itself to t or nil in order to turn all
1457 plug-ins on or off, respectively.
1458 \\<LaTeX-mode-map>`LaTeX-label-function' is the function used for label insertion when you
1459 enter a new environment in AUCTeX with \\[LaTeX-environment].
1460 The `TeX-arg-label' etc. functions are for entering macro arguments during
1461 macro insertion with \\[TeX-insert-macro].
1462 See the AUCTeX documentation for more information.
1463 RefTeX uses `fset' to take over the function calls. Changing the variable
1464 may require a restart of Emacs in order to become effective."
1465 :group 'reftex-miscellaneous-configurations
1466 :type '(choice (const :tag "No plug-ins" nil)
1467 (const :tag "All possible plug-ins" t)
1468 (list
1469 :tag "Individual choice"
1470 :value (nil nil nil nil)
1471 (boolean :tag "Use reftex-label as LaTeX-label-function")
1472 (boolean :tag "Use reftex-arg-label as TeX-arg-label ")
1473 (boolean :tag "Use reftex-arg-ref as TeX-arg-ref ")
1474 (boolean :tag "Use reftex-arg-cite as TeX-arg-cite ")
1475 )))
1476
1477 (defcustom reftex-use-fonts t
1478 "*Non-nil means, use fonts in label menu and on-the-fly help.
1479 Font-lock must be loaded as well to actually get fontified display."
1480 :group 'reftex-miscellaneous-configurations
1481 :type '(boolean))
1482
1483 (defcustom reftex-auto-show-entry 'copy
1484 "*Non-nil means, do something when context in other window is hidden.
1485 Some modes like `outline-mode' or `folding-mode' hide parts of buffers.
1486 When RefTeX is asked to show context for a label definition, and the context
1487 is invisible, it can unhide that section permanently (value t), or copy the
1488 context to a temporary buffer (value 'copy)."
1489 :group 'reftex-miscellaneous-configurations
1490 :type '(radio :value copy
1491 :indent 4
1492 (const :tag "Do nothing" nil)
1493 (const :tag "Unhide section permanently" t)
1494 (const :tag "Copy context to show" copy)))
1495
1496 (defcustom reftex-load-hook nil
1497 "Hook which is being run when loading reftex.el."
1498 :group 'reftex-miscellaneous-configurations
1499 :type 'hook)
1500
1501 (defcustom reftex-mode-hook nil
1502 "Hook which is being run when turning on RefTeX mode."
1503 :group 'reftex-miscellaneous-configurations
1504 :type 'hook)
1505
1506 ;;; End of Configuration Section ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1507
1508 ;;;===========================================================================
1509 ;;;
1510 ;;; Define the formal stuff for a minor mode named RefTeX.
1511 ;;;
1512
1513 ;; This file corresponds to RefTeX version 3.7
1514
1515 (defvar reftex-mode nil
1516 "Determines if RefTeX minor mode is active.")
1517 (make-variable-buffer-local 'reftex-mode)
1518
1519 (defvar reftex-mode-map (make-sparse-keymap)
1520 "Keymap for RefTeX minor mode.")
1521
1522 (defvar reftex-mode-menu nil)
1523
1524 ;;;###autoload
1525 (defun turn-on-reftex ()
1526 "Turn on RefTeX minor mode."
1527 (reftex-mode t))
1528
1529 ;;;###autoload
1530 (defun reftex-mode (&optional arg)
1531 "Minor mode with distinct support for \\label, \\ref and \\cite in LaTeX.
1532
1533 Labels can be created with `\\[reftex-label]' and referenced with `\\[reftex-reference]'.
1534 When referencing, you get a menu with all labels of a given type and
1535 context of the label definition. The selected label is inserted as a
1536 \\ref macro.
1537
1538 Citations can be made with `\\[reftex-citation]' which will use a regular expression
1539 to pull out a *formatted* list of articles from your BibTeX
1540 database. The selected citation is inserted as a \\cite macro.
1541
1542 A Table of Contents of the entire (multifile) document with browsing
1543 capabilities is available with `\\[reftex-toc]'.
1544
1545 Most command have help available on the fly. This help is accessed by
1546 pressing `?' to any prompt mentioning this feature.
1547
1548 Extensive documentation about RefTeX is in the file header of `reftex.el'.
1549 You can view this information with `\\[reftex-show-commentary]'.
1550
1551 \\{reftex-mode-map}
1552 Under X, these and other functions will also be available as `Ref' menu
1553 on the menu bar.
1554
1555 ------------------------------------------------------------------------------"
1556
1557 (interactive "P")
1558 (setq reftex-mode (not (or (and (null arg) reftex-mode)
1559 (<= (prefix-numeric-value arg) 0))))
1560
1561 ; Add or remove the menu, and run the hook
1562 (if reftex-mode
1563 (progn
1564 (easy-menu-add reftex-mode-menu)
1565 (reftex-plug-into-AUCTeX)
1566 (run-hooks 'reftex-mode-hook))
1567 (easy-menu-remove reftex-mode-menu)))
1568
1569 (or (assoc 'reftex-mode minor-mode-alist)
1570 (push '(reftex-mode " Ref") minor-mode-alist))
1571
1572 (or (assoc 'reftex-mode minor-mode-map-alist)
1573 (push (cons 'reftex-mode reftex-mode-map) minor-mode-map-alist))
1574
1575 ;;; ===========================================================================
1576 ;;;
1577 ;;; Silence warnings about variables in other packages.
1578 (defvar TeX-master)
1579 (defvar LaTeX-label-function)
1580 (defvar tex-main-file)
1581 (defvar outline-minor-mode)
1582
1583 ;;; ===========================================================================
1584 ;;;
1585 ;;; Interfaces for other packages
1586 ;;; -----------------------------
1587 ;;;
1588 ;;; AUCTeX
1589 ;;; ------
1590
1591 (defun reftex-arg-label (optional &optional prompt definition)
1592 "Use `reftex-label' to create label. Insert it with `TeX-argument-insert'.
1593 This function is intended for AUCTeX macro support."
1594 (let ((label (reftex-label nil t)))
1595 (if (and definition (not (string-equal "" label)))
1596 (LaTeX-add-labels label))
1597 (TeX-argument-insert label optional optional)))
1598
1599 (defun reftex-arg-ref (optional &optional prompt definition)
1600 "Use `reftex-reference' to select label. Insert with `TeX-argument-insert'.
1601 This function is intended for AUCTeX macro support."
1602 (let ((label (reftex-reference nil t)))
1603 (if (and definition (not (string-equal "" label)))
1604 (LaTeX-add-labels label))
1605 (TeX-argument-insert label optional optional)))
1606
1607 (defun reftex-arg-cite (optional &optional prompt definition)
1608 "Use reftex-citation to select a key. Insert with `TeX-argument-insert'.
1609 This function is intended for AUCTeX macro support."
1610 (let ((key (reftex-citation t)))
1611 (TeX-argument-insert (or key "") optional optional)))
1612
1613 (defun reftex-plug-into-AUCTeX ()
1614 ;; Replace AucTeX functions with RefTeX functions.
1615 ;; Which functions are replaced is controlled by the variable
1616 ;; `reftex-plug-into-AUCTeX'.
1617 (let ((flags
1618 (cond ((eq reftex-plug-into-AUCTeX t) '(t t t t))
1619 ((eq reftex-plug-into-AUCTeX nil) '(nil nil nil nil))
1620 (t reftex-plug-into-AUCTeX))))
1621
1622 (and (nth 0 flags)
1623 (boundp 'LaTeX-label-function)
1624 (setq LaTeX-label-function 'reftex-label))
1625
1626 (and (nth 1 flags)
1627 (fboundp 'TeX-arg-label)
1628 (fset 'TeX-arg-label 'reftex-arg-label))
1629
1630 (and (nth 2 flags)
1631 (fboundp 'TeX-arg-ref)
1632 (fset 'TeX-arg-ref 'reftex-arg-ref))
1633
1634 (and (nth 3 flags)
1635 (fboundp 'TeX-arg-cite)
1636 (fset 'TeX-arg-cite 'reftex-arg-cite))))
1637
1638
1639 (defvar reftex-label-alist-external-add-ons nil
1640 "List of label alist entries added with reftex-add-to-label-alist.")
1641
1642 (defun reftex-add-to-label-alist (entry-list)
1643 "Add label environment descriptions to `reftex-label-alist-external-add-ons'.
1644 The format of ENTRY-LIST is exactly like `reftex-label-alist'. See there
1645 for details.
1646 This function makes it possible to support RefTeX from AUCTeX style files.
1647 The entries in ENTRY-LIST will be processed after the user settings in
1648 `reftex-label-alist', and before the defaults (specified in
1649 `reftex-default-label-alist-entries'). Any changes made to
1650 `reftex-label-alist-external-add-ons' will raise a flag to the effect that a
1651 mode reset is done on the next occasion."
1652 (let (entry)
1653 (while entry-list
1654 (setq entry (car entry-list)
1655 entry-list (cdr entry-list))
1656 (unless (member entry reftex-label-alist-external-add-ons)
1657 (setq reftex-tables-dirty t)
1658 (push entry reftex-label-alist-external-add-ons)))))
1659
1660 ;;; ===========================================================================
1661 ;;;
1662 ;;; Multifile support
1663 ;;;
1664 ;;; Technical notes: Multifile works as follows: We keep just one list
1665 ;;; of labels for each master file - this can save a lot of memory.
1666 ;;; `reftex-master-index-list' is an alist which connects the true file name
1667 ;;; of each master file with the symbols holding the information on that
1668 ;;; document. Each buffer has local variables which point to these symbols.
1669
1670 ;; List of variables which handle the multifile stuff.
1671 ;; This list is used to tie, untie, and reset these symbols.
1672 (defconst reftex-multifile-symbols
1673 '(reftex-docstruct-symbol))
1674
1675 ;; Alist connecting master file names with the corresponding lisp symbols.
1676 (defvar reftex-master-index-list nil)
1677
1678 ;; Last index used for a master file.
1679 (defvar reftex-multifile-index 0)
1680
1681 ;; Variable holding the symbol with the label list of the document.
1682 (defvar reftex-docstruct-symbol nil)
1683 (make-variable-buffer-local 'reftex-docstruct-symbol)
1684
1685 (defun reftex-next-multifile-index ()
1686 ;; Return the next free index for multifile symbols.
1687 (incf reftex-multifile-index))
1688
1689 (defun reftex-tie-multifile-symbols ()
1690 ;; Tie the buffer-local symbols to globals connected with the master file.
1691 ;; If the symbols for the current master file do not exist, they are created.
1692
1693 (let* ((master (file-truename (reftex-TeX-master-file)))
1694 (index (assoc master reftex-master-index-list))
1695 (symlist reftex-multifile-symbols)
1696 (symbol nil)
1697 (symname nil)
1698 (newflag nil))
1699 ;; Find the correct index.
1700 (if index
1701 ;; symbols do exist
1702 (setq index (cdr index))
1703 ;; Get a new index and add info to the alist.
1704 (setq index (reftex-next-multifile-index)
1705 newflag t)
1706 (push (cons master index) reftex-master-index-list))
1707
1708 ;; Get/create symbols and tie them.
1709 (while symlist
1710 (setq symbol (car symlist)
1711 symlist (cdr symlist)
1712 symname (symbol-name symbol))
1713 (set symbol (intern (concat symname "-" (int-to-string index))))
1714 ;; Initialize if new symbols.
1715 (if newflag (set (symbol-value symbol) nil)))
1716
1717 ;; Return t if the symbols did already exist, nil when we've made them.
1718 (not newflag)))
1719
1720 (defun reftex-untie-multifile-symbols ()
1721 ;; Remove ties from multifile symbols, so that next use makes new ones.
1722 (let ((symlist reftex-multifile-symbols)
1723 (symbol nil))
1724 (while symlist
1725 (setq symbol (car symlist)
1726 symlist (cdr symlist))
1727 (set symbol nil))))
1728
1729 (defun reftex-TeX-master-file ()
1730 ;; Return the name of the master file associated with the current buffer.
1731 ;; When AUCTeX is loaded, we will use it's more sophisticated method.
1732 ;; We also support the default TeX and LaTeX modes by checking for a
1733 ;; variable tex-main-file.
1734
1735 (let
1736 ((master
1737 (cond
1738 ((fboundp 'TeX-master-file) ; AUCTeX is loaded. Use its mechanism.
1739 (TeX-master-file t))
1740 ((boundp 'TeX-master) ; The variable is defined - lets use it.
1741 (cond
1742 ((eq TeX-master t)
1743 (buffer-file-name))
1744 ((eq TeX-master 'shared)
1745 (setq TeX-master (read-file-name "Master file: "
1746 nil nil t nil)))
1747 (TeX-master)
1748 (t
1749 (setq TeX-master (read-file-name "Master file: "
1750 nil nil t nil)))))
1751 ((boundp 'tex-main-file)
1752 ;; This is the variable from the default TeX modes.
1753 (cond
1754 ((stringp tex-main-file)
1755 ;; ok, this must be it
1756 tex-main-file)
1757 (t
1758 ;; In this case, the buffer is its own master.
1759 (buffer-file-name))))
1760 (t
1761 ;; Know nothing about master file. Assume this is a master file.
1762 (buffer-file-name)))))
1763 (cond
1764 ((null master)
1765 (error "Need a filename for this buffer. Please save it first."))
1766 ((or (file-exists-p master)
1767 (reftex-get-buffer-visiting master))
1768 ;; We either see the file, or have a buffer on it. OK.
1769 )
1770 ((or (file-exists-p (concat master ".tex"))
1771 (reftex-get-buffer-visiting (concat master ".tex")))
1772 ;; Ahh, an extra .tex was missing...
1773 (setq master (concat master ".tex")))
1774 (t
1775 ;; Something is wrong here. Throw an exception.
1776 (error "No such master file %s" master)))
1777 (expand-file-name master)))
1778
1779 (defun reftex-parse-one ()
1780 "Re-parse this file."
1781 (interactive)
1782 (let ((reftex-enable-partial-scans t))
1783 (reftex-access-scan-info '(4))))
1784
1785 (defun reftex-parse-all ()
1786 "Re-parse entire document."
1787 (interactive)
1788 (reftex-access-scan-info '(16)))
1789
1790 (defun reftex-all-document-files (&optional relative)
1791 ;; Return a list of all files belonging to the current document.
1792 ;; When RELATIVE is non-nil, give file names relative to directory
1793 ;; of master file.
1794 (let* ((all (symbol-value reftex-docstruct-symbol))
1795 (master-dir (file-name-directory (reftex-TeX-master-file)))
1796 (re (concat "\\`" (regexp-quote master-dir)))
1797 file-list tmp file)
1798 (while (setq tmp (assoc 'bof all))
1799 (setq file (nth 1 tmp)
1800 all (cdr (memq tmp all)))
1801 (and relative
1802 (string-match re file)
1803 (setq file (substring file (match-end 0))))
1804 (push file file-list))
1805 (nreverse file-list)))
1806
1807 (defun reftex-create-tags-file ()
1808 "Create TAGS file by running `etags' on the current document.
1809 The TAGS file is also immediately visited with `visit-tags-table'."
1810 (interactive)
1811 (reftex-access-scan-info current-prefix-arg)
1812 (let* ((master (reftex-TeX-master-file))
1813 (files (reftex-all-document-files))
1814 (cmd (format "etags %s" (mapconcat 'identity files " "))))
1815 (save-excursion
1816 (set-buffer (reftex-get-buffer-visiting master))
1817 (message "Running etags to create TAGS file...")
1818 (shell-command cmd)
1819 (visit-tags-table "TAGS"))))
1820
1821 ;; History of grep commands.
1822 (defvar reftex-grep-history nil)
1823 (defvar reftex-grep-command "grep -n "
1824 "Last grep command used in \\[reftex-grep-document]; default for next grep.")
1825
1826 (defun reftex-grep-document (grep-cmd)
1827 "Run grep query through all files related to this document.
1828 With prefix arg, force to rescan document.
1829 This works also without an active TAGS table."
1830
1831 (interactive
1832 (list (read-from-minibuffer "Run grep on document (like this): "
1833 reftex-grep-command nil nil
1834 'reftex-grep-history)))
1835 (reftex-access-scan-info current-prefix-arg)
1836 (let* ((files (reftex-all-document-files t))
1837 (cmd (format
1838 "%s %s" grep-cmd
1839 (mapconcat 'identity files " "))))
1840 (grep cmd)))
1841
1842 (defun reftex-search-document (&optional regexp)
1843 "Regexp search through all files of the current TeX document.
1844 Starts always in the master file. Stops when a match is found.
1845 To continue searching for next match, use command \\[tags-loop-continue].
1846 This works also without an active TAGS table."
1847 (interactive)
1848 (let ((default (reftex-this-word)))
1849 (unless regexp
1850 (setq regexp (read-string (format "Search regexp in document [%s]: "
1851 default))))
1852 (if (string= regexp "") (setq regexp (regexp-quote default)))
1853
1854 (reftex-access-scan-info current-prefix-arg)
1855 (tags-search regexp (list 'reftex-all-document-files))))
1856
1857 (defun reftex-query-replace-document (&optional from to delimited)
1858 "Run a query-replace-regexp of FROM with TO over the entire TeX document.
1859 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
1860 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1861 with the command \\[tags-loop-continue].
1862 This works also without an active TAGS table."
1863 (interactive)
1864 (let ((default (reftex-this-word)))
1865 (unless from
1866 (setq from (read-string (format "Replace regexp in document [%s]: "
1867 default)))
1868 (if (string= from "") (setq from (regexp-quote default))))
1869 (unless to
1870 (setq to (read-string (format "Replace regexp %s with: " from))))
1871 (reftex-access-scan-info current-prefix-arg)
1872 (tags-query-replace from to (or delimited current-prefix-arg)
1873 (list 'reftex-all-document-files))))
1874
1875 (defun reftex-change-label (&optional from to)
1876 "Query replace FROM with TO in all \\label and \\ref commands.
1877 Works on the entire multifile document.
1878 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
1879 with the command \\[tags-loop-continue].
1880 This works also without an active TAGS table."
1881 (interactive)
1882 (let ((default (reftex-this-word "-a-zA-Z0-9_*.:")))
1883 (unless from
1884 (setq from (read-string (format "Replace label globally [%s]: "
1885 default))))
1886 (if (string= from "") (setq from default))
1887 (unless to
1888 (setq to (read-string (format "Replace label %s with: "
1889 from))))
1890 (reftex-query-replace-document
1891 (concat "\\\\\\(label\\|[a-z]*ref\\){" (regexp-quote from) "}")
1892 (format "\\\\\\1{%s}" to))))
1893
1894 ;;; ===========================================================================
1895 ;;;
1896 ;;; Functions to create and reference automatic labels.
1897
1898 ;; The following constants are derived from `reftex-label-alist'.
1899
1900 ;; Prompt used for label type querys directed to the user.
1901 (defconst reftex-type-query-prompt nil)
1902
1903 ;; Help string for label type querys.
1904 (defconst reftex-type-query-help nil)
1905
1906 ;; Alist relating label type to reference format.
1907 (defconst reftex-typekey-to-format-alist nil)
1908
1909 ;; Alist relating label type to label affix.
1910 (defconst reftex-typekey-to-prefix-alist nil)
1911
1912 ;; Alist relating environments or macros to label type and context regexp.
1913 (defconst reftex-env-or-mac-alist nil)
1914
1915 ;; List of macros carrying a label.
1916 (defconst reftex-label-mac-list nil)
1917
1918 ;; List of environments carrying a label.
1919 (defconst reftex-label-env-list nil)
1920
1921 ;; List of all typekey letters in use.
1922 (defconst reftex-typekey-list nil)
1923
1924 ;; Alist relating magic words to a label type.
1925 (defconst reftex-words-to-typekey-alist nil)
1926
1927 ;; The last list-of-labels entry used in a reference.
1928 (defvar reftex-last-used-reference (list nil nil nil nil))
1929
1930 ;; The regular expression used to abbreviate words.
1931 (defconst reftex-abbrev-regexp
1932 (concat
1933 "\\`\\("
1934 (make-string (nth 0 reftex-abbrev-parameters) ?.)
1935 "[" (nth 2 reftex-abbrev-parameters) "]*"
1936 "\\)"
1937 "[" (nth 3 reftex-abbrev-parameters) "]"
1938 (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
1939
1940 ;; Global variables used for communication between functions.
1941 (defvar reftex-default-context-position nil)
1942 (defvar reftex-location-start nil)
1943 (defvar reftex-call-back-to-this-buffer nil)
1944 (defvar reftex-active-toc nil)
1945 (defvar reftex-tex-path nil)
1946 (defvar reftex-bib-path nil)
1947
1948 ;; Internal list with index numbers of labels in the selection menu
1949 (defvar reftex-label-index-list)
1950
1951 ;; List of buffers created temporarily for lookup, which should be killed.
1952 (defvar reftex-buffers-to-kill nil)
1953
1954 ;; Regexp to find section statements. Computed from reftex-section-levels.
1955 (defvar reftex-section-regexp nil)
1956 (defvar reftex-section-or-include-regexp nil)
1957 (defvar reftex-everything-regexp nil)
1958 (defvar reftex-find-label-regexp-format nil)
1959 (defvar reftex-find-label-regexp-format2 nil)
1960
1961 ;; The parser functions ----------------------------------
1962
1963 (defvar reftex-memory nil
1964 "Memorizes old variable values to indicate changes in these variables.")
1965
1966 (defun reftex-access-scan-info (&optional rescan file)
1967 ;; Access the scanning info. When the multifile symbols are not yet tied,
1968 ;; tie them. When they are empty or RESCAN is non-nil, scan the document.
1969
1970 ;; Reset the mode if we had changes to important variables.
1971 (when (or reftex-tables-dirty
1972 (not (eq reftex-label-alist (nth 0 reftex-memory)))
1973 (not (eq reftex-label-alist-external-add-ons
1974 (nth 1 reftex-memory)))
1975 (not (eq reftex-default-label-alist-entries
1976 (nth 2 reftex-memory))))
1977 (reftex-reset-mode))
1978
1979 (if (eq reftex-docstruct-symbol nil)
1980 ;; Symbols are not yet tied: Tie them.
1981 (reftex-tie-multifile-symbols))
1982
1983 (if (and (null (symbol-value reftex-docstruct-symbol))
1984 reftex-save-parse-info)
1985 ;; Try to read the stuff from a file
1986 (reftex-access-parse-file 'read))
1987
1988 (cond
1989 ((not (symbol-value reftex-docstruct-symbol))
1990 (reftex-do-parse 1 file))
1991 ((member rescan '(t 1 (4) (16)))
1992 (reftex-do-parse rescan file))))
1993
1994 (defun reftex-do-parse (rescan &optional file)
1995 ;; Access the scanning info. When the multifile symbols are not yet tied,
1996 ;; tie them. When they are have to be created, do a buffer scan to
1997 ;; fill them.
1998
1999 ;; If RESCAN is non-nil, enforce document scanning
2000
2001 ;; Normalize the rescan argument
2002 (setq rescan (cond ((eq rescan t) t)
2003 ((eq rescan 1) 1)
2004 ((equal rescan '(4)) t)
2005 ((equal rescan '(16)) 1)
2006 (t 1)))
2007
2008 ;; Partial scans only when allowed
2009 (unless reftex-enable-partial-scans
2010 (setq rescan 1))
2011
2012 ;; Do the scanning.
2013
2014 (let* ((old-list (symbol-value reftex-docstruct-symbol))
2015 (master (reftex-TeX-master-file))
2016 (master-dir (file-name-as-directory (file-name-directory master)))
2017 (file (or file (buffer-file-name)))
2018 from-file
2019 docstruct tmp)
2020
2021 ;; Make sure replacement is really an option here
2022 (when (and (eq rescan t)
2023 (not (and (member (list 'bof file) old-list)
2024 (member (list 'eof file) old-list))))
2025 (message "Scanning whole document (no file section %s)" file)
2026 (setq rescan 1))
2027 (when (string= file master)
2028 (message "Scanning whole document (%s is master)" file)
2029 (setq rescan 1))
2030
2031 ;; From which file do we start?
2032 (setq from-file
2033 (cond ((eq rescan t) (or file master))
2034 ((eq rescan 1) master)
2035 (t (error "horrible!!"))))
2036
2037 ;; Find active toc entry and initialize section-numbers
2038 (setq reftex-active-toc
2039 (reftex-last-assoc-before-elt
2040 'toc (list 'bof from-file) old-list))
2041 (reftex-init-section-numbers reftex-active-toc)
2042
2043 (if (eq rescan 1)
2044 (message "Scanning entire document...")
2045 (message "Scanning document from %s..." from-file))
2046
2047 (save-window-excursion
2048 (save-excursion
2049 (unwind-protect
2050 (setq docstruct
2051 (reftex-parse-from-file
2052 from-file docstruct master-dir))
2053 (reftex-kill-temporary-buffers))))
2054
2055 (message "Scanning document... done")
2056
2057 ;; Turn the list around.
2058 (setq docstruct (nreverse docstruct))
2059
2060 ;; Set or insert
2061 (setq docstruct (reftex-replace-label-list-segment
2062 old-list docstruct (eq rescan 1)))
2063
2064 ;; Add all missing information
2065 (unless (assq 'label-numbers docstruct)
2066 (push (cons 'label-numbers nil) docstruct))
2067 (unless (assq 'master-dir docstruct)
2068 (push (cons 'master-dir master-dir) docstruct))
2069 (let* ((bof1 (memq (assq 'bof docstruct) docstruct))
2070 (bof2 (assq 'bof (cdr bof1)))
2071 (is-multi (not (not (and bof1 bof2))))
2072 (entry (or (assq 'is-multi docstruct)
2073 (car (push (list 'is-multi is-multi) docstruct)))))
2074 (setcdr entry (cons is-multi nil)))
2075 (unless (assq 'xr docstruct)
2076 (let* ((allxr (reftex-all-assq 'xr-doc docstruct))
2077 (alist (mapcar
2078 '(lambda (x)
2079 (if (setq tmp (reftex-find-tex-file (nth 2 x)
2080 master-dir))
2081 (cons (nth 1 x) tmp)
2082 (message "Can't find external document %s"
2083 (nth 2 x))
2084 nil))
2085 allxr))
2086 (alist (delete nil alist))
2087 (allprefix (delete nil (mapcar 'car alist)))
2088 (regexp (concat "\\`\\(" (mapconcat 'identity allprefix "\\|")
2089 "\\)")))
2090 (push (list 'xr alist regexp) docstruct)))
2091
2092 (set reftex-docstruct-symbol docstruct)
2093
2094 ;; Save the parsing informtion into a file?
2095 (if reftex-save-parse-info
2096 (reftex-access-parse-file 'write))))
2097
2098 (defun reftex-is-multi ()
2099 ;; Tell if this is a multifile document. When not sure, say yes.
2100 (let ((entry (assq 'is-multi (symbol-value reftex-docstruct-symbol))))
2101 (if entry
2102 (nth 1 entry)
2103 t)))
2104
2105 (defun reftex-parse-from-file (file docstruct master-dir)
2106 ;; Scan the buffer for labels and save them in a list.
2107 (let ((regexp reftex-everything-regexp)
2108 (bound 0)
2109 file-found tmp
2110 (level 1)
2111 (highest-level 100)
2112 toc-entry next-buf)
2113
2114 (catch 'exit
2115 (setq file-found (reftex-find-tex-file file master-dir))
2116 (unless file-found
2117 (push (list 'file-error file) docstruct)
2118 (throw 'exit nil))
2119
2120 (save-excursion
2121
2122 (message "Scanning file %s" file)
2123 (set-buffer
2124 (setq next-buf
2125 (reftex-get-file-buffer-force
2126 file-found
2127 (not (eq t reftex-keep-temporary-buffers)))))
2128
2129 ;; Begin of file mark
2130 (setq file (buffer-file-name))
2131 (push (list 'bof file) docstruct)
2132
2133 (save-excursion
2134 (save-restriction
2135 (widen)
2136 (goto-char 1)
2137
2138 (while (re-search-forward regexp nil t)
2139
2140 (cond
2141
2142 ((match-end 1)
2143 ;; It is a label
2144 (push (reftex-label-info (reftex-match-string 1) file bound)
2145 docstruct))
2146
2147 ((match-end 3)
2148 ;; It is a section
2149 (setq bound (point))
2150
2151 ;; Insert in List
2152 (setq toc-entry (reftex-section-info file))
2153 (setq level (nth 5 toc-entry))
2154 (setq highest-level (min highest-level level))
2155 (if (= level highest-level)
2156 (message
2157 "Scanning %s %s ..."
2158 (car (nth level reftex-section-levels))
2159 (nth 6 toc-entry)))
2160
2161 (push toc-entry docstruct)
2162 (setq reftex-active-toc toc-entry))
2163
2164 ((match-end 7)
2165 ;; It's an include or input
2166 (setq docstruct
2167 (reftex-parse-from-file
2168 (reftex-match-string 7)
2169 docstruct master-dir)))
2170
2171 ((match-end 8)
2172 ;; A macro with label
2173 (save-excursion
2174 (let* ((mac (reftex-match-string 8))
2175 (label (progn (goto-char (match-end 8))
2176 (save-match-data
2177 (reftex-no-props
2178 (reftex-nth-arg-wrapper
2179 mac)))))
2180 (entry (progn (goto-char (match-end 0))
2181 (reftex-label-info
2182 label file bound mac))))
2183 (push entry docstruct))))
2184 (t (error "This should not happen (reftex-parse-from-file)")))
2185 )
2186
2187
2188 ;; Find bibliography statement
2189 (when (setq tmp (reftex-locate-bibliography-files master-dir))
2190 (push (cons 'bib tmp) docstruct))
2191
2192 ;; Find external document specifications
2193 (goto-char 1)
2194 (while (re-search-forward "[\n\r][ \t]*\\\\externaldocument\\(\\[\\([^]]*\\)\\]\\)?{\\([^}]+\\)}" nil t)
2195 (push (list 'xr-doc (reftex-match-string 2)
2196 (reftex-match-string 3))
2197 docstruct))
2198
2199 ;; End of file mark
2200 (push (list 'eof file) docstruct))))
2201
2202 ;; Kill the scanned buffer
2203 (reftex-kill-temporary-buffers next-buf))
2204
2205 ;; Return the list
2206 docstruct))
2207
2208 (defun reftex-locate-bibliography-files (master-dir)
2209 ;; Scan buffer for bibliography macro and return file list.
2210 (let (file-list)
2211 (save-excursion
2212 (goto-char (point-min))
2213 (if (re-search-forward
2214 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\bibliography{[ \t]*\\([^}]+\\)" nil t)
2215 (setq file-list
2216 (mapcar '(lambda (x) (concat x ".bib"))
2217 (reftex-delete-list
2218 reftex-bibfile-ignore-list
2219 (split-string
2220 (reftex-match-string 2)
2221 "[ \t\n\r]*,[ \t\n\r]*")))))
2222 (delete nil
2223 (mapcar
2224 (function
2225 (lambda (file) (reftex-find-bib-file file master-dir)))
2226 file-list)))))
2227
2228 (defun reftex-last-assoc-before-elt (key elt list)
2229 ;; Find the last association of KEY in LIST before or at ELT
2230 ;; ELT is found in LIST with equal, not eq.
2231 ;; Returns nil when either KEY or elt are not found in LIST.
2232 ;; On success, returns the association.
2233 (let* ((elt (car (member elt list))) ass last-ass)
2234
2235 (while (and (setq ass (assoc key list))
2236 (setq list (memq ass list))
2237 (memq elt list))
2238 (setq last-ass ass
2239 list (cdr list)))
2240 last-ass))
2241
2242 (defun reftex-replace-label-list-segment (old insert &optional entirely)
2243 ;; Replace the segment in OLD which corresponds to INSERT.
2244 ;; Works with side effects, directly changes old.
2245 ;; If entirely is t, just return INSERT.
2246 ;; This function also makes sure the old toc markers do not point anywhere.
2247
2248 (cond
2249 (entirely
2250 (reftex-silence-toc-markers old (length old))
2251 insert)
2252 (t (let* ((new old)
2253 (file (nth 1 (car insert)))
2254 (eof-list (member (list 'eof file) old))
2255 (bof-list (member (list 'bof file) old))
2256 n)
2257 (if (not (and bof-list eof-list))
2258 (error "Cannot splice")
2259 ;; Splice
2260 (reftex-silence-toc-markers bof-list (- (length bof-list)
2261 (length eof-list)))
2262 (setq n (- (length old) (length bof-list)))
2263 (setcdr (nthcdr n new) (cdr insert))
2264 (setcdr (nthcdr (1- (length new)) new) (cdr eof-list)))
2265 new))))
2266
2267 (defun reftex-silence-toc-markers (list n)
2268 ;; Set all markers in list to nil
2269 (while (and list (> (decf n) -1))
2270 (and (eq (car (car list)) 'toc)
2271 (markerp (nth 4 (car list)))
2272 (set-marker (nth 4 (car list)) nil))
2273 (pop list)))
2274
2275 (defun reftex-access-parse-file (action)
2276 (let* ((list (symbol-value reftex-docstruct-symbol))
2277 (master (reftex-TeX-master-file))
2278 (enable-local-variables nil)
2279 (file (if (string-match "\\.[a-zA-Z]+\\'" master)
2280 (concat (substring master 0 (match-beginning 0)) ".rel")
2281 (concat master ".rel"))))
2282 (cond
2283 ((eq action 'readable)
2284 (file-readable-p file))
2285 ((eq action 'restore)
2286 (if (eq reftex-docstruct-symbol nil)
2287 ;; Symbols are not yet tied: Tie them.
2288 (reftex-tie-multifile-symbols))
2289 (if (file-exists-p file)
2290 ;; load the file and return t for success
2291 (progn (load-file file) t)
2292 ;; return nil for failure
2293 nil))
2294 ((eq action 'read)
2295 (if (file-exists-p file)
2296 ;; load the file and return t for success
2297 (progn (load-file file) t)
2298 ;; return nil for failure
2299 nil))
2300 (t
2301 (save-excursion
2302 (if (file-writable-p file)
2303 (progn
2304 (message "Writing parse file %s" (abbreviate-file-name file))
2305 (find-file file)
2306 (erase-buffer)
2307 (insert (format ";; RefTeX parse info file\n"))
2308 (insert (format ";; File: %s\n" master))
2309 (insert (format ";; Date: %s\n"
2310 (format-time-string "%D %T"
2311 (current-time))))
2312 (insert (format ";; User: %s (%s)\n\n"
2313 (user-login-name) (user-full-name)))
2314 (insert "(set reftex-docstruct-symbol '(\n\n")
2315 (let ((standard-output (current-buffer)))
2316 (mapcar
2317 (function
2318 (lambda (x)
2319 (cond ((eq (car x) 'toc)
2320 ;; A toc entry. Do not save the marker.
2321 ;; Save the markers position at position 8
2322 (print (list 'toc "toc" (nth 2 x) (nth 3 x)
2323 nil (nth 5 x) (nth 6 x) (nth 7 x)
2324 (or (and (markerp (nth 4 x))
2325 (marker-position (nth 4 x)))
2326 (nth 8 x)))))
2327 (t (print x)))))
2328 list))
2329 (insert "))")
2330 (save-buffer 0)
2331 (kill-buffer (current-buffer)))
2332 (error "Cannot write to file %s" file)))
2333 t))))
2334
2335 ;; Creating labels --------------
2336
2337 (defun reftex-label (&optional environment no-insert)
2338 "Insert a unique label. Return the label.
2339 If ENVIRONMENT is given, don't bother to find out yourself.
2340 If NO-INSERT is non-nil, do not insert label into buffer.
2341 With prefix arg, force to rescan document first.
2342 The label is also inserted into the label list.
2343 This function is controlled by the settings of reftex-insert-label-flags."
2344
2345 (interactive)
2346
2347 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4).
2348 (reftex-access-scan-info current-prefix-arg)
2349
2350 ;; Find out what kind of environment this is and abort if necessary.
2351 (if (or (not environment)
2352 (not (assoc environment reftex-env-or-mac-alist)))
2353 (setq environment (reftex-label-location)))
2354 (unless environment
2355 (error "Can't figure out what kind of label should be inserted"))
2356
2357 ;; Ok, go ahead.
2358 (let* ((entry (assoc environment reftex-env-or-mac-alist))
2359 (typekey (nth 1 entry))
2360 (format (nth 3 entry))
2361 label prefix valid default force-prompt)
2362 (when (and (eq (string-to-char environment) ?\\)
2363 (nth 4 entry)
2364 (memq (preceding-char) '(?\[ ?\{)))
2365 (setq format "%s"))
2366
2367 (setq prefix (or (cdr (assoc typekey reftex-typekey-to-prefix-alist))
2368 (concat typekey "-")))
2369 ;; Replace any escapes in the prefix
2370 (setq prefix (reftex-replace-prefix-escapes prefix))
2371
2372 ;; Make a default label.
2373 (cond
2374
2375 ((reftex-typekey-check typekey (nth 0 reftex-insert-label-flags))
2376 ;; Derive a label from context.
2377 (setq reftex-active-toc (reftex-last-assoc-before-elt
2378 'toc (car (reftex-where-am-I))
2379 (symbol-value reftex-docstruct-symbol)))
2380 (setq default (reftex-no-props
2381 (nth 2 (reftex-label-info " " nil nil t))))
2382 ;; Catch the cases where the is actually no context available.
2383 (if (or (string-match "NO MATCH FOR CONTEXT REGEXP" default)
2384 (string-match "ILLEGAL VALUE OF PARSE" default)
2385 (string-match "SECTION HEADING NOT FOUND" default)
2386 (string-match "HOOK ERROR" default)
2387 (string-match "^[ \t]*$" default))
2388 (setq default prefix
2389 force-prompt t) ; need to prompt
2390 (setq default (concat prefix (reftex-string-to-label default)))
2391
2392 ;; Make it unique.
2393 (setq default (reftex-uniquify-label default nil "-"))))
2394
2395 ((reftex-typekey-check typekey (nth 1 reftex-insert-label-flags)) ; prompt
2396 ;; Minimal default: the user will be prompted.
2397 (setq default prefix))
2398
2399 (t
2400 ;; Make an automatic label.
2401 (setq default (reftex-uniquify-label prefix t))))
2402
2403 ;; Should we ask the user?
2404 (if (or (reftex-typekey-check typekey
2405 (nth 1 reftex-insert-label-flags)) ; prompt
2406 force-prompt)
2407
2408 (while (not valid)
2409 ;; iterate until we get a legal label
2410
2411 (setq label (read-string
2412 (if (string= format "%s") "Naked Label: " "Label: ")
2413 default))
2414
2415 ;; Lets make sure that this is a legal label
2416 (cond
2417
2418 ;; Test if label contains strange characters
2419 ((string-match reftex-label-illegal-re label)
2420 (message "Label \"%s\" contains illegal characters" label)
2421 (ding)
2422 (sit-for 2))
2423
2424 ;; Look it up in the label list
2425 ((setq entry (assoc label
2426 (symbol-value reftex-docstruct-symbol)))
2427 (message "Label \"%s\" exists in file %s" label (nth 3 entry))
2428 (ding)
2429 (sit-for 2))
2430
2431 ;; Label is ok
2432 (t
2433 (setq valid t))))
2434 (setq label default))
2435
2436 ;; Insert the label into the label list
2437 (let* ((here-I-am-info (reftex-where-am-I))
2438 (here-I-am (car here-I-am-info))
2439 (note (if (cdr here-I-am-info)
2440 ""
2441 "POSITION UNCERTAIN. RESCAN TO FIX."))
2442 (file (buffer-file-name))
2443 (text nil)
2444 (tail (memq here-I-am (symbol-value reftex-docstruct-symbol))))
2445
2446 (if tail
2447 (setcdr tail (cons (list label typekey text file note)
2448 (cdr tail)))))
2449
2450 ;; Insert the label into the buffer
2451 (unless no-insert
2452 (insert (format format label)))
2453
2454 ;; return value of the function is the label
2455 label))
2456
2457 (defun reftex-string-to-label (string)
2458 ;; Convert a string (a sentence) to a label.
2459 ;;
2460 ;; Uses reftex-derive-label-parameters and reftex-abbrev-parameters
2461 ;;
2462
2463 (let* ((words0 (split-string string "[- \t\n\r]+"))
2464 (ignore-words (nth 5 reftex-derive-label-parameters))
2465 words word)
2466
2467 ;; remove words from the ignore list or with funny characters
2468 (while (setq word (pop words0))
2469 (cond
2470 ((member (downcase word) ignore-words))
2471 ((string-match reftex-label-illegal-re word)
2472 (when (nth 2 reftex-derive-label-parameters)
2473 (while (string-match reftex-label-illegal-re word)
2474 (setq word (replace-match "" nil nil word)))
2475 (push word words)))
2476 (t
2477 (push word words))))
2478 (setq words (nreverse words))
2479
2480 ;; restrict number of words
2481 (if (> (length words) (nth 0 reftex-derive-label-parameters))
2482 (setcdr (nthcdr (1- (nth 0 reftex-derive-label-parameters)) words) nil))
2483
2484 ;; First, try to use all words
2485 (setq string (mapconcat '(lambda(w) w) words
2486 (nth 4 reftex-derive-label-parameters)))
2487
2488 ;; Abbreviate words if enforced by user settings or string length
2489 (if (or (eq t (nth 3 reftex-derive-label-parameters))
2490 (and (nth 3 reftex-derive-label-parameters)
2491 (> (length string) (nth 1 reftex-derive-label-parameters))))
2492 (setq words
2493 (mapcar
2494 '(lambda (w) (if (string-match reftex-abbrev-regexp w)
2495 (match-string 1 w)
2496 w))
2497 words)
2498 string (mapconcat '(lambda(w) w) words
2499 (nth 4 reftex-derive-label-parameters))))
2500
2501 ;; Shorten if still to long
2502 (setq string
2503 (if (> (length string) (nth 1 reftex-derive-label-parameters))
2504 (substring string 0 (nth 1 reftex-derive-label-parameters))
2505 string))
2506
2507 ;; Delete the final punctuation, if any
2508 (if (string-match "[^a-zA-Z0-9]+\\'" string)
2509 (setq string (replace-match "" nil nil string)))
2510 string))
2511
2512 (defun reftex-replace-prefix-escapes (prefix)
2513 ;; Replace %escapes in a label prefix
2514 (save-match-data
2515 (let (letter (num 0) replace)
2516 (while (string-match "\\%\\([a-zA-Z]\\)" prefix num)
2517 (setq letter (match-string 1 prefix))
2518 (setq replace
2519 (cond
2520 ((equal letter "f")
2521 (file-name-sans-extension
2522 (file-name-nondirectory (buffer-file-name))))
2523 ((equal letter "F")
2524 (let ((masterdir (file-name-directory (reftex-TeX-master-file)))
2525 (file (file-name-sans-extension (buffer-file-name))))
2526 (if (string-match (concat "\\`" (regexp-quote masterdir))
2527 file)
2528 (substring file (length masterdir))
2529 file)))
2530 ((equal letter "u")
2531 (or (user-login-name) ""))
2532 (t "")))
2533 (setq num (1- (+ (match-beginning 1) (length replace)))
2534 prefix (replace-match replace nil nil prefix)))
2535 prefix)))
2536
2537 (defun reftex-label-location (&optional bound)
2538 ;; Return the environment or macro which determines the label type at point.
2539 ;; If optional BOUND is an integer, limit backward searches to that point.
2540
2541 (let* ((loc1 (reftex-what-macro reftex-label-mac-list bound))
2542 (loc2 (reftex-what-environment reftex-label-env-list bound))
2543 (p1 (or (cdr loc1) 0))
2544 (p2 (or (cdr loc2) 0)))
2545
2546 (setq reftex-location-start (max p1 p2))
2547 (if (>= p1 p2)
2548 (progn
2549 (setq reftex-default-context-position (+ p1 (length (car loc1))))
2550 (or (car loc1) "section"))
2551 (setq reftex-default-context-position (+ p2 8 (length (car loc2))))
2552 (or (car loc2) "section"))))
2553
2554 (defun reftex-uniquify-label (label &optional force separator)
2555 ;; Make label unique by appending a number.
2556 ;; Optional FORCE means, force appending a number, even if label is unique.
2557 ;; Optional SEPARATOR is a string to stick between label and number.
2558
2559 ;; Ensure access to scanning info
2560 (reftex-access-scan-info)
2561
2562 (cond
2563 ((and (not force)
2564 (not (assoc label (symbol-value reftex-docstruct-symbol))))
2565 label)
2566 (t
2567 (let* ((label-numbers (assq 'label-numbers
2568 (symbol-value reftex-docstruct-symbol)))
2569 (label-numbers-alist (cdr label-numbers))
2570 (cell (or (assoc label label-numbers-alist)
2571 (car (setcdr label-numbers
2572 (cons (cons label 0)
2573 label-numbers-alist)))))
2574 (num (1+ (cdr cell)))
2575 (sep (or separator "")))
2576 (while (assoc (concat label sep (int-to-string num))
2577 (symbol-value reftex-docstruct-symbol))
2578 (incf num))
2579 (setcdr cell num)
2580 (concat label sep (int-to-string num))))))
2581
2582 ;; Help string for the reference label menu
2583 (defconst reftex-select-label-prompt
2584 "Select: [n]ext [p]revious [r]escan [ ]context e[x]tern [q]uit RET [?]HELP+more")
2585
2586 (defconst reftex-select-label-help
2587 " AVAILABLE KEYS IN REFERENCE LABEL MENU
2588 --------------------------------------
2589 n / p Go to next/previous label (Cursor motion works as well)
2590 C-s / C-r Search forward/backward. Use repeated C-s/C-r as in isearch.
2591 r / s Reparse document / Switch label type
2592 x Switch to label menu of external document (with LaTeX package `xr')
2593 t i c # % Toggle: [i]ncl. file borders, [t]able of contents, [c]ontext
2594 [#] label counters, [%] labels in comments
2595 SPC Show full context for current label in other window
2596 f Toggle follow mode: other window will follow context
2597 l / q Reuse last referenced label / Quit without accepting label
2598 e Recursive Edit into other window
2599 RET Accept current label")
2600
2601 (defun reftex-reference (&optional type no-insert)
2602 "Make a LaTeX reference. Look only for labels of a certain TYPE.
2603 With prefix arg, force to rescan buffer for labels. This should only be
2604 necessary if you have recently entered labels yourself without using
2605 reftex-label. Rescanning of the buffer can also be requested from the
2606 label selection menu.
2607 The function returns the selected label or nil.
2608 If NO-INSERT is non-nil, do not insert \\ref command, just return label.
2609 When called with 2 C-u prefix args, disable magic word recognition."
2610
2611 (interactive)
2612
2613 ;; check for active recursive edits
2614 (reftex-check-recursive-edit)
2615
2616 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
2617 (reftex-access-scan-info current-prefix-arg)
2618
2619 (unless type
2620 ;; guess type from context
2621 (if (and reftex-guess-label-type
2622 (setq type (assoc (downcase (reftex-word-before-point))
2623 reftex-words-to-typekey-alist)))
2624 (setq type (cdr type))
2625 (setq type (reftex-query-label-type))))
2626
2627 (let (label pair
2628 (form (or (cdr (assoc type reftex-typekey-to-format-alist))
2629 "\\ref{%s}")))
2630
2631 ;; Have the user select a label
2632 (setq pair (reftex-offer-label-menu type))
2633 (setq label (car pair))
2634
2635 (if (and label
2636 (not no-insert))
2637 (progn
2638 ;; do we need to remove spaces?
2639 (if (string= "~" (substring form 0 1))
2640 (while (or (= (preceding-char) ?\ )
2641 (= (preceding-char) ?\C-i))
2642 (backward-delete-char 1)))
2643 ;; ok, insert the reference
2644 (insert (format form label label))
2645 (message ""))
2646 (message "Quit"))
2647 ;; return the label
2648 label))
2649
2650 (defun reftex-offer-label-menu (typekey)
2651 ;; Offer a menu with the appropriate labels. Return (label . file).
2652 (let* ((buf (current-buffer))
2653 (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
2654 (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
2655 (xr-index 0)
2656 (here-I-am (car (reftex-where-am-I)))
2657 (toc (reftex-typekey-check typekey reftex-label-menu-flags 0))
2658 (files (reftex-typekey-check typekey reftex-label-menu-flags 7))
2659 (context (not (reftex-typekey-check
2660 typekey reftex-label-menu-flags 3)))
2661 (counter (reftex-typekey-check
2662 typekey reftex-label-menu-flags 2))
2663 (follow (reftex-typekey-check
2664 typekey reftex-label-menu-flags 4))
2665 (commented (nth 5 reftex-label-menu-flags))
2666 (match-everywhere (reftex-typekey-check
2667 typekey reftex-label-menu-flags 6))
2668 (prefix "")
2669 offset rtn key cnt last-cnt entry)
2670
2671 (setq entry (cons nil nil))
2672
2673 ;; The following unwind-protect kills temporary buffers after use
2674 (unwind-protect
2675 (catch 'exit
2676 (while t
2677 (save-window-excursion
2678 (setq reftex-call-back-to-this-buffer buf)
2679 (switch-to-buffer-other-window "*RefTeX Select*")
2680 (erase-buffer)
2681 (setq truncate-lines t)
2682 (setq mode-line-format
2683 (list "---- " 'mode-line-buffer-identification
2684 " " (abbreviate-file-name
2685 (buffer-file-name buf))
2686 " -%-"))
2687
2688 (setq reftex-label-index-list
2689 (reftex-make-and-insert-label-list
2690 typekey buf toc files context counter commented
2691 here-I-am prefix))
2692 (setq here-I-am nil) ; turn off determination of offset
2693 ;; use only when searched
2694 (setq offset (or (car reftex-label-index-list) offset))
2695 ;; only this is the true list
2696 (pop reftex-label-index-list)
2697 (setq rtn
2698 (reftex-select-item
2699 reftex-select-label-prompt
2700 "^>"
2701 2
2702 reftex-select-label-help
2703 '(?r ?R ?g ?c ?t ?s ?# ?i ?l ?% ?x)
2704 offset
2705 'reftex-select-label-callback follow
2706 match-everywhere))
2707 (setq key (car rtn)
2708 cnt (nth 1 rtn)
2709 last-cnt (nth 2 rtn)
2710 offset (1+ (or cnt last-cnt 0)))
2711 (unless key (throw 'exit nil))
2712 (cond
2713 ((or (eq key ?r)
2714 (eq key ?R)
2715 (eq key ?g))
2716 ;; rescan buffer
2717 (reftex-parse-document buf (or cnt last-cnt) key))
2718 ((eq key ?c)
2719 ;; toggle context mode
2720 (setq context (not context)))
2721 ((eq key ?s)
2722 ;; switch type
2723 (setq typekey (reftex-query-label-type)))
2724 ((eq key ?t)
2725 ;; toggle tabel of contents display
2726 (setq toc (not toc)))
2727 ((eq key ?i)
2728 ;; toggle display of included file borders
2729 (setq files (not files)))
2730 ((eq key ?#)
2731 ;; toggle counter display
2732 (setq counter (not counter)))
2733 ((eq key ?%)
2734 ;; toggle display of commented labels
2735 (setq commented (not commented)))
2736 ((eq key ?l)
2737 ;; reuse the last referenced label again
2738 (setq entry reftex-last-used-reference)
2739 (throw 'exit t))
2740 ((eq key ?x)
2741 ;; select an external document
2742 (setq xr-index (reftex-select-external-document
2743 xr-alist xr-index))
2744 (setq buf (or (reftex-get-file-buffer-force
2745 (cdr (nth xr-index xr-alist)))
2746 (error "Cannot switch document"))
2747 prefix (or (car (nth xr-index xr-alist)) "")
2748 offset nil))
2749 (t
2750 (set-buffer buf)
2751 (if cnt
2752 (progn
2753 (setq entry (nth (nth cnt reftex-label-index-list)
2754 (symbol-value reftex-docstruct-symbol)))
2755 (setq reftex-last-used-reference entry))
2756 (setq entry nil))
2757 (throw 'exit t))))))
2758 (kill-buffer "*RefTeX Select*")
2759 (and (get-buffer "*RefTeX Context Copy*")
2760 (kill-buffer "*RefTeX Context Copy*"))
2761 (reftex-kill-temporary-buffers))
2762 (cons (if (nth 0 entry) (concat prefix (nth 0 entry)) nil)
2763 (nth 3 entry))))
2764
2765 (defun reftex-select-external-document (xr-alist xr-index)
2766 ;; Return index of an external document.
2767 (cond
2768 ((= (length xr-alist) 1)
2769 (message "No external douments available")
2770 (ding) 0)
2771 ((= (length xr-alist) 2)
2772 (- 1 xr-index))
2773 (t
2774 (save-window-excursion
2775 (let* ((fmt " [%c] %-5s %s\n") (n (1- ?0)) key)
2776 (with-output-to-temp-buffer "*RefTeX Select*"
2777 (princ
2778 (concat "Select a document by pressing a number key:\n KEY PREFIX DOCUMENT\n----------------------\n"
2779 (mapconcat '(lambda (x)
2780 (format fmt (incf n) (or (car x) "")
2781 (abbreviate-file-name (cdr x))))
2782 xr-alist ""))))
2783 (setq key (read-char))
2784 (if (< (- key ?1) (length xr-alist))
2785 (- key ?0)
2786 (error "Illegal document selection [%c]" key)))))))
2787
2788 (defun reftex-make-and-insert-label-list
2789 (typekey0 buf toc files context counter show-commented here-I-am xr-prefix)
2790 ;; Insert a menu of all labels in buffer BUF into current buffer.
2791 ;; Return the list of labels, with the index of HERE-I-AM as extra car.
2792 (let* ((font (reftex-use-fonts))
2793 (refont (reftex-refontify))
2794 (cnt 0)
2795 (index -1)
2796 (toc-indent " ")
2797 (label-indent
2798 (concat "> "
2799 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
2800 (context-indent
2801 (concat ". "
2802 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
2803 all cell text label typekey note comment master-dir-re
2804 index-list offset docstruct-symbol from from1 to)
2805
2806 ;; Pop to buffer buf to get the correct buffer-local variables
2807 (save-excursion
2808 (set-buffer buf)
2809
2810 ;; Ensure access to scanning info
2811 (reftex-access-scan-info)
2812
2813 (setq docstruct-symbol reftex-docstruct-symbol
2814 all (symbol-value reftex-docstruct-symbol)
2815 reftex-active-toc nil
2816 master-dir-re
2817 (concat "\\`" (regexp-quote
2818 (file-name-directory (reftex-TeX-master-file))))))
2819
2820 (when refont
2821 ;; Calculate font-lock-defaults as in LaTeX mode.
2822 (make-local-variable 'font-lock-defaults)
2823 (setq font-lock-defaults nil)
2824 (let ((major-mode 'latex-mode))
2825 (font-lock-set-defaults))
2826 ;; The following is only needed for XEmacs, but does not hurt Emacs.
2827 (setq font-lock-mode nil))
2828
2829 ;; Walk the docstruct and insert the appropriate stuff
2830
2831 (while (setq cell (pop all))
2832
2833 (incf index)
2834 (setq from (point))
2835
2836 (if (eq cell here-I-am) (setq offset (1+ cnt)))
2837
2838 (cond
2839
2840 ((memq (car cell) '(bib label-numbers master-dir is-multi
2841 xr xr-doc)))
2842 ;; These are currently ignored
2843
2844 ((memq (car cell) '(bof eof file-error))
2845 ;; Beginning or end of a file
2846 (when files
2847 (insert
2848 " " (if (string-match master-dir-re (nth 1 cell))
2849 (substring (nth 1 cell) (match-end 0))
2850 (nth 1 cell))
2851 (cond ((eq (car cell) 'bof) " starts here\n")
2852 ((eq (car cell) 'eof) " ends here\n")
2853 ((eq (car cell) 'file-error) " was not found\n")))
2854 (when font
2855 (put-text-property from (point)
2856 'face 'font-lock-function-name-face))))
2857
2858 ((eq (car cell) 'toc)
2859 ;; a table of contents entry
2860 (when toc
2861 (setq reftex-active-toc cell)
2862 (insert (concat toc-indent (nth 2 cell) "\n"))))
2863
2864 ((stringp (car cell))
2865 ;; a label
2866 (when (null (nth 2 cell))
2867 ;; No context yet. Quick update.
2868 (setq cell (reftex-label-info-update cell))
2869 (setcar (nthcdr index (symbol-value docstruct-symbol))
2870 cell))
2871
2872 (setq label (car cell)
2873 typekey (nth 1 cell)
2874 text (nth 2 cell)
2875 note (nth 4 cell)
2876 comment (get-text-property 0 'in-comment text))
2877
2878 (when (and (or (string= typekey typekey0) (string= typekey0 " "))
2879 (or show-commented (null comment)))
2880
2881 ;; Yes we want this one
2882 (incf cnt)
2883 (push index index-list)
2884
2885 (setq label (concat xr-prefix label))
2886 (when comment (setq label (concat "% " label)))
2887 (insert label-indent label)
2888 (when font
2889 (put-text-property
2890 (- (point) (length label)) (point)
2891 'face (if comment
2892 'font-lock-comment-face
2893 'font-lock-reference-face)))
2894
2895 (insert (if counter (format " (%d) " cnt) "")
2896 (if comment " LABEL IS COMMENTED OUT " "")
2897 (if note (concat " " note) "")
2898 "\n")
2899 (setq to (point))
2900
2901 (when context
2902 (setq from1 to)
2903 (insert context-indent text "\n")
2904 (setq to (point))
2905 (when refont
2906 (font-lock-fontify-region from1 to)
2907 (goto-char to)))
2908 (put-text-property from to 'cnt (1- cnt))
2909 (goto-char to)))))
2910
2911 ;; Return the index list
2912 (cons offset (nreverse index-list))))
2913
2914 (defun reftex-parse-document (&optional buffer cnt key)
2915 "Rescan the document."
2916 (interactive)
2917 (save-window-excursion
2918 (save-excursion
2919 (if buffer
2920 (if (not (bufferp buffer))
2921 (error "No such buffer %s" (buffer-name buffer))
2922 (set-buffer buffer)))
2923 (let ((arg (if (eq key ?R) '(16) '(4)))
2924 (file (if cnt
2925 (nth 3
2926 (nth (nth cnt reftex-label-index-list)
2927 (symbol-value reftex-docstruct-symbol))))))
2928 (reftex-access-scan-info arg file)))))
2929
2930 (defun reftex-query-label-type ()
2931 ;; Ask for label type
2932 (message reftex-type-query-prompt)
2933 (let ((key (read-char)))
2934 (when (eq key ?\?)
2935 (save-window-excursion
2936 (with-output-to-temp-buffer "*RefTeX Help*"
2937 (princ reftex-type-query-help))
2938 (setq key (read-char))
2939 (kill-buffer "*RefTeX Help*")))
2940 (unless (member (char-to-string key) reftex-typekey-list)
2941 (error "No such label type: %s" (char-to-string key)))
2942 (char-to-string key)))
2943
2944 ;; Variable holding the vector with section numbers
2945 (defvar reftex-section-numbers [0 0 0 0 0 0 0 0])
2946
2947 (defun reftex-section-info (file)
2948 ;; Return a section entry for the current match.
2949 ;; Carefull: This function expects the match-data to be still in place!
2950 (let* ((marker (set-marker (make-marker) (1- (match-beginning 3))))
2951 (macro (reftex-match-string 3))
2952 (star (= ?* (char-after (match-end 3))))
2953 (level (cdr (assoc macro reftex-section-levels)))
2954 (section-number (reftex-section-number
2955 reftex-section-numbers level star))
2956 (text1 (save-match-data (save-excursion (reftex-context-substring))))
2957 (literal (buffer-substring-no-properties
2958 (1- (match-beginning 3))
2959 (min (point-max) (+ (match-end 0) (length text1) 1))))
2960 ;; Literal can be too short since text1 too short. No big problem.
2961 (text (reftex-nicify-text text1)))
2962
2963 ;; Add section number and indentation
2964 (setq text
2965 (concat
2966 (make-string (* reftex-level-indent level) ?\ )
2967 (if (nth 1 reftex-label-menu-flags) ; section number flag
2968 (concat section-number " "))
2969 text))
2970 ;; Fontify
2971 (if (reftex-use-fonts)
2972 (put-text-property 0 (length text)
2973 'face 'font-lock-comment-face text))
2974 (list 'toc "toc" text file marker level section-number
2975 literal (marker-position marker))))
2976
2977 (defun reftex-label-info-update (cell)
2978 ;; Update information about just one label in a different file.
2979 ;; CELL contains the old info list
2980 (let* ((label (nth 0 cell))
2981 (typekey (nth 1 cell))
2982 ;; (text (nth 2 cell))
2983 (file (nth 3 cell))
2984 (note (nth 4 cell))
2985 (buf (reftex-get-file-buffer-force
2986 file (not (eq t reftex-keep-temporary-buffers)))))
2987 (if (not buf)
2988 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")
2989 (save-excursion
2990 (set-buffer buf)
2991 (save-restriction
2992 (widen)
2993 (goto-char 1)
2994
2995 (if (or (re-search-forward
2996 (format reftex-find-label-regexp-format
2997 (regexp-quote label)) nil t)
2998 (re-search-forward
2999 (format reftex-find-label-regexp-format2
3000 (regexp-quote label)) nil t))
3001
3002 (progn
3003 (backward-char 1)
3004 (append (reftex-label-info label file) (list note)))
3005 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")))))))
3006
3007 (defun reftex-label-info (label &optional file bound derive env-or-mac)
3008 ;; Return info list on LABEL at point.
3009 (let* ((env-or-mac (or env-or-mac (reftex-label-location bound)))
3010 (typekey (nth 1 (assoc env-or-mac reftex-env-or-mac-alist)))
3011 (file (or file (buffer-file-name)))
3012 (parse (if (reftex-typekey-check
3013 typekey reftex-use-text-after-label-as-context)
3014 nil
3015 (nth 2 (assoc env-or-mac reftex-env-or-mac-alist))))
3016 (text (reftex-short-context env-or-mac parse reftex-location-start
3017 derive)))
3018 (if (reftex-in-comment)
3019 (put-text-property 0 1 'in-comment t text))
3020 (list label typekey text file)))
3021
3022 (defun reftex-in-comment ()
3023 (save-excursion
3024 (skip-chars-backward "^%\n\r")
3025 (eq (preceding-char) ?%)))
3026
3027 (defun reftex-short-context (env parse &optional bound derive)
3028 ;; Get about one line of useful context for the label definition at point.
3029
3030 (if (consp parse)
3031 (setq parse (if derive (cdr parse) (car parse))))
3032
3033 (reftex-nicify-text
3034
3035 (cond
3036
3037 ((null parse)
3038 (save-excursion
3039 (reftex-context-substring)))
3040
3041 ((eq parse t)
3042 (if (string= env "section")
3043 ;; special treatment for section labels
3044 (save-excursion
3045 (if (and (re-search-backward reftex-section-or-include-regexp
3046 (point-min) t)
3047 (match-end 2))
3048 (progn
3049 (goto-char (match-end 0))
3050 (reftex-context-substring))
3051 (if reftex-active-toc
3052 (progn
3053 (string-match "{\\([^}]*\\)" (nth 7 reftex-active-toc))
3054 (match-string 1 (nth 7 reftex-active-toc)))
3055 "SECTION HEADING NOT FOUND")))
3056 (save-excursion
3057 (goto-char reftex-default-context-position)
3058 (unless (eq (string-to-char env) ?\\)
3059 (reftex-move-over-touching-args))
3060 (reftex-context-substring))))
3061
3062 ((stringp parse)
3063 (save-excursion
3064 (if (re-search-backward parse bound t)
3065 (progn
3066 (goto-char (match-end 0))
3067 (reftex-context-substring))
3068 "NO MATCH FOR CONTEXT REGEXP")))
3069
3070 ((integerp parse)
3071 (or (save-excursion
3072 (goto-char reftex-default-context-position)
3073 (reftex-nth-arg
3074 parse
3075 (nth 6 (assoc env reftex-env-or-mac-alist))))
3076 ""))
3077
3078 ((fboundp parse)
3079 ;; A hook function. Call it.
3080 (save-excursion
3081 (condition-case error-var
3082 (funcall parse env)
3083 (error (format "HOOK ERROR: %s" (cdr error-var))))))
3084 (t
3085 "ILLEGAL VALUE OF PARSE"))))
3086
3087 (defun reftex-where-am-I ()
3088 ;; Return the docstruct entry above point. Actually returns a cons
3089 ;; cell in which the cdr is a flag indicating if the information is
3090 ;; exact (t) or approximate (nil).
3091 (interactive)
3092
3093 (let ((docstruct (symbol-value reftex-docstruct-symbol))
3094 (cnt 0) rtn
3095 found)
3096 (save-excursion
3097 (while (not rtn)
3098 (incf cnt)
3099 (setq found (re-search-backward reftex-everything-regexp nil t))
3100 (setq rtn
3101 (cond
3102 ((not found)
3103 ;; no match
3104 (or
3105 (car (member (list 'bof (buffer-file-name)) docstruct))
3106 (not (setq cnt 2))
3107 (assq 'bof docstruct) ;; for safety reasons
3108 'corrupted))
3109 ((match-end 1)
3110 ;; Label
3111 (assoc (reftex-match-string 1)
3112 (symbol-value reftex-docstruct-symbol)))
3113 ((match-end 3)
3114 ;; Section
3115 (goto-char (1- (match-beginning 3)))
3116 (let* ((list (member (list 'bof (buffer-file-name))
3117 docstruct))
3118 (endelt (car (member (list 'eof (buffer-file-name))
3119 list)))
3120 rtn1)
3121 (while (and list (not (eq endelt (car list))))
3122 (if (and (eq (car (car list)) 'toc)
3123 (string= (buffer-file-name)
3124 (nth 3 (car list))))
3125 (cond
3126 ((equal (point)
3127 (or (and (markerp (nth 4 (car list)))
3128 (marker-position (nth 4 (car list))))
3129 (nth 8 (car list))))
3130 ;; Fits with marker position or recorded position
3131 (setq rtn1 (car list) list nil))
3132 ((looking-at (reftex-make-regexp-allow-for-ctrl-m
3133 (nth 7 (car list))))
3134 ;; Same title
3135 (setq rtn1 (car list) list nil cnt 2))))
3136 (pop list))
3137 rtn1))
3138 ((match-end 7)
3139 ;; Input or include...
3140 (car
3141 (member (list 'eof (reftex-find-tex-file
3142 (reftex-match-string 7)
3143 (cons
3144 (cdr (assq 'master-dir docstruct))
3145 reftex-tex-path)))
3146 docstruct)))
3147 ((match-end 8)
3148 (save-excursion
3149 (goto-char (match-end 8))
3150 (assoc (reftex-no-props
3151 (reftex-nth-arg-wrapper
3152 (reftex-match-string 8)))
3153 (symbol-value reftex-docstruct-symbol))))
3154 (t
3155 (error "This should not happen (reftex-where-am-I)"))))))
3156 (cons rtn (eq cnt 1))))
3157
3158 (defun reftex-parse-args (macro)
3159 ;; Return a list of macro name, nargs, arg-nr which is label and a list of
3160 ;; optional argument indices.
3161 (if (string-match "[[{]\\*?[]}]" macro)
3162 (progn
3163 (let ((must-match (substring macro 0 (match-beginning 0)))
3164 (args (substring macro (match-beginning 0)))
3165 opt-list nlabel (cnt 0))
3166 (while (string-match "\\`[[{]\\(\\*\\)?[]}]" args)
3167 (incf cnt)
3168 (when (eq ?\[ (string-to-char args))
3169 (push cnt opt-list))
3170 (when (and (match-end 1)
3171 (not nlabel))
3172 (setq nlabel cnt))
3173 (setq args (substring args (match-end 0))))
3174 (list must-match cnt nlabel opt-list)))
3175 nil))
3176
3177 (defsubst reftex-move-to-next-arg (&optional ignore)
3178 ;; Assuming that we are at the end of a macro name or a macro argument,
3179 ;; move forward to the opening parenthesis of the next argument.
3180 ;; This function understands the splitting of macros over several lines
3181 ;; in TeX.
3182 (cond
3183 ;; Just to be quick:
3184 ((memq (following-char) '(?\[ ?\{)))
3185 ;; Do a search
3186 ((looking-at "[ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*[[{]")
3187 (goto-char (1- (match-end 0)))
3188 t)
3189 (t nil)))
3190
3191 (defsubst reftex-move-to-previous-arg (&optional bound)
3192 ;; Assuming that we are in front of a macro argument,
3193 ;; move backward to the closing parenthesis of the previous argument.
3194 ;; This function understands the splitting of macros over several lines
3195 ;; in TeX.
3196 (cond
3197 ;; Just to be quick:
3198 ((memq (preceding-char) '(?\] ?\})))
3199 ;; Do a search
3200 ((re-search-backward
3201 "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\=" bound t)
3202 (goto-char (1+ (match-beginning 0)))
3203 t)
3204 (t nil)))
3205
3206 (defun reftex-nth-arg-wrapper (key)
3207 (let ((entry (assoc key reftex-env-or-mac-alist)))
3208 (reftex-nth-arg (nth 5 entry) (nth 6 entry))))
3209
3210 (defun reftex-nth-arg (n &optional opt-args)
3211 ;; Return the nth following {} or [] parentheses content.
3212 ;; OPT-ARGS is a list of argument numbers which are optional.
3213
3214 ;; If we are sitting at a macro start, skip to end of macro name.
3215 (and (eq (following-char) ?\\) (skip-chars-forward "a-zA-Z*\\\\"))
3216
3217 (if (= n 1000)
3218 ;; Special case: Skip all touching arguments
3219 (progn
3220 (reftex-move-over-touching-args)
3221 (reftex-context-substring))
3222
3223 ;; Do the real thing.
3224 (let ((cnt 1))
3225
3226 (when (reftex-move-to-next-arg)
3227
3228 (while (< cnt n)
3229 (while (and (member cnt opt-args)
3230 (eq (following-char) ?\{))
3231 (incf cnt))
3232 (when (< cnt n)
3233 (unless (and (condition-case nil
3234 (or (forward-list 1) t)
3235 (error nil))
3236 (reftex-move-to-next-arg)
3237 (incf cnt))
3238 (setq cnt 1000))))
3239
3240 (while (and (memq cnt opt-args)
3241 (eq (following-char) ?\{))
3242 (incf cnt)))
3243 (if (and (= n cnt)
3244 (> (skip-chars-forward "{\\[") 0))
3245 (reftex-context-substring)
3246 nil))))
3247
3248 (defun reftex-move-over-touching-args ()
3249 (condition-case nil
3250 (while (memq (following-char) '(?\[ ?\{))
3251 (forward-list 1))
3252 (error nil)))
3253
3254 (defun reftex-context-substring ()
3255 ;; Return up to 100 chars from point
3256 ;; When point is just after a { or [, limit string to matching parenthesis
3257 (cond
3258 ((or (= (preceding-char) ?\{)
3259 (= (preceding-char) ?\[))
3260 ;; Inside a list - get only the list.
3261 (buffer-substring-no-properties
3262 (point)
3263 (min (reftex-fp 150)
3264 (point-max)
3265 (condition-case nil
3266 (progn
3267 (up-list 1)
3268 (1- (point)))
3269 (error (point-max))))))
3270 (t
3271 ;; no list - just grab 100 characters
3272 (buffer-substring-no-properties (point) (min (reftex-fp 150) (point-max))))))
3273
3274 (defun reftex-init-section-numbers (&optional toc-entry)
3275 ;; Initialize the section numbers with zeros or with what is found
3276 ;; in the toc entry.
3277 (let* ((level (or (nth 5 toc-entry) -1))
3278 (numbers (nreverse (split-string (or (nth 6 toc-entry) "") "\\.")))
3279 (depth (1- (length reftex-section-numbers)))
3280 (i depth))
3281 (while (>= i 0)
3282 (if (> i level)
3283 (aset reftex-section-numbers i 0)
3284 (aset reftex-section-numbers i (string-to-int (or (car numbers) "0")))
3285 (pop numbers))
3286 (decf i))))
3287
3288 (defun reftex-section-number (section-numbers &optional level star)
3289 ;; Return a string with the current section number.
3290 ;; When LEVEL is non-nil, increase section numbers on that level.
3291 (let* ((depth (1- (length section-numbers))) idx n (string ""))
3292 (when level
3293 (when (and (> level -1) (not star))
3294 (aset section-numbers level (1+ (aref section-numbers level))))
3295 (setq idx (1+ level))
3296 (while (<= idx depth)
3297 (aset section-numbers idx 0)
3298 (incf idx)))
3299 (setq idx 0)
3300 (while (<= idx depth)
3301 (setq n (aref section-numbers idx))
3302 (setq string (concat string (if (not (string= string "")) "." "")
3303 (int-to-string n)))
3304 (incf idx))
3305 (save-match-data
3306 (if (string-match "\\`\\(0\\.\\)+" string)
3307 (setq string (replace-match "" nil nil string)))
3308 (if (string-match "\\(\\.0\\)+\\'" string)
3309 (setq string (replace-match "" nil nil string))))
3310 (if star
3311 (concat (make-string (1- (length string)) ?\ ) "*")
3312 string)))
3313
3314 ;; A variable to remember the index of the last label context shown
3315 (defvar reftex-last-cnt 0)
3316
3317 (defun reftex-select-label-callback (cnt)
3318 ;; Callback function called from the label selection in order to
3319 ;; show context in another window
3320 (let* ((this-window (selected-window))
3321 index entry label file buffer re)
3322 ;; pop to original buffer in order to get correct variables
3323 (catch 'exit
3324 (save-excursion
3325 (set-buffer reftex-call-back-to-this-buffer)
3326 (setq index (nth (or cnt 1) reftex-label-index-list)
3327 entry (nth index (symbol-value reftex-docstruct-symbol))
3328 label (nth 0 entry)
3329 file (nth 3 entry)))
3330
3331 ;; goto the file in another window
3332 (setq buffer (reftex-get-file-buffer-force
3333 file (not reftex-keep-temporary-buffers)))
3334 (if buffer
3335 ;; good - the file is available
3336 (switch-to-buffer-other-window buffer)
3337 ;; we have got a problem here. The file does not exist.
3338 ;; Let' get out of here..
3339 (ding)
3340 (throw 'exit nil))
3341
3342
3343 ;; search for that label
3344 (setq re (format reftex-find-label-regexp-format (regexp-quote label)))
3345 (unless (and (integerp cnt)
3346 (integerp reftex-last-cnt)
3347 (if (> cnt reftex-last-cnt)
3348 (re-search-forward re nil t)
3349 (re-search-backward re nil t)))
3350 (goto-char (point-min))
3351 (unless (re-search-forward re nil t)
3352 ;; Ooops. Must be in a macro with distributed args.
3353 (re-search-forward (format reftex-find-label-regexp-format2
3354 (regexp-quote label)) nil t)))
3355 (when (match-end 3)
3356 (reftex-highlight 0 (match-beginning 3) (match-end 3))
3357 (reftex-show-entry (- (point) (match-beginning 3))
3358 (- (point) (match-end 3)))
3359 (recenter (/ (window-height) 2)))
3360 (select-window this-window))))
3361
3362 (defun reftex-pop-to-label (label file-list &optional mark-to-kill highlight)
3363 ;; Find LABEL in any file in FILE-LIST in another window.
3364 ;; If mark-to-kill is non-nil, mark new buffer for killing.
3365 ;; If HIGHLIGHT is non-nil, highlight the label definition.
3366 (let* ((re1 (format reftex-find-label-regexp-format (regexp-quote label)))
3367 (re2 (format reftex-find-label-regexp-format2 (regexp-quote label)))
3368 (re-list (list re1 re2)) re
3369 (file-list-1 file-list)
3370 file buf)
3371 (catch 'exit
3372 (while (setq re (pop re-list))
3373 (setq file-list file-list-1)
3374 (while (setq file (pop file-list))
3375 (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
3376 (error "No such file %s" file))
3377 (set-buffer buf)
3378 (widen)
3379 (goto-char (point-min))
3380 (when (re-search-forward re nil t)
3381 (switch-to-buffer-other-window buf)
3382 (goto-char (match-beginning 0))
3383 (recenter (/ (window-height) 2))
3384 (if highlight
3385 (reftex-highlight 0 (match-beginning 3) (match-end 3)))
3386 (throw 'exit (selected-window)))))
3387 (error "Label %s not found" label))))
3388
3389 (defun reftex-find-duplicate-labels ()
3390 "Produce a list of all duplicate labels in the document."
3391
3392 (interactive)
3393
3394 ;; Rescan the document to make sure
3395 (reftex-access-scan-info t)
3396
3397 (let ((master (reftex-TeX-master-file))
3398 (cnt 0)
3399 (dlist
3400 (mapcar
3401 '(lambda(x)
3402 (let (x1)
3403 (cond
3404 ((memq (car x)
3405 '(toc bof eof bib label-numbers xr xr-doc
3406 master-dir file-error is-multi))
3407 nil)
3408 (t
3409 (setq x1 (reftex-all-assoc-string
3410 (car x) (symbol-value reftex-docstruct-symbol)))
3411 (if (< 1 (length x1))
3412 (append (list (car x))
3413 (mapcar '(lambda(x)
3414 (abbreviate-file-name (nth 3 x))) x1))
3415 (list nil))))))
3416 (reftex-uniquify (symbol-value reftex-docstruct-symbol)))))
3417
3418 (setq dlist (reftex-uniquify dlist))
3419 (if (null dlist) (error "No duplicate labels in document"))
3420 (switch-to-buffer-other-window "*Duplicate Labels*")
3421 (make-local-variable 'TeX-master)
3422 (setq TeX-master master)
3423 (erase-buffer)
3424 (insert " MULTIPLE LABELS IN CURRENT DOCUMENT:\n")
3425 (insert
3426 " Move point to label and type `r' to run a query-replace on the label\n"
3427 " and its references. Type `q' to exit this buffer.\n\n")
3428 (insert " LABEL FILE\n")
3429 (insert " -------------------------------------------------------------\n")
3430 (use-local-map (make-sparse-keymap))
3431 (local-set-key [?q] '(lambda () (interactive)
3432 (kill-buffer (current-buffer)) (delete-window)))
3433 (local-set-key [?r] 'reftex-change-label)
3434 (while dlist
3435 (when (and (car (car dlist))
3436 (cdr (car dlist)))
3437 (incf cnt)
3438 (insert (mapconcat '(lambda(x) x) (car dlist) "\n ") "\n"))
3439 (pop dlist))
3440 (goto-char (point-min))
3441 (when (= cnt 0)
3442 (kill-buffer (current-buffer))
3443 (delete-window)
3444 (message "Document does not contain duplicate labels."))))
3445
3446 (defun reftex-all-assq (key list)
3447 ;; Return a list of all associations of KEY in LIST. Comparison with string=
3448 (let (rtn)
3449 (while (setq list (memq (assq key list) list))
3450 (push (car list) rtn)
3451 (pop list))
3452 (nreverse rtn)))
3453
3454 (defun reftex-all-assoc-string (key list)
3455 ;; Return a list of all associations of KEY in LIST. Comparison with string=
3456 (let (rtn)
3457 (while list
3458 (if (string= (car (car list)) key)
3459 (push (car list) rtn))
3460 (pop list))
3461 (nreverse rtn)))
3462
3463 (defun reftex-kill-temporary-buffers (&optional buffer)
3464 ;; Kill all buffers in the list reftex-kill-temporary-buffers.
3465 (cond
3466 (buffer
3467 (when (member buffer reftex-buffers-to-kill)
3468 (kill-buffer buffer)
3469 (setq reftex-buffers-to-kill
3470 (delete buffer reftex-buffers-to-kill))))
3471 (t
3472 (while (setq buffer (pop reftex-buffers-to-kill))
3473 (when (bufferp buffer)
3474 (and (buffer-modified-p buffer)
3475 (y-or-n-p (format "Save file %s? "
3476 (buffer-file-name buffer)))
3477 (save-excursion
3478 (set-buffer buffer)
3479 (save-buffer)))
3480 (kill-buffer buffer))
3481 (pop reftex-buffers-to-kill)))))
3482
3483 (defun reftex-show-entry (beg-hlt end-hlt)
3484 ;; Show entry if point is hidden by outline mode
3485 (let* ((pos (point))
3486 (n (/ (window-height) 2))
3487 (beg (save-excursion
3488 (re-search-backward "[\n\r]" nil 1 n) (point)))
3489 (end (save-excursion
3490 (re-search-forward "[\n\r]" nil 1 n) (point))))
3491 (if (and reftex-auto-show-entry
3492 (string-match
3493 "\r" (buffer-substring beg end)))
3494 (cond
3495 ((eq t reftex-auto-show-entry)
3496 (subst-char-in-region
3497 (save-excursion (search-backward "\n" nil t) (point))
3498 (save-excursion (search-forward "\n" nil t) (point))
3499 ?\r ?\n t))
3500 ((eq reftex-auto-show-entry 'copy)
3501 (let ((string (buffer-substring beg end)))
3502 (switch-to-buffer "*RefTeX Context Copy*")
3503 (setq buffer-read-only nil)
3504 (erase-buffer)
3505 (insert string)
3506 (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
3507 (goto-char (- pos beg))
3508 (reftex-highlight 0 (1+ (- (point) beg-hlt))
3509 (1+ (- (point) end-hlt)))
3510 (when (reftex-refontify)
3511 (make-local-variable 'font-lock-defaults)
3512 (setq font-lock-defaults nil)
3513 (let ((major-mode 'latex-mode))
3514 (font-lock-set-defaults)
3515 (font-lock-fontify-buffer)))
3516 (setq buffer-read-only t)))
3517 ))))
3518
3519 (defun reftex-nicify-text (text)
3520 ;; Make TEXT nice for inclusion as context into label menu
3521 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text) ; remove extra whitespace
3522 (setq text (replace-match " " nil t text)))
3523 (if (string-match "\\\\end{.*" text) ; nothing beyond \end{
3524 (setq text (replace-match "" nil t text)))
3525 (if (string-match "\\\\label{[^}]*}" text) ; kill the label
3526 (setq text (replace-match "" nil t text)))
3527 (if (string-match "\\`[ }]+" text) ; leading whitespace, `}'
3528 (setq text (replace-match "" nil t text)))
3529 (cond
3530 ((> (length text) 100) (substring text 0 100))
3531 ((= (length text) 0) " ")
3532 (t text)))
3533
3534 (defun reftex-typekey-check (typekey conf-variable &optional n)
3535 ;; Check if CONF-VARIABLE is true or contains TYPEKEY
3536 (and n (setq conf-variable (nth n conf-variable)))
3537 (or (eq conf-variable t)
3538 (and (stringp conf-variable)
3539 (string-match (concat "[" conf-variable "]") typekey))))
3540
3541 ;;; ===========================================================================
3542 ;;;
3543 ;;; Table of contents
3544
3545 ;; We keep at most one *toc* buffer - it is easy to make them
3546
3547 (defvar reftex-last-toc-master nil
3548 "Stores the name of the tex file that `reftex-toc' was last run on.")
3549
3550 (defvar reftex-last-toc-file nil
3551 "Stores the file name from which `reftex-toc' was called. For redo command.")
3552
3553 (defvar reftex-last-window-height nil)
3554
3555 (defvar reftex-toc-return-marker (make-marker)
3556 "Marker which makes it possible to return from toc to old position.")
3557
3558 (defconst reftex-toc-help
3559 " AVAILABLE KEYS IN TOC BUFFER
3560 ============================
3561 SPC Show the corresponding section of the LaTeX document.
3562 TAB Goto the section.
3563 RET Goto the section and hide the *toc* buffer (also on mouse-2).
3564 q / Q Hide/Kill *toc* buffer, return to position of last reftex-toc command.
3565 f Toggle follow mode on and off.
3566 r / g Reparse the LaTeX document.
3567 x Switch to TOC of external document (with LaTeX package `xr').")
3568
3569 (defun reftex-toc ()
3570 "Show the table of contents for the current document.
3571 When called with a raw C-u prefix, rescan the document first."
3572
3573 (interactive)
3574
3575 (if (or (not (string= reftex-last-toc-master (reftex-TeX-master-file)))
3576 current-prefix-arg)
3577 (reftex-empty-toc-buffer))
3578
3579 (setq reftex-last-toc-file (buffer-file-name))
3580 (setq reftex-last-toc-master (reftex-TeX-master-file))
3581
3582 (set-marker reftex-toc-return-marker (point))
3583
3584 ;; If follow mode is active, arrange to delay it one command
3585 (if reftex-toc-follow-mode
3586 (setq reftex-toc-follow-mode 1))
3587
3588 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
3589 (reftex-access-scan-info current-prefix-arg)
3590
3591 (let* ((all (symbol-value reftex-docstruct-symbol))
3592 (xr-data (assq 'xr all))
3593 (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
3594 (where (reftex-nearest-section))
3595 toc1 cell startpos)
3596
3597 (if (get-buffer-window "*toc*")
3598 (select-window (get-buffer-window "*toc*"))
3599 (setq reftex-last-window-height (window-height)) ; remember
3600 (split-window-vertically)
3601 (switch-to-buffer (get-buffer-create "*toc*")))
3602
3603 (cond
3604 ;; buffer is empty - fill it with the table of contents
3605 ((= (buffer-size) 0)
3606
3607 (local-set-key "?" 'reftex-toc-show-help)
3608 (local-set-key " " 'reftex-toc-view-line)
3609 (local-set-key "\C-m" 'reftex-toc-goto-line-and-hide)
3610 (local-set-key "\C-i" 'reftex-toc-goto-line)
3611 (local-set-key "r" 'reftex-toc-redo)
3612 (local-set-key "R" 'reftex-toc-Redo)
3613 (local-set-key "g" 'revert-buffer)
3614 (local-set-key "q" 'reftex-toc-quit)
3615 (local-set-key "Q" 'reftex-toc-quit-and-kill)
3616 (local-set-key "f" 'reftex-toc-toggle-follow)
3617 (local-set-key "x" 'reftex-toc-external)
3618 (local-set-key [(mouse-2)] 'reftex-toc-mouse-goto-line-and-hide); Emacs
3619 (local-set-key [(button2)] 'reftex-toc-mouse-goto-line-and-hide); XEmacs
3620 (make-local-variable 'revert-buffer-function)
3621 (setq revert-buffer-function 'reftex-toc-redo)
3622 (setq truncate-lines t)
3623 (make-local-hook 'post-command-hook)
3624 (make-local-hook 'pre-command-hook)
3625 (setq post-command-hook '(reftex-toc-post-command-hook))
3626 (setq pre-command-hook '(reftex-toc-pre-command-hook))
3627
3628 (insert (format
3629 "TABLE-OF-CONTENTS on %s
3630 SPC=view TAB=goto RET=goto+hide [q]uit [r]escan [f]ollow-mode e[x]tern [?]Help
3631 -------------------------------------------------------------------------------
3632 " (abbreviate-file-name reftex-last-toc-master)))
3633 (setq startpos (point))
3634
3635 (if (reftex-use-fonts)
3636 (put-text-property 1 (point) 'face 'font-lock-keyword-face))
3637 (put-text-property 1 (point) 'intangible t)
3638 (put-text-property 1 2 'xr-alist xr-alist)
3639
3640 (while all
3641 (setq cell (car all)
3642 all (cdr all))
3643 (when (eq (car cell) 'toc)
3644 (setq toc1 (concat (nth 2 cell) "\n"))
3645 (put-text-property 0 (length toc1) 'toc cell toc1)
3646 (insert toc1)))
3647
3648 (backward-delete-char 1)
3649
3650 (setq buffer-read-only t))
3651 (t
3652 (goto-line 3)
3653 (beginning-of-line)
3654 (setq startpos (point))))
3655
3656 ;; Find the correct section
3657 (goto-char (point-max))
3658 (beginning-of-line)
3659 (while (and (> (point) startpos)
3660 (not (eq (get-text-property (point) 'toc) where)))
3661 (beginning-of-line 0))))
3662
3663 (defun reftex-nearest-section ()
3664 ;; Return (file . find) of nearest section command
3665 (let* ((here-I-am (car (reftex-where-am-I))))
3666 (reftex-last-assoc-before-elt
3667 'toc here-I-am (symbol-value reftex-docstruct-symbol))))
3668
3669 (defun reftex-toc-pre-command-hook ()
3670 ;; used as pre command hook in *toc* buffer
3671 (reftex-unhighlight 0)
3672 (reftex-unhighlight 1))
3673
3674 (defun reftex-toc-post-command-hook ()
3675 ;; used in the post-command-hook for the *toc* buffer
3676 (and (> (point) 1)
3677 (save-excursion
3678 (reftex-highlight 1
3679 (progn (beginning-of-line) (point))
3680 (progn (end-of-line) (point)))))
3681 (cond
3682 ((integerp reftex-toc-follow-mode)
3683 ;; remove delayed action
3684 (setq reftex-toc-follow-mode t))
3685 (reftex-toc-follow-mode
3686 ;; show context in other window
3687 (condition-case nil
3688 (reftex-toc-visit-line)
3689 (error (ding) t)))))
3690
3691 (defun reftex-empty-toc-buffer ()
3692 (if (get-buffer "*toc*")
3693 (save-excursion
3694 (set-buffer "*toc*")
3695 (setq buffer-read-only nil)
3696 (erase-buffer))))
3697
3698 (defun reftex-re-enlarge ()
3699 (enlarge-window
3700 (max 0 (- (or reftex-last-window-height (window-height))
3701 (window-height)))))
3702
3703 (defun reftex-toc-show-help ()
3704 (interactive)
3705 (with-output-to-temp-buffer "*RefTeX Help*"
3706 (princ reftex-toc-help))
3707 ;; If follow mode is active, arrange to delay it one command
3708 (if reftex-toc-follow-mode
3709 (setq reftex-toc-follow-mode 1)))
3710
3711 (defun reftex-toc-toggle-follow ()
3712 "Toggle toc-follow mode.
3713 (It is not really a mode, just a flag)."
3714 (interactive)
3715 (setq reftex-toc-follow-mode (not reftex-toc-follow-mode)))
3716 (defun reftex-toc-view-line ()
3717 "View document location in other window."
3718 (interactive)
3719 (reftex-toc-visit-line))
3720 (defun reftex-toc-goto-line-and-hide ()
3721 "Go to document location in other window. Hide the *toc* window."
3722 (interactive)
3723 (reftex-toc-visit-line 'hide))
3724 (defun reftex-toc-goto-line ()
3725 "Go to document location in other window. Hide the *toc* window."
3726 (interactive)
3727 (reftex-toc-visit-line t))
3728 (defun reftex-toc-mouse-goto-line-and-hide (ev)
3729 "Go to document location in other window. Hide the *toc* window."
3730 (interactive "e")
3731 (mouse-set-point ev)
3732 (reftex-toc-visit-line 'hide))
3733 (defun reftex-toc-quit ()
3734 "Hide the *toc* window and do not move point."
3735 (interactive)
3736 (or (one-window-p) (delete-window))
3737 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
3738 (reftex-re-enlarge)
3739 (goto-char (or (marker-position reftex-toc-return-marker) (point))))
3740 (defun reftex-toc-quit-and-kill ()
3741 "Kill the *toc* buffer."
3742 (interactive)
3743 (kill-buffer "*toc*")
3744 (or (one-window-p) (delete-window))
3745 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
3746 (reftex-re-enlarge)
3747 (goto-char (marker-position reftex-toc-return-marker)))
3748 (defun reftex-toc-redo (&rest ignore)
3749 "Regenerate the *toc* buffer by reparsing file of last reftex-toc command."
3750 (interactive)
3751 (if reftex-enable-partial-scans
3752 (let ((file (nth 3 (get-text-property (point) 'toc))))
3753 (if (not file)
3754 (error "Don't know which file to rescan. Try `R'.")
3755 (switch-to-buffer-other-window
3756 (reftex-get-file-buffer-force file))
3757 (setq current-prefix-arg '(4))
3758 (reftex-toc)))
3759 (reftex-toc-Redo))
3760 (reftex-kill-temporary-buffers))
3761 (defun reftex-toc-Redo (&rest ignore)
3762 "Regenerate the *toc* buffer by reparsing the entire document."
3763 (interactive)
3764 (switch-to-buffer-other-window
3765 (reftex-get-file-buffer-force reftex-last-toc-file))
3766 (setq current-prefix-arg '(16))
3767 (reftex-toc))
3768 (defun reftex-toc-external (&rest ignore)
3769 "Switch to table of contents of an external document."
3770 (interactive)
3771 (let* ((xr-alist (get-text-property 1 'xr-alist))
3772 (xr-index (reftex-select-external-document
3773 xr-alist 0)))
3774 (switch-to-buffer-other-window (or (reftex-get-file-buffer-force
3775 (cdr (nth xr-index xr-alist)))
3776 (error "Cannot switch document")))
3777 (reftex-toc)))
3778
3779 (defun reftex-toc-visit-line (&optional final)
3780 ;; Visit the tex file corresponding to the toc entry on the current line.
3781 ;; If FINAL is t, stay there
3782 ;; If FINAL is 'hide, hide the *toc* window.
3783 ;; Otherwise, move cursor back into *toc* window.
3784 ;; This function is pretty clever about finding back a section heading,
3785 ;; even if the buffer is not live, or things like outline, x-symbol etc.
3786 ;; have been active.
3787
3788 (let* ((toc (get-text-property (point) 'toc))
3789 (file (nth 3 toc))
3790 (marker (nth 4 toc))
3791 (level (nth 5 toc))
3792 (literal (nth 7 toc))
3793 (emergency-point (nth 8 toc))
3794 (toc-window (selected-window))
3795 show-window show-buffer match)
3796
3797 (unless toc (error "Don't know which toc line to visit"))
3798
3799 (setq match
3800 (cond
3801 ((and (markerp marker) (marker-buffer marker))
3802 ;; Buffer is still live and we have the marker. Should be easy.
3803 (switch-to-buffer-other-window (marker-buffer marker))
3804 (goto-char (marker-position marker))
3805 (or (looking-at (regexp-quote literal))
3806 (looking-at (reftex-make-regexp-allow-for-ctrl-m literal))
3807 (looking-at (reftex-make-desparate-section-regexp literal))
3808 (looking-at (concat "\\\\"
3809 (regexp-quote
3810 (car (rassq level reftex-section-levels)))
3811 "[[{]"))))
3812 (t
3813 ;; Marker is lost. Use the backup method.
3814 (switch-to-buffer-other-window
3815 (reftex-get-file-buffer-force file nil))
3816 (goto-char (or emergency-point (point-min)))
3817 (or (looking-at (regexp-quote literal))
3818 (let ((pos (point)))
3819 (re-search-backward "\\`\\|[\r\n][ \t]*[\r\n]" nil t)
3820 (or (reftex-nearest-match (regexp-quote literal) pos)
3821 (reftex-nearest-match
3822 (reftex-make-regexp-allow-for-ctrl-m literal) pos)
3823 (reftex-nearest-match
3824 (reftex-make-desparate-section-regexp literal) pos)))))
3825 ))
3826
3827 (setq show-window (selected-window)
3828 show-buffer (current-buffer))
3829
3830 (unless match
3831 (select-window toc-window)
3832 (error "Cannot find line"))
3833
3834 (goto-char (match-beginning 0))
3835 (recenter 1)
3836 (reftex-highlight 0 (match-beginning 0) (match-end 0) (current-buffer))
3837
3838 (select-window toc-window)
3839
3840 ;; use the `final' parameter to decide what to do next
3841 (cond
3842 ((eq final t)
3843 (reftex-unhighlight 0)
3844 (select-window show-window))
3845 ((eq final 'hide)
3846 (reftex-unhighlight 0)
3847 (or (one-window-p) (delete-window))
3848 (switch-to-buffer show-buffer)
3849 (reftex-re-enlarge))
3850 (t nil))))
3851
3852 ;;; ===========================================================================
3853 ;;;
3854 ;;; BibTeX citations.
3855
3856 ;; Variables and constants
3857
3858 ;; Define variable to silence compiler warnings
3859 (defvar reftex-found-list)
3860 (defvar reftex-cite-format-builtin)
3861
3862 ;; The history list of regular expressions used for citations
3863 (defvar reftex-cite-regexp-hist nil)
3864
3865 ;; Prompt and help string for citation selection
3866 (defconst reftex-citation-prompt
3867 "Select: [n]ext [p]revious [r]estrict [ ]full_entry [q]uit RET [?]Help+more")
3868
3869 (defconst reftex-citation-help
3870 "AVAILABLE KEYS IN MAKE CITATION MENU
3871 ---------------------------------------
3872 n / p Go to next/previous entry (Cursor motion works as well).
3873 C-s / C-r Search forward/backward. Use repeated C-s/C-r as in isearch.
3874 g / r Start over with new regexp / Restrict with additional regexp.
3875 SPC Show full database entry in other window.
3876 f Toggle follow mode: Other window will follow with full db entry.
3877 q Quit without inserting \\cite macro into buffer.
3878 e Recursive edit into other window.
3879 RET / a Accept current entry / Accept all entries.")
3880
3881 ;; Find bibtex files
3882
3883 (defun reftex-get-bibfile-list ()
3884 ;; Return list of bibfiles for current document.
3885 ;; When using the chapterbib or bibunits package you should either
3886 ;; use the same database files everywhere, or separate parts using
3887 ;; different databases into different files (included into the mater file).
3888 ;; Then this function will return the applicable database files.
3889
3890 ;; Ensure access to scanning info
3891 (reftex-access-scan-info)
3892 (or
3893 ;; Try inside this file (and its includes)
3894 (cdr (reftex-last-assoc-before-elt
3895 'bib (list 'eof (buffer-file-name))
3896 (member (list 'bof (buffer-file-name))
3897 (symbol-value reftex-docstruct-symbol))))
3898 ;; Try after the beginning of this file
3899 (cdr (assq 'bib (member (list 'bof (buffer-file-name))
3900 (symbol-value reftex-docstruct-symbol))))
3901 ;; Anywhere in the entire document
3902 (cdr (assq 'bib (symbol-value reftex-docstruct-symbol)))
3903 (error "\\bibliography statment missing or .bib files not found.")))
3904
3905 (defun reftex-find-tex-file (file master-dir &optional die)
3906 ;; Find FILE in MASTER-DIR or on reftex-tex-path.
3907 ;; FILE may be given without the .tex extension.
3908 (reftex-access-search-path "tex")
3909 (let* ((path (cons master-dir reftex-tex-path))
3910 file1)
3911 (setq file1
3912 (or (reftex-find-file-on-path (concat file ".tex") path)
3913 (reftex-find-file-on-path file path)))
3914 (unless file1
3915 (reftex-access-search-path "tex" t file)
3916 (setq path (cons master-dir reftex-tex-path))
3917 (setq file1
3918 (or (reftex-find-file-on-path (concat file ".tex") path)
3919 (reftex-find-file-on-path file path))))
3920 (cond (file1 file1)
3921 (die (error "No such file: %s" file) nil)
3922 (t (message "No such file: %s (ignored)" file) nil))))
3923
3924 (defun reftex-find-bib-file (file master-dir &optional die)
3925 ;; Find FILE in MASTER-DIR or on reftex-bib-path
3926 (reftex-access-search-path "bib")
3927 (let ((file1 (reftex-find-file-on-path
3928 file (cons master-dir reftex-bib-path))))
3929 (unless file1
3930 (reftex-access-search-path "bib" t file)
3931 (setq file1 (reftex-find-file-on-path
3932 file (cons master-dir reftex-bib-path))))
3933 (cond (file1 file1)
3934 (die (error "No such file: %s" file) nil)
3935 (t (message "No such file: %s (ignored)" file) nil))))
3936
3937 ;; Find a certain reference in any of the BibTeX files.
3938
3939 (defun reftex-pop-to-bibtex-entry (key file-list
3940 &optional mark-to-kill highlight)
3941 ;; Find BibTeX KEY in any file in FILE-LIST in another window.
3942 ;; If mark-to-kill is non-nil, mark new buffer to kill."
3943
3944 (let* ((re (concat "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*" (regexp-quote key) "[ \t\n\r,]"))
3945 (window-conf (current-window-configuration))
3946 file buf)
3947 (catch 'exit
3948 (switch-to-buffer-other-window (current-buffer))
3949 (while file-list
3950 (setq file (car file-list)
3951 file-list (cdr file-list))
3952 (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
3953 (error "No such file %s" file))
3954 (switch-to-buffer buf)
3955 (widen)
3956 (goto-char (point-min))
3957 (when (re-search-forward re nil t)
3958 (goto-char (match-beginning 0))
3959 (recenter 0)
3960 (if highlight
3961 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
3962 (throw 'exit (selected-window))))
3963 (set-window-configuration window-conf)
3964 (beep)
3965 (message "No BibTeX entry with citation key %s" key))))
3966
3967 ;; Parse bibtex buffers
3968
3969 (defun reftex-extract-bib-entries (buffers &optional get-word)
3970 ;; Extract bib entries which match regexps from BUFFERS.
3971 ;; BUFFERS is a list of buffers or file names.
3972 ;; Return list with entries."
3973 (let* (re-list first-re rest-re
3974 (buffer-list (if (listp buffers) buffers (list buffers)))
3975 found-list entry buffer1 buffer alist
3976 key-point start-point end-point)
3977
3978 (setq re-list (split-string
3979 (read-string "RegExp [ && RegExp...]: "
3980 nil 'reftex-cite-regexp-hist)
3981 "[ \t]*&&[ \t]*"))
3982
3983 (setq first-re (car re-list) ; We'll use the first re to find things,
3984 rest-re (cdr re-list)) ; the other to narrow down.
3985 (if (string-match "\\`[ \t]*\\'" first-re)
3986 (error "Empty regular expression"))
3987
3988 (save-excursion
3989 (save-window-excursion
3990
3991 ;; Walk through all bibtex files
3992 (while buffer-list
3993 (setq buffer (car buffer-list)
3994 buffer-list (cdr buffer-list))
3995 (if (and (bufferp buffer)
3996 (buffer-live-p buffer))
3997 (setq buffer1 buffer)
3998 (setq buffer1 (reftex-get-file-buffer-force
3999 buffer (not reftex-keep-temporary-buffers))))
4000 (if (not buffer1)
4001 (error "Cannot find BibTeX file %s" buffer)
4002 (message "Scanning bibliography database %s" buffer1))
4003
4004 (set-buffer buffer1)
4005 (save-excursion
4006 (goto-char (point-min))
4007 (while (re-search-forward first-re nil t)
4008 (catch 'search-again
4009 (setq key-point (point))
4010 (unless (re-search-backward
4011 "\\(\\`\\|[\n\r]\\)[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*[{(]" nil t)
4012 (throw 'search-again nil))
4013 (setq start-point (point))
4014 (goto-char (match-end 0))
4015 (condition-case nil
4016 (up-list 1)
4017 (error (goto-char key-point)
4018 (throw 'search-again nil)))
4019 (setq end-point (point))
4020
4021 ;; Ignore @string, @comment and @c entries or things
4022 ;; outside entries
4023 (when (or (string= (downcase (match-string 2)) "string")
4024 (string= (downcase (match-string 2)) "comment")
4025 (string= (downcase (match-string 2)) "c")
4026 (< (point) key-point)) ; this means match not in {}
4027 (goto-char key-point)
4028 (throw 'search-again nil))
4029
4030 ;; Well, we have got a match
4031 (setq entry (concat
4032 (buffer-substring start-point (point)) "\n"))
4033
4034 ;; Check if other regexp match as well
4035 (setq re-list rest-re)
4036 (while re-list
4037 (unless (string-match (car re-list) entry)
4038 ;; nope - move on
4039 (throw 'search-again nil))
4040 (pop re-list))
4041
4042 (setq alist (reftex-parse-bibtex-entry
4043 nil start-point end-point))
4044 (push (cons "&entry" entry) alist)
4045
4046 ;; check for crossref entries
4047 (if (assoc "crossref" alist)
4048 (setq alist
4049 (append
4050 alist (reftex-get-crossref-alist alist))))
4051
4052 ;; format the entry
4053 (push (cons "&formatted" (reftex-format-bib-entry alist))
4054 alist)
4055
4056 ;; add it to the list
4057 (push alist found-list))))
4058 (reftex-kill-temporary-buffers))))
4059 (setq found-list (nreverse found-list))
4060
4061 ;; Sorting
4062 (cond
4063 ((eq 'author reftex-sort-bibtex-matches)
4064 (sort found-list 'reftex-bib-sort-author))
4065 ((eq 'year reftex-sort-bibtex-matches)
4066 (sort found-list 'reftex-bib-sort-year))
4067 ((eq 'reverse-year reftex-sort-bibtex-matches)
4068 (sort found-list 'reftex-bib-sort-year-reverse))
4069 (t found-list))))
4070
4071 (defun reftex-bib-sort-author (e1 e2)
4072 (let ((al1 (reftex-get-bib-names "author" e1))
4073 (al2 (reftex-get-bib-names "author" e2)))
4074 (while (and al1 al2 (string= (car al1) (car al2)))
4075 (pop al1)
4076 (pop al2))
4077 (if (and (stringp (car al1))
4078 (stringp (car al2)))
4079 (string< (car al1) (car al2))
4080 (not (stringp (car al1))))))
4081
4082 (defun reftex-bib-sort-year (e1 e2)
4083 (< (string-to-int (cdr (assoc "year" e1)))
4084 (string-to-int (cdr (assoc "year" e2)))))
4085
4086 (defun reftex-bib-sort-year-reverse (e1 e2)
4087 (> (string-to-int (or (cdr (assoc "year" e1)) "0"))
4088 (string-to-int (or (cdr (assoc "year" e2)) "0"))))
4089
4090 (defun reftex-get-crossref-alist (entry)
4091 ;; return the alist from a crossref entry
4092 (let ((crkey (cdr (assoc "crossref" entry)))
4093 start)
4094 (save-excursion
4095 (save-restriction
4096 (widen)
4097 (if (re-search-forward
4098 (concat "@\\w+[{(][ \t\n\r]*" (regexp-quote crkey)
4099 "[ \t\n\r]*,") nil t)
4100 (progn
4101 (setq start (match-beginning 0))
4102 (condition-case nil
4103 (up-list 1)
4104 (error nil))
4105 (reftex-parse-bibtex-entry nil start (point)))
4106 nil)))))
4107
4108 ;; Parse and format individual entries
4109
4110 (defun reftex-get-bib-names (field entry)
4111 ;; Return a list with the author or editor anmes in ENTRY
4112 (let ((names (reftex-get-bib-field field entry)))
4113 (if (equal "" names)
4114 (setq names (reftex-get-bib-field "editor" entry)))
4115 (while (string-match "\\band\\b[ \t]*" names)
4116 (setq names (replace-match "\n" nil t names)))
4117 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
4118 (setq names (replace-match "" nil t names)))
4119 (while (string-match "^[ \t]+\\|[ \t]+$" names)
4120 (setq names (replace-match "" nil t names)))
4121 (while (string-match "[ \t][ \t]+" names)
4122 (setq names (replace-match " " nil t names)))
4123 (split-string names "\n")))
4124
4125 (defun reftex-parse-bibtex-entry (entry &optional from to)
4126 (let (alist key start field)
4127 (save-excursion
4128 (save-restriction
4129 (if entry
4130 (progn
4131 (switch-to-buffer "*RefTeX-scratch*")
4132 (fundamental-mode)
4133 (erase-buffer)
4134 (insert entry))
4135 (widen)
4136 (narrow-to-region from to))
4137 (goto-char (point-min))
4138
4139 (if (re-search-forward
4140 "@\\(\\w+\\)[ \t\n\r]*[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
4141 (setq alist
4142 (list
4143 (cons "&type" (downcase (reftex-match-string 1)))
4144 (cons "&key" (reftex-match-string 2)))))
4145 (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
4146 (setq key (downcase (reftex-match-string 1)))
4147 (cond
4148 ((= (following-char) ?{)
4149 (forward-char 1)
4150 (setq start (point))
4151 (condition-case nil
4152 (up-list 1)
4153 (error nil)))
4154 ((= (following-char) ?\")
4155 (forward-char 1)
4156 (setq start (point))
4157 (while (and (search-forward "\"" nil t)
4158 (= ?\\ (char-after (- (point) 2))))))
4159 (t
4160 (setq start (point))
4161 (re-search-forward "[ \t\n\r,}]" nil 1)))
4162 (setq field (buffer-substring-no-properties start (1- (point))))
4163 ;; remove extra whitesp
4164 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
4165 (setq field (replace-match " " nil t field)))
4166 ;; remove leading garbage
4167 (if (string-match "^[ \t{]+" field)
4168 (setq field (replace-match "" nil t field)))
4169 ;; remove trailing garbage
4170 (if (string-match "[ \t}]+$" field)
4171 (setq field (replace-match "" nil t field)))
4172 (push (cons key field) alist))))
4173 alist))
4174
4175 (defun reftex-get-bib-field (fieldname entry)
4176 ;; Extract the field FIELDNAME from an ENTRY
4177 (or (cdr (assoc fieldname entry))
4178 ""))
4179
4180 (defun reftex-format-bib-entry (entry)
4181 ;; Format a BibTeX ENTRY so that it is nice to look at
4182 (let*
4183 ((auth-list (reftex-get-bib-names "author" entry))
4184 (authors (mapconcat '(lambda (x) x) auth-list ", "))
4185 (year (reftex-get-bib-field "year" entry))
4186 (title (reftex-get-bib-field "title" entry))
4187 (type (reftex-get-bib-field "&type" entry))
4188 (key (reftex-get-bib-field "&key" entry))
4189 (extra
4190 (cond
4191 ((equal type "article")
4192 (concat (reftex-get-bib-field "journal" entry) " "
4193 (reftex-get-bib-field "volume" entry) ", "
4194 (reftex-get-bib-field "pages" entry)))
4195 ((equal type "book")
4196 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
4197 ((equal type "phdthesis")
4198 (concat "PhD: " (reftex-get-bib-field "school" entry)))
4199 ((equal type "mastersthesis")
4200 (concat "Master: " (reftex-get-bib-field "school" entry)))
4201 ((equal type "inbook")
4202 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
4203 ", pp. " (reftex-get-bib-field "pages" entry)))
4204 ((or (equal type "conference")
4205 (equal type "incollection")
4206 (equal type "inproceedings"))
4207 (concat "in: " (reftex-get-bib-field "booktitle" entry)))
4208 (t ""))))
4209 (setq authors (reftex-truncate authors 30 t t))
4210 (when (reftex-use-fonts)
4211 (put-text-property 0 (length authors) 'face 'font-lock-keyword-face
4212 authors)
4213 (put-text-property 0 (length title) 'face 'font-lock-comment-face
4214 title)
4215 (put-text-property 0 (length extra) 'face 'font-lock-reference-face
4216 extra))
4217 (concat key "\n " authors " " year " " extra "\n " title "\n\n")))
4218
4219 ;; Make a citation
4220
4221 (defun reftex-citation (&optional no-insert)
4222 "Make a citation using BibTeX database files.
4223 After asking for a Regular Expression, it scans the buffers with
4224 bibtex entries (taken from the \\bibliography command) and offers the
4225 matching entries for selection. The selected entry is formated according
4226 to `reftex-cite-format' and inserted into the buffer.
4227 If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
4228 The regular expression uses an expanded syntax: && is interpreted as `and'.
4229 Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
4230 When this function is called with point inside the braces of a \\cite
4231 command, it will add another key, ignoring the value of `reftex-cite-format'.
4232 When called with a numeric prefix, that many citations will be made and all
4233 put into the same \\cite command.
4234 When called with just C-u as prefix, enforces rescan of buffer for
4235 bibliography statement (e.g. if it was changed)."
4236
4237 (interactive)
4238
4239 ;; check for recursive edit
4240 (reftex-check-recursive-edit)
4241
4242 ;; if there is just 1 C-u prefix arg, force to rescan buffer
4243 (reftex-access-scan-info current-prefix-arg)
4244
4245 ;; Call reftex-do-citation, but protected
4246 (unwind-protect
4247 (reftex-do-citation current-prefix-arg no-insert)
4248 (reftex-kill-temporary-buffers)))
4249
4250 (defun reftex-do-citation (&optional arg no-insert)
4251 ;; This really does the work of reftex-citation.
4252
4253 ;; Check if there is already a cite command at point and change cite format
4254 ;; in order to only add another reference in the same cite command.
4255 (let (key format (macro (car (car (reftex-what-macro t)))))
4256 (if (and (stringp macro)
4257 (string-match "\\`\\\\cite\\|cite\\'" macro))
4258 (progn
4259 (cond
4260 ((or (not arg)
4261 (not (listp arg)))
4262 (setq format
4263 (concat
4264 (if (not (or (= (preceding-char) ?{)
4265 (= (preceding-char) ?,)))
4266 ","
4267 "")
4268 "%l"
4269 (if (not (or (= (following-char) ?})
4270 (= (following-char) ?,)))
4271 ","
4272 ""))))
4273 (t
4274 (setq format "%l"))))
4275 ;; else: figure out the correct format
4276 (setq format
4277 (cond
4278 ((stringp reftex-cite-format) reftex-cite-format)
4279 ((and (symbolp reftex-cite-format)
4280 (assq reftex-cite-format reftex-cite-format-builtin))
4281 (nth 2 (assq reftex-cite-format reftex-cite-format-builtin)))
4282 (t reftex-cite-format)))
4283 (if (listp format)
4284 (save-window-excursion
4285 (with-output-to-temp-buffer "*RefTeX Select*"
4286 (princ "SELECT A CITATION FORMAT\n\n")
4287 (princ
4288 (mapconcat
4289 (function (lambda (x)
4290 (format "[%c] %s %s" (car x)
4291 (if (> (car x) 31) " " "")
4292 (cdr x))))
4293 format "\n")))
4294 (setq key (read-char))
4295 (if (assq key format)
4296 (setq format (cdr (assq key format)))
4297 (error "No citation format associated with key `%c'" key)))))
4298
4299 (let* (entry cnt rtn ins-string re-list re
4300 ;; scan bibtex files
4301 (reftex-found-list (reftex-extract-bib-entries
4302 (reftex-get-bibfile-list)))
4303 (found-list-r nil))
4304 (unless reftex-found-list
4305 (error "Sorry, no matches found"))
4306
4307 ;; remember where we came from
4308 (setq reftex-call-back-to-this-buffer (current-buffer))
4309
4310 ;; offer selection
4311 (save-window-excursion
4312 (switch-to-buffer-other-window "*RefTeX Select*")
4313 (erase-buffer)
4314 (reftex-insert-bib-matches reftex-found-list)
4315 (if (= 0 (buffer-size))
4316 (error "Sorry, no matches found"))
4317 (setq truncate-lines t)
4318 (goto-char 1)
4319 (if (catch 'exit
4320 (while t
4321 (setq rtn
4322 (reftex-select-item
4323 reftex-citation-prompt
4324 "^[^ \t\n\r]"
4325 4
4326 reftex-citation-help
4327 '(?r ?a ?g ?\C-m)
4328 nil
4329 'reftex-bibtex-selection-callback nil))
4330 (setq key (car rtn)
4331 cnt (nth 1 rtn))
4332 (unless key (throw 'exit nil))
4333 (cond
4334 ((eq key ?g)
4335 (setq reftex-found-list
4336 (save-excursion
4337 (set-buffer reftex-call-back-to-this-buffer)
4338 (reftex-extract-bib-entries
4339 (reftex-get-bibfile-list))))
4340 (erase-buffer)
4341 (reftex-insert-bib-matches reftex-found-list)
4342 (if (= 0 (buffer-size))
4343 (error "Sorry, no matches found"))
4344 (goto-char 1))
4345
4346 ((eq key ?r)
4347 ;; restrict with new regular expression
4348 (setq re-list
4349 (split-string (read-string
4350 "RegExp [ && RegExp...]: "
4351 nil 'reftex-cite-regexp-hist)
4352 "[ \t]*&&[ \t]*"))
4353 (while re-list
4354 (setq re (car re-list)
4355 re-list (cdr re-list))
4356 (setq found-list-r
4357 (delete ""
4358 (mapcar
4359 '(lambda (x)
4360 (if (string-match
4361 re (cdr (assoc "&entry" x)))
4362 x
4363 ""))
4364 reftex-found-list))))
4365 (if found-list-r
4366 (setq reftex-found-list found-list-r)
4367 (ding))
4368 (erase-buffer)
4369 (reftex-insert-bib-matches reftex-found-list)
4370 (goto-char 1))
4371 ((eq key ?a)
4372 (setq entry 'all)
4373 (throw 'exit t))
4374 ((or (eq key ?\C-m)
4375 (eq key 'return))
4376 (if cnt
4377 (setq entry (nth cnt reftex-found-list))
4378 (setq entry nil))
4379 (throw 'exit t))
4380 (t
4381 (ding)))))
4382 (progn
4383 ;; format the entry
4384 (if (eq entry 'all)
4385 (setq ins-string
4386 (mapconcat
4387 '(lambda (entry)
4388 (reftex-format-citation entry format))
4389 reftex-found-list "\n"))
4390 (setq ins-string (reftex-format-citation entry format))))
4391 (setq ins-string "")
4392 (message "Quit")))
4393 (kill-buffer "*RefTeX Select*")
4394
4395 (unless no-insert
4396 (insert ins-string)
4397 (when (string-match "\\?" ins-string)
4398 (search-backward "?")
4399 (delete-char 1)))
4400 (message "")
4401
4402 ;; Check if the prefix arg was numeric, and call recursively
4403 (when (and (integerp arg)
4404 (> arg 1)
4405 (re-search-backward
4406 "\\\\\\([a-zA-Z]*cite\\|cite[a-zA-Z]*\\)\\**\\(\\[[^]]*\\]\\)*{\\([^}]*\\)" nil t))
4407 (goto-char (match-end 0))
4408 (decf arg)
4409 (reftex-do-citation arg))
4410
4411 ;; Return the citation key
4412 (or (eq entry 'all)
4413 (reftex-get-bib-field "&key" entry)))))
4414
4415 (defun reftex-insert-bib-matches (list)
4416 ;; Insert the bib matches and number them correctly
4417 (let ((cnt -1) tmp)
4418 (mapcar '(lambda (x)
4419 (setq tmp (cdr (assoc "&formatted" x)))
4420 (incf cnt)
4421 (put-text-property 0 (length tmp) 'cnt cnt tmp)
4422 (insert tmp))
4423 list)))
4424
4425 (defun reftex-format-names (namelist n)
4426 (interactive)
4427 (let (last (len (length namelist)))
4428 (cond
4429 ((= 1 len) (car namelist))
4430 ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
4431 (t
4432 (setq n (min len n)
4433 last (nth (1- n) namelist))
4434 (setcdr (nthcdr (- n 2) namelist) nil)
4435 (concat
4436 (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
4437 (nth 1 reftex-cite-punctuation)
4438 last)))))
4439
4440 (defun reftex-format-citation (entry format)
4441 ;; Format a citation from the info in the BibTeX ENTRY
4442
4443 (unless (stringp format) (setq format "\\cite{%l}"))
4444
4445 (if (and reftex-comment-citations
4446 (string-match "%l" reftex-cite-comment-format))
4447 (error "reftex-cite-comment-format contains illeagal %%l"))
4448
4449 (while (string-match
4450 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
4451 format)
4452 (let ((n (string-to-int (match-string 4 format)))
4453 (l (string-to-char (match-string 5 format)))
4454 rpl b e)
4455 (save-match-data
4456 (setq rpl
4457 (cond
4458 ((= l ?l) (concat
4459 (reftex-get-bib-field "&key" entry)
4460 (if reftex-comment-citations
4461 reftex-cite-comment-format
4462 "")))
4463 ((= l ?a) (reftex-format-names
4464 (reftex-get-bib-names "author" entry)
4465 (or n 2)))
4466 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
4467 ((= l ?b) (reftex-get-bib-field "booktitle" entry))
4468 ((= l ?c) (reftex-get-bib-field "chapter" entry))
4469 ((= l ?d) (reftex-get-bib-field "edition" entry))
4470 ((= l ?e) (reftex-format-names
4471 (reftex-get-bib-names "editor" entry)
4472 (or n 2)))
4473 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
4474 ((= l ?h) (reftex-get-bib-field "howpublished" entry))
4475 ((= l ?i) (reftex-get-bib-field "institution" entry))
4476 ((= l ?j) (reftex-get-bib-field "journal" entry))
4477 ((= l ?k) (reftex-get-bib-field "key" entry))
4478 ((= l ?m) (reftex-get-bib-field "month" entry))
4479 ((= l ?n) (reftex-get-bib-field "number" entry))
4480 ((= l ?o) (reftex-get-bib-field "organization" entry))
4481 ((= l ?p) (reftex-get-bib-field "pages" entry))
4482 ((= l ?P) (car (split-string
4483 (reftex-get-bib-field "pages" entry)
4484 "[- .]+")))
4485 ((= l ?s) (reftex-get-bib-field "school" entry))
4486 ((= l ?u) (reftex-get-bib-field "publisher" entry))
4487 ((= l ?r) (reftex-get-bib-field "address" entry))
4488 ((= l ?t) (reftex-get-bib-field "title" entry))
4489 ((= l ?v) (reftex-get-bib-field "volume" entry))
4490 ((= l ?y) (reftex-get-bib-field "year" entry)))))
4491
4492 (if (string= rpl "")
4493 (setq b (match-beginning 2) e (match-end 2))
4494 (setq b (match-beginning 3) e (match-end 3)))
4495 (setq format (concat (substring format 0 b) rpl (substring format e)))))
4496 (while (string-match "%%" format)
4497 (setq format (replace-match "%" t t format)))
4498 (while (string-match "[ ,.;:]*%<" format)
4499 (setq format (replace-match "" t t format)))
4500 format)
4501
4502 ;; This is slow and not recommended for follow mode
4503 (defun reftex-bibtex-selection-callback (cnt)
4504 ;; Callback function to be called from the BibTeX selection, in
4505 ;; order to display context. This function is relatively slow and not
4506 ;; recommended for follow mode, just for individual lookups.
4507 (let ((win (selected-window))
4508 (key (reftex-get-bib-field "&key" (nth cnt reftex-found-list)))
4509 (bibfile-list (save-excursion
4510 (set-buffer reftex-call-back-to-this-buffer)
4511 (reftex-get-bibfile-list))))
4512 (reftex-pop-to-bibtex-entry key bibfile-list
4513 (not reftex-keep-temporary-buffers) t)
4514 (select-window win)))
4515
4516 ;;; ===========================================================================
4517 ;;;
4518 ;;; Here is the routine used for selection
4519
4520 ;; Marker for return point from recursive edit
4521 (defvar reftex-recursive-edit-marker (make-marker))
4522
4523 (defun reftex-check-recursive-edit ()
4524 ;; Check if we are already in a recursive edit. Abort with helpful
4525 ;; message if so.
4526 (if (marker-position reftex-recursive-edit-marker)
4527 (error
4528 (substitute-command-keys
4529 "In unfinished recursive edit. Finish (\\[exit-recursive-edit]) or abort (\\[abort-recursive-edit])."))))
4530
4531 (defun reftex-select-item (prompt next-re size help-string
4532 event-list &optional offset
4533 call-back cb-flag match-everywhere)
4534 ;; Select an item. Show PROMPT to user, find next item with NEXT-RE
4535 ;; regular expression, return on any of the events listed in
4536 ;; EVENT-LIST. The function returns the event along with an integer
4537 ;; indicating which item was selected. When OFFSET is specified,
4538 ;; starts at that item in the list. When CALL-BACK is given, it is a
4539 ;; function which is called with the index of the element.
4540
4541 (let* (key key-sq b e ev cnt last-cnt cmd skip-callback
4542 (search-str "") tmp search-start matched forward mini-map last-key
4543 (offset1 (or offset 1)) win1 win2)
4544
4545 ;; Set up a minibuffer keymap for the search stuff
4546 (setq mini-map (copy-keymap minibuffer-local-map))
4547 (define-key mini-map "\C-s"
4548 '(lambda () (interactive) (setq forward t) (exit-minibuffer)))
4549 (define-key mini-map "\C-r"
4550 '(lambda () (interactive) (setq forward nil) (exit-minibuffer)))
4551 (define-key mini-map "\C-m" 'exit-minibuffer)
4552
4553 (setq ev
4554 (catch 'exit
4555 (save-window-excursion
4556 (setq truncate-lines t)
4557 (goto-char 1)
4558 (unless (re-search-forward next-re nil t offset1)
4559 ;; in case the offset is illegal
4560 (setq offset1 1)
4561 (re-search-forward next-re nil t offset1))
4562 (beginning-of-line 1)
4563 (while t
4564 (setq last-cnt (or cnt last-cnt))
4565 (setq cnt (get-text-property (point) 'cnt))
4566 (if (and cnt cb-flag call-back (not skip-callback))
4567 (funcall call-back cnt))
4568 (setq skip-callback nil)
4569 (if cnt
4570 (setq b (or (previous-single-property-change
4571 (1+ (point)) 'cnt)
4572 (point-min))
4573 e (or (next-single-property-change
4574 (point) 'cnt)
4575 (point-max)))
4576 (setq b (point) e (point)))
4577 (reftex-highlight 1 b e)
4578 (if (or (not (pos-visible-in-window-p b))
4579 (not (pos-visible-in-window-p e)))
4580 (recenter (/ (window-height) 2)))
4581 (setq key-sq (read-key-sequence prompt))
4582 (setq last-key key)
4583 (setq key (car
4584 (cond
4585 ((fboundp 'event-to-character) ; XEmacs
4586 (mapcar 'event-to-character key-sq))
4587 ((fboundp 'listify-key-sequence) ; Emacs
4588 (listify-key-sequence key-sq))
4589 (t (error "Please report this problem to dominik@strw.leidenuniv.nl")))))
4590
4591 (setq cmd (key-binding key-sq))
4592
4593 (reftex-unhighlight 2)
4594 (reftex-unhighlight 0)
4595
4596 (cond
4597
4598 ;; Single line motions
4599 ((or (eq key ?n)
4600 (eq key ?\C-i)
4601 (eq cmd 'next-line))
4602 (or (eobp) (forward-char 1))
4603 (re-search-forward next-re nil t 1)
4604 (beginning-of-line 1))
4605 ((or (eq key ?p)
4606 (eq cmd 'previous-line))
4607 (re-search-backward next-re nil t))
4608
4609 ;; Page motions
4610 ((eq cmd 'scroll-up)
4611 (while (and (pos-visible-in-window-p)
4612 (re-search-forward next-re nil t)))
4613 (beginning-of-line 1)
4614 (recenter 1))
4615 ((eq cmd 'scroll-down)
4616 (while (and (pos-visible-in-window-p)
4617 (re-search-backward next-re nil t)))
4618 (recenter (- (window-height) size 2)))
4619
4620 ;; Begin and end of buffer
4621 ((eq cmd 'beginning-of-buffer)
4622 (goto-char (point-min))
4623 (re-search-forward next-re nil t)
4624 (beginning-of-line 1))
4625 ((eq cmd 'end-of-buffer)
4626 (goto-char (point-max))
4627 (re-search-backward next-re nil t))
4628
4629 ;; Exit
4630 ((eq key ?q)
4631 (throw 'exit nil))
4632 ((eq key ?\C-g)
4633 (if (or (eq last-key ?\C-s) (eq last-key ?\C-r))
4634 (ding)
4635 (bury-buffer)
4636 (error "Abort")))
4637 ((or (eq key ?\C-m)
4638 (eq key 'return)
4639 (eq cmd 'newline))
4640 (throw 'exit 'return))
4641 ((memq key event-list)
4642 (throw 'exit key))
4643
4644 ;; Callback
4645 ((or (eq key ?C) ; backward compatibility
4646 (eq key ?f))
4647 (setq cb-flag (not cb-flag)))
4648 ((eq key ?\ )
4649 (if cnt (funcall call-back cnt) (ding)))
4650
4651 ;; Help
4652 ((eq key ?\?)
4653 (with-output-to-temp-buffer "*RefTeX Help*"
4654 (princ help-string))
4655 (setq win1 (selected-window)
4656 win2 (get-buffer-window "*RefTeX Help*" t))
4657 (select-window win2)
4658 (unless (and (pos-visible-in-window-p 1)
4659 (pos-visible-in-window-p (point-max)))
4660 (enlarge-window (1+ (- (count-lines 1 (point-max))
4661 (window-height)))))
4662 (select-window win1)
4663 (setq skip-callback t))
4664
4665 ;; Searching
4666 ((or (setq forward (eq key ?\C-s)) (eq key ?\C-r))
4667 (if (or (and (not (eq last-key ?\C-s))
4668 (not (eq last-key ?\C-r)))
4669 (string= search-str ""))
4670 (setq tmp ; get a new string
4671 (read-from-minibuffer
4672 (if (string= search-str "")
4673 "Search: "
4674 (format "Search [%s]:" search-str))
4675 nil mini-map)
4676 search-str (if (string= tmp "")
4677 search-str tmp)))
4678 (setq search-start (point))
4679 (and (not (string= search-str ""))
4680 (progn
4681 (while
4682 (and (setq matched
4683 (if forward
4684 (search-forward search-str nil 1)
4685 (search-backward search-str nil 1)))
4686 (or (>= (save-excursion
4687 (goto-char (match-beginning 0))
4688 (current-column))
4689 (window-width))
4690 (not (or (get-text-property (point) 'cnt)
4691 match-everywhere)))))
4692 (if matched
4693 (reftex-highlight 2 (match-beginning 0)
4694 (match-end 0))
4695 (ding)
4696 (goto-char search-start)))))
4697
4698 ;; Recursive edit
4699 ((eq key ?e)
4700 (set-marker reftex-recursive-edit-marker (point))
4701 (unwind-protect
4702 (progn
4703 (save-window-excursion
4704 (save-excursion
4705 (other-window 1)
4706 (message
4707 (substitute-command-keys
4708 "Recursive edit. Return to selection with \\[exit-recursive-edit]"))
4709 (recursive-edit)))
4710 (unless (equal (marker-buffer
4711 reftex-recursive-edit-marker)
4712 (current-buffer))
4713 (error "Cannot continue RefTeX from this buffer."))
4714 (goto-char reftex-recursive-edit-marker))
4715 (set-marker reftex-recursive-edit-marker nil)))
4716
4717 (t
4718 (ding)))))))
4719 (and (get-buffer "*RefTeX Help*") (kill-buffer "*RefTeX Help*"))
4720 (message "")
4721 (list ev cnt last-cnt)))
4722
4723 ;;; ===========================================================================
4724 ;;;
4725 ;;; View cross references
4726
4727 (defun reftex-view-crossref (&optional arg)
4728 "View cross reference of \\ref or \\cite macro at point.
4729 If the macro at point is a \\ref, show the corresponding label definition.
4730 If it is a \\cite, show the BibTeX database entry.
4731 If there is no such macro at point, search forward to find one.
4732 When you call this function several times in direct successtion, point will
4733 move to view subsequent cross references further down in the buffer.
4734 To cope with the plethora of variations in packages, this function
4735 assumes any macro either starting with ending in `ref' or `cite' to contain
4736 cross references.
4737 With argument, actually select the window showing the cross reference."
4738
4739 (interactive "P")
4740
4741 ;; See where we are.
4742 (let* ((re "\\\\\\([a-z]*\\(cite\\|ref\\)\\|\\(cite\\|ref\\)[a-z]*\\)\\**\\(\\[[^{}]*\\]\\)?{")
4743 (macro (car (car (reftex-what-macro t))))
4744 (this-word (reftex-this-word "*a-zA-Z\\\\"))
4745 (my-window (selected-window))
4746 pop-window cmd args point)
4747
4748 (if (and macro
4749 (string-match "\\`\\\\cite\\|\\`\\\\ref\\|cite\\'\\|ref\\'"
4750 macro))
4751 (and (setq macro (match-string 0 macro))
4752 (string-match "\\`\\\\" macro)
4753 (setq macro (substring macro 1)))
4754 (setq macro nil))
4755
4756 (if (and macro (eq last-command this-command))
4757 (if (string= macro "cite")
4758 (progn
4759 (skip-chars-forward "^},%")
4760 (while (and (eq (following-char) ?%)
4761 (or (beginning-of-line 2) t)
4762 (skip-chars-forward " \t\n\r")))
4763 (skip-chars-forward ",")
4764 (if (eq (following-char) ?})
4765 (setq macro nil)))
4766 (setq macro nil)))
4767
4768 (if (and (not macro)
4769 (or (not (string-match "\\`\\\\" this-word))
4770 (eq (following-char) ?\\)
4771 (search-backward "\\" nil t)
4772 t))
4773 (if (interactive-p)
4774 ;; Only move far if this function was called directly
4775 (and (re-search-forward re nil t)
4776 (setq macro (or (match-string 2) (match-string 3))))
4777 ;; The macro needs to be at point
4778 (and (looking-at re)
4779 (setq macro (or (match-string 2) (match-string 3)))
4780 (goto-char (match-end 0)))))
4781
4782
4783 (unless macro
4784 (error "No cross reference to display"))
4785
4786 ;; Ensure access to scanning info
4787 (reftex-access-scan-info)
4788
4789 (cond
4790 ((string= macro "cite")
4791 (setq cmd 'reftex-pop-to-bibtex-entry
4792 args (list
4793 (reftex-this-word "^{},%\n\r")
4794 (reftex-get-bibfile-list) nil t)))
4795 ((string= macro "ref")
4796 (let* ((label (reftex-this-word "^{}%\n\r"))
4797 (xr-data (assoc 'xr (symbol-value reftex-docstruct-symbol)))
4798 (xr-re (nth 2 xr-data))
4799 (entry (assoc label (symbol-value reftex-docstruct-symbol))))
4800 (if (and (not entry) (string-match xr-re label))
4801 ;; Label is defined in external document
4802 (save-excursion
4803 (save-match-data
4804 (set-buffer
4805 (or (reftex-get-file-buffer-force
4806 (cdr (assoc (match-string 1 label) (nth 1 xr-data))))
4807 (error "Problem with external label %s" label))))
4808 (setq label (substring label (match-end 1)))
4809 (reftex-access-scan-info)
4810 (setq entry
4811 (assoc label (symbol-value reftex-docstruct-symbol)))))
4812 (if entry
4813 (setq cmd 'reftex-pop-to-label
4814 args (list label (list (nth 3 entry)) nil t))
4815 (error "Label %s not known - reparse document might help" label))))
4816 (t (error "This should not happen (reftex-view-crossref)")))
4817 (setq point (point))
4818 (apply cmd args)
4819 (setq pop-window (selected-window))
4820 (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
4821 (select-window my-window)
4822 (goto-char point)
4823 (and arg (select-window pop-window))))
4824
4825 (defun reftex-mouse-view-crossref (ev)
4826 "View cross reference of \\ref or \\cite macro where you click.
4827 If the macro at point is a \\ref, show the corresponding label definition.
4828 If it is a \\cite, show the BibTeX database entry.
4829 If there is no such macro at point, search forward to find one.
4830 With argument, actually select the window showing the cross reference."
4831 (interactive "e")
4832 (mouse-set-point ev)
4833 (setq last-command 'self-insert-command) ;; make sure we do not move!
4834 (reftex-view-crossref current-prefix-arg))
4835
4836 ;;; ===========================================================================
4837 ;;;
4838 ;;; Functions that check out the surroundings
4839
4840 (defun reftex-what-macro (which &optional bound)
4841 ;; Find out if point is within the arguments of any TeX-macro.
4842 ;; The return value is either ("\\macro" . (point)) or a list of them.
4843
4844 ;; If WHICH is nil, immediately return nil.
4845 ;; If WHICH is t, return list of all macros enclosing point.
4846 ;; If WHICH is a list of macros, look only for those macros and return the
4847 ;; name of the first macro in this list found to enclose point.
4848 ;; If the optional BOUND is an integer, bound backwards directed
4849 ;; searches to this point. If it is nil, limit to nearest \section -
4850 ;; like statement.
4851
4852 ;; This function is pretty stable, but can be fooled if the text contains
4853 ;; things like \macro{aa}{bb} where \macro is defined to take only one
4854 ;; argument. As RefTeX cannot know this, the string "bb" would still be
4855 ;; considered an argument of macro \macro.
4856
4857 (catch 'exit
4858 (if (null which) (throw 'exit nil))
4859 (let ((bound (or bound (save-excursion (re-search-backward
4860 reftex-section-regexp nil 1)
4861 (point))))
4862 pos cmd-list cmd cnt cnt-opt entry)
4863 (save-restriction
4864 (save-excursion
4865 (narrow-to-region (max 1 bound) (point-max))
4866 ;; move back out of the current parenthesis
4867 (while (condition-case nil
4868 (progn (up-list -1) t)
4869 (error nil))
4870 (setq cnt 1 cnt-opt 0)
4871 ;; move back over any touching sexps
4872 (while (and (reftex-move-to-previous-arg bound)
4873 (condition-case nil
4874 (progn (backward-sexp) t)
4875 (error nil)))
4876 (if (eq (following-char) ?\[) (incf cnt-opt))
4877 (incf cnt))
4878 (setq pos (point))
4879 (when (and (or (= (following-char) ?\[)
4880 (= (following-char) ?\{))
4881 (re-search-backward "\\\\[*a-zA-Z]+\\=" nil t))
4882 (setq cmd (reftex-match-string 0))
4883 (when (looking-at "\\\\begin{[^}]*}")
4884 (setq cmd (reftex-match-string 0)
4885 cnt (1- cnt)))
4886 ;; This does ignore optional arguments. Very hard to fix.
4887 (when (setq entry (assoc cmd reftex-env-or-mac-alist))
4888 (if (> cnt (or (nth 4 entry) 100))
4889 (setq cmd nil)))
4890 (cond
4891 ((null cmd))
4892 ((eq t which)
4893 (push (cons cmd (point)) cmd-list))
4894 ((member cmd which)
4895 (throw 'exit (cons cmd (point))))))
4896 (goto-char pos)))
4897 (nreverse cmd-list)))))
4898
4899 (defun reftex-what-environment (which &optional bound)
4900 ;; Find out if point is inside a LaTeX environment.
4901 ;; The return value is (e.g.) either ("equation" . (point)) or a list of
4902 ;; them.
4903
4904 ;; If WHICH is nil, immediately return nil.
4905 ;; If WHICH is t, return list of all environments enclosing point.
4906 ;; If WHICH is a list of environments, look only for those environments and
4907 ;; return the name of the first environment in this list found to enclose
4908 ;; point.
4909
4910 ;; If the optional BOUND is an integer, bound backwards directed searches to
4911 ;; this point. If it is nil, limit to nearest \section - like statement.
4912
4913 (catch 'exit
4914 (save-excursion
4915 (if (null which) (throw 'exit nil))
4916 (let ((bound (or bound (save-excursion (re-search-backward
4917 reftex-section-regexp nil 1)
4918 (point))))
4919 env-list end-list env)
4920 (while (re-search-backward "\\\\\\(begin\\|end\\){\\([^}]+\\)}"
4921 bound t)
4922 (setq env (buffer-substring-no-properties
4923 (match-beginning 2) (match-end 2)))
4924 (cond
4925 ((string= (match-string 1) "end")
4926 (add-to-list 'end-list env))
4927 ((member env end-list)
4928 (setq end-list (delete env end-list)))
4929 ((eq t which)
4930 (push (cons env (point)) env-list))
4931 ((member env which)
4932 (throw 'exit (cons env (point))))))
4933 (nreverse env-list)))))
4934
4935 (defun reftex-word-before-point ()
4936 ;; Return the word before point. Word means here:
4937 ;; Consists of [a-zA-Z0-9.:] and ends at point or whitespace.
4938 (let ((pos (point)))
4939 (save-excursion
4940 (re-search-backward "[^ \t\n\r]" (point-min) 1)
4941 (setq pos (min (1+ (point)) (point-max)))
4942 (if (re-search-backward "[^a-zA-Z0-9\\\.:]" (point-min) 1)
4943 (forward-char 1))
4944 (buffer-substring-no-properties (point) pos))))
4945
4946 ;; ============================================================================
4947 ;;
4948 ;; Some generally useful functions
4949
4950 (defun reftex-no-props (string)
4951 ;; Return STRING with all text properties removed
4952 (and (stringp string)
4953 (set-text-properties 0 (length string) nil string))
4954 string)
4955
4956 (defun reftex-match-string (n)
4957 ;; Match string without properties
4958 (when (match-beginning n)
4959 (buffer-substring-no-properties (match-beginning n) (match-end n))))
4960
4961 (defun reftex-this-word (&optional class)
4962 ;; Grab the word around point.
4963 (setq class (or class "-a-zA-Z0-9:_/.*;|"))
4964 (save-excursion
4965 (buffer-substring-no-properties
4966 (progn (skip-chars-backward class) (point))
4967 (progn (skip-chars-forward class) (point)))))
4968
4969 (defvar enable-multibyte-characters)
4970 (defun reftex-truncate (string ncols &optional ellipses padding)
4971 ;; Truncate a string to NCHAR characters.
4972 ;; Works fast with ASCII and correctly with Mule characters.
4973 ;; When ELLIPSES is non-nil, put three dots at the end of the string.
4974 (setq string
4975 (cond
4976 ((and (boundp 'enable-multibyte-characters)
4977 enable-multibyte-characters)
4978 (if (<= (string-width string) ncols)
4979 string
4980 (if ellipses
4981 (concat (truncate-string-to-width string (- ncols 3)) "...")
4982 (truncate-string-to-width string ncols))))
4983 (t
4984 (if (<= (length string) ncols)
4985 string
4986 (if ellipses
4987 (concat (substring string 0 (- ncols 3)) "...")
4988 (substring string 0 ncols))))))
4989 (if padding
4990 (format (format "%%-%ds" ncols) string)
4991 string))
4992
4993 (defun reftex-nearest-match (regexp &optional pos)
4994 ;; Find the nearest match of REGEXP. Set the match data.
4995 ;; If POS is given, calculate distances relative to it.
4996 ;; Return nil if there is no match.
4997 (let ((start (point)) (pos (or pos (point))) match1 match2 match)
4998 (goto-char start)
4999 (when (re-search-backward regexp nil t)
5000 (setq match1 (match-data)))
5001 (goto-char start)
5002 (when (re-search-forward regexp nil t)
5003 (setq match2 (match-data)))
5004 (goto-char start)
5005 (setq match
5006 (cond
5007 ((not match1) match2)
5008 ((not match2) match1)
5009 ((< (abs (- pos (car match1))) (abs (- pos (car match2)))) match1)
5010 (t match2)))
5011 (if match (progn (store-match-data match) t) nil)))
5012
5013 (defun reftex-auto-mode-alist ()
5014 ;; Return an `auto-mode-alist' with only the .gz (etc) thingies.
5015 ;; Stolen from gnus nnheader.
5016 (let ((alist auto-mode-alist)
5017 out)
5018 (while alist
5019 (when (listp (cdr (car alist)))
5020 (push (car alist) out))
5021 (pop alist))
5022 (nreverse out)))
5023
5024 (defun reftex-access-search-path (which &optional recurse file)
5025 ;; Access path from environment variables. WHICH is either "tex" or "bib".
5026 ;; When RECURSE is t, expand recursive paths, ending in double slash
5027 ;; FILE is just for the message.
5028 (let* ((pathvar (intern (concat "reftex-" which "-path")))
5029 (status (get pathvar 'status)))
5030 (cond
5031 ((eq status 'recursed))
5032 ((and status (null recurse)))
5033 ((null status)
5034 (let ((env-vars (if (equal which "tex") (list "TEXINPUTS")
5035 reftex-bibpath-environment-variables)))
5036 (set pathvar (reftex-parse-colon-path
5037 (mapconcat '(lambda(x) (or (getenv x) ""))
5038 env-vars path-separator))))
5039 (put pathvar 'status 'split))
5040 ((and (eq 'split status) recurse)
5041 (message "Expanding search path to find %s file: %s ..." which file)
5042 (set pathvar (reftex-expand-path (symbol-value pathvar)))
5043 (put pathvar 'status 'recursed)))))
5044
5045 (defun reftex-find-file-on-path (file path)
5046 ;; Find FILE along the directory list PATH.
5047 (catch 'exit
5048 (when (file-name-absolute-p file)
5049 (if (file-exists-p file)
5050 (throw 'exit file)
5051 (throw 'exit nil)))
5052 (let* ((thepath path) file1 dir
5053 (doubleslash (concat "/" "/")))
5054 (while (setq dir (pop thepath))
5055 (when (string= (substring dir -2) doubleslash)
5056 (setq dir (substring dir 0 -1)))
5057 (setq file1 (expand-file-name file dir))
5058 (if (file-exists-p file1)
5059 (throw 'exit file1)))
5060 ;; No such file
5061 nil)))
5062
5063 (defun reftex-parse-colon-path (path)
5064 ;; Like parse-colon-parse, but // or /~ have no effects.
5065 (mapcar 'file-name-as-directory
5066 (delete "" (split-string path (concat path-separator "+")))))
5067
5068 (defun reftex-expand-path (path)
5069 ;; Expand parts of path ending in a double slash
5070 (let (path1 dir dirs (doubleslash (concat "/" "/")))
5071 (while (setq dir (pop path))
5072 (if (string= (substring dir -2) doubleslash)
5073 (progn
5074 (setq dir (substring dir 0 -1))
5075 (setq dirs (reftex-recursive-directory-list dir))
5076 (setq path1 (append dirs path1)))
5077 (push dir path1)))
5078 (nreverse path1)))
5079
5080 (defun reftex-recursive-directory-list (dir)
5081 (let ((path (list dir)) dirs path1)
5082 (while (setq dir (pop path))
5083 (setq dirs
5084 (delete nil
5085 (mapcar (function
5086 (lambda (x)
5087 (if (and (file-directory-p x)
5088 (not (string-match "/\\.+\\'" x)))
5089 (file-name-as-directory x)
5090 nil)))
5091 (directory-files dir t))))
5092 (setq path (append dirs path))
5093 (push dir path1))
5094 path1))
5095
5096 (defun reftex-make-regexp-allow-for-ctrl-m (string)
5097 ;; convert STRING into a regexp, allowing ^M for \n and vice versa
5098 (let ((start -2))
5099 (setq string (regexp-quote string))
5100 (while (setq start (string-match "[\n\r]" string (+ 3 start)))
5101 (setq string (replace-match "[\n\r]" nil t string)))
5102 string))
5103
5104 (defun reftex-make-desparate-section-regexp (old)
5105 ;; Return a regexp which will still match a section statement even if
5106 ;; x-symbol or isotex or the like have been at work in the mean time.
5107 (let* ((n (1+ (string-match "[[{]" old)))
5108 (new (regexp-quote (substring old 0 (1+ (string-match "[[{]" old)))))
5109 (old (substring old n)))
5110 (while (string-match
5111 "\\([\r\n]\\)\\|\\(\\`\\|[ \t\n\r]\\)\\([a-zA-Z0-9]+\\)\\([ \t\n\r]\\|}\\'\\)"
5112 old)
5113 (if (match-beginning 1)
5114 (setq new (concat new "[^\n\r]*[\n\r]"))
5115 (setq new (concat new "[^\n\r]*" (match-string 3 old))))
5116 (setq old (substring old (match-end 0))))
5117 new))
5118
5119 (defun reftex-delete-list (elt-list list)
5120 ;; like delete, but with a list of things to delete
5121 ;; (original code from Rory Molinari)
5122 (while elt-list
5123 (setq list (delete (car elt-list) list)
5124 elt-list (cdr elt-list)))
5125 list)
5126
5127 (defun reftex-get-buffer-visiting (file)
5128 ;; return a buffer visiting FILE
5129 (cond
5130 ((boundp 'find-file-compare-truenames) ; XEmacs
5131 (let ((find-file-compare-truenames t))
5132 (get-file-buffer file)))
5133 ((fboundp 'find-buffer-visiting) ; Emacs
5134 (find-buffer-visiting file))
5135 (t (error "Please report this problem to dominik@strw.leidenuniv.nl"))))
5136
5137 (defun reftex-get-file-buffer-force (file &optional mark-to-kill)
5138 ;; Return a buffer visiting file. Make one, if necessary.
5139 ;; If neither such a buffer nor the file exist, return nil.
5140 ;; If MARK-TO-KILL is t and there is no live buffer, load the file with
5141 ;; initializations according to `reftex-initialize-temporary-buffers',
5142 ;; and mark the buffer to be killed after use.
5143
5144 (let ((buf (reftex-get-buffer-visiting file)))
5145
5146 (cond (buf
5147 ;; We have it already as a buffer - just return it
5148 buf)
5149
5150 ((file-readable-p file)
5151 ;; At least there is such a file and we can read it.
5152
5153 (if (or (not mark-to-kill)
5154 (eq t reftex-initialize-temporary-buffers))
5155
5156 ;; Visit the file with full magic
5157 (setq buf (find-file-noselect file))
5158
5159 ;; Else: Visit the file just briefly, without or
5160 ;; with limited Magic
5161
5162 ;; The magic goes away
5163 (let ((format-alist nil)
5164 (auto-mode-alist (reftex-auto-mode-alist))
5165 (default-major-mode 'fundamental-mode)
5166 (after-insert-file-functions nil))
5167 (setq buf (find-file-noselect file)))
5168
5169 ;; Is there a hook to run?
5170 (when (listp reftex-initialize-temporary-buffers)
5171 (save-excursion
5172 (set-buffer buf)
5173 (run-hooks 'reftex-initialize-temporary-buffers))))
5174
5175 ;; Lets see if we got a license to kill :-|
5176 (and mark-to-kill
5177 (add-to-list 'reftex-buffers-to-kill buf))
5178
5179 ;; Return the new buffer
5180 buf)
5181
5182 ;; If no such file exists, return nil
5183 (t nil))))
5184
5185 (defun reftex-splice-symbols-into-list (list alist)
5186 ;; Splice the association in ALIST of any symbols in LIST into the list.
5187 ;; Return new list.
5188 (let (rtn tmp)
5189 (while list
5190 (while (and (not (null (car list))) ;; keep list elements nil
5191 (symbolp (car list)))
5192 (setq tmp (car list))
5193 (cond
5194 ((assoc tmp alist)
5195 (setq list (append (nth 2 (assoc tmp alist)) (cdr list))))
5196 (t
5197 (error "Cannot treat symbol %s in reftex-label-alist"
5198 (symbol-name tmp)))))
5199 (push (pop list) rtn))
5200 (nreverse rtn)))
5201
5202 (defun reftex-uniquify (alist &optional keep-list)
5203 ;; Return a list of all elements in ALIST, but each car only once.
5204 ;; Elements of KEEP-LIST are not removed even if duplicate.
5205 (let (new elm)
5206 (while alist
5207 (setq elm (pop alist))
5208 (if (or (member (car elm) keep-list)
5209 (not (assoc (car elm) new)))
5210 (push elm new)))
5211 (nreverse new)))
5212
5213 (defun reftex-use-fonts ()
5214 ;; Return t if we can and want to use fonts.
5215 (and window-system
5216 reftex-use-fonts
5217 (featurep 'font-lock)))
5218
5219 (defun reftex-refontify ()
5220 ;; Return t if we need to refontify context
5221 (and (reftex-use-fonts)
5222 (or (eq t reftex-refontify-context)
5223 (and (eq 1 reftex-refontify-context)
5224 (or (featurep 'x-symbol))))))
5225
5226 ;; Highlighting uses overlays. If this is for XEmacs, we need to load
5227 ;; the overlay library, available in version 19.15
5228 (and (not (fboundp 'make-overlay))
5229 (condition-case nil
5230 (require 'overlay)
5231 (error
5232 (error "RefTeX needs overlay emulation (available in XEmacs 19.15)"))))
5233
5234 ;; We keep a vector with several different overlays to do our highlighting.
5235 (defvar reftex-highlight-overlays [nil nil nil])
5236
5237 ;; Initialize the overlays
5238 (aset reftex-highlight-overlays 0 (make-overlay 1 1))
5239 (overlay-put (aref reftex-highlight-overlays 0) 'face 'highlight)
5240 (aset reftex-highlight-overlays 1 (make-overlay 1 1))
5241 (overlay-put (aref reftex-highlight-overlays 1) 'face 'highlight)
5242 (aset reftex-highlight-overlays 2 (make-overlay 1 1))
5243 (overlay-put (aref reftex-highlight-overlays 2) 'face
5244 (if (string-match "XEmacs" emacs-version) 'zmacs-region 'region))
5245
5246 ;; Two functions for activating and deactivation highlight overlays
5247 (defun reftex-highlight (index begin end &optional buffer)
5248 "Highlight a region with overlay INDEX."
5249 (move-overlay (aref reftex-highlight-overlays index)
5250 begin end (or buffer (current-buffer))))
5251 (defun reftex-unhighlight (index)
5252 "Detatch overlay INDEX."
5253 (delete-overlay (aref reftex-highlight-overlays index)))
5254
5255 (defun reftex-highlight-shall-die ()
5256 ;; Function used in pre-command-hook to remove highlights.
5257 (remove-hook 'pre-command-hook 'reftex-highlight-shall-die)
5258 (reftex-unhighlight 0))
5259
5260 ;;; ---------------------------------------------------------------------------
5261 ;;;
5262 ;;; Functions to compile the tables, reset the mode etc.
5263
5264 (defun reftex-reset-mode ()
5265 "Reset RefTeX Mode. Required to implement changes to some list variables.
5266 This function will compile the information in `reftex-label-alist' and similar
5267 variables. It is called when RefTeX is first used, and after changes to
5268 these variables."
5269 (interactive)
5270
5271 ;; Record that we have done this
5272 (setq reftex-tables-dirty nil)
5273 (setq reftex-memory
5274 (list reftex-label-alist reftex-label-alist-external-add-ons
5275 reftex-default-label-alist-entries))
5276
5277 ;; Reset the file search path variables
5278 (put 'reftex-tex-path 'status nil)
5279 (put 'reftex-bib-path 'status nil)
5280
5281 ;; Kill temporary buffers associated with RefTeX - just in case they
5282 ;; were not cleaned up properly
5283 (let ((buffer-list '("*RefTeX Master*" "*RefTeX Help*" "*RefTeX Select*"
5284 "*Duplicate Labels*" "*toc*" "*RefTeX-scratch*"))
5285 buf)
5286 (while (setq buf (pop buffer-list))
5287 (if (get-buffer buf)
5288 (kill-buffer buf))))
5289
5290 ;; Make sure the current document will be rescanned soon.
5291 (reftex-reset-scanning-information)
5292
5293 ;; Plug functions into AUCTeX if the user option says so.
5294 (reftex-plug-into-AUCTeX)
5295
5296 (message "updating internal tables...")
5297 (reftex-compute-ref-cite-tables)
5298 (message "updating internal tables... done"))
5299
5300 (defun reftex-reset-scanning-information ()
5301 "Reset the symbols containing information from buffer scanning.
5302 This enforces rescanning the buffer on next use."
5303 (if (string= reftex-last-toc-master (reftex-TeX-master-file))
5304 (reftex-empty-toc-buffer))
5305 (let ((symlist reftex-multifile-symbols)
5306 symbol)
5307 (while symlist
5308 (setq symbol (car symlist)
5309 symlist (cdr symlist))
5310 (if (and (symbolp (symbol-value symbol))
5311 (not (null (symbol-value symbol))))
5312 (set (symbol-value symbol) nil)))))
5313
5314 (defun reftex-compute-ref-cite-tables ()
5315 ;; Update ref and cite tables
5316
5317 (interactive)
5318
5319 ;; Compile information in reftex-label-alist
5320 (let ((tmp (reftex-uniquify (reftex-splice-symbols-into-list
5321 (append
5322 reftex-label-alist
5323 reftex-label-alist-external-add-ons
5324 reftex-default-label-alist-entries)
5325 reftex-label-alist-builtin)
5326 '(nil)))
5327 entry env-or-mac typekeychar typekey prefix context word
5328 fmt reffmt labelfmt wordlist qh-list macros-with-labels
5329 nargs nlabel opt-args cell sum)
5330
5331 (setq reftex-words-to-typekey-alist nil
5332 reftex-typekey-list nil
5333 reftex-typekey-to-format-alist nil
5334 reftex-typekey-to-prefix-alist nil
5335 reftex-env-or-mac-alist nil
5336 reftex-label-env-list nil
5337 reftex-label-mac-list nil)
5338 (while tmp
5339 (catch 'next-entry
5340 (setq entry (car tmp)
5341 env-or-mac (car entry)
5342 entry (cdr entry)
5343 tmp (cdr tmp))
5344 (if (null env-or-mac)
5345 (setq env-or-mac ""))
5346 (if (stringp (car entry))
5347 ;; This is before version 2.00 - convert entry to new format
5348 ;; This is just to keep old users happy
5349 (setq entry (cons (string-to-char (car entry))
5350 (cons (concat (car entry) ":")
5351 (cdr entry)))))
5352 (setq typekeychar (nth 0 entry)
5353 typekey (char-to-string typekeychar)
5354 prefix (nth 1 entry)
5355 fmt (nth 2 entry)
5356 context (nth 3 entry)
5357 wordlist (nth 4 entry))
5358 (if (stringp wordlist)
5359 ;; This is before version 2.04 - convert to new format
5360 (setq wordlist (nthcdr 4 entry)))
5361
5362 (if (and (stringp fmt)
5363 (string-match "@" fmt))
5364 ;; special syntax for specifying a label format
5365 (setq fmt (split-string fmt "@+"))
5366 (setq fmt (list "\\label{%s}" fmt)))
5367 (setq labelfmt (car fmt)
5368 reffmt (nth 1 fmt))
5369 (if typekey
5370 (add-to-list 'reftex-typekey-list typekey))
5371 (if (and typekey prefix
5372 (not (assoc typekey reftex-typekey-to-prefix-alist)))
5373 (add-to-list 'reftex-typekey-to-prefix-alist
5374 (cons typekey prefix)))
5375 (cond
5376 ((string-match "\\`\\\\" env-or-mac)
5377 ;; It's a macro
5378 (let ((result (reftex-parse-args env-or-mac)))
5379 (setq env-or-mac (or (first result) env-or-mac)
5380 nargs (second result)
5381 nlabel (third result)
5382 opt-args (fourth result))
5383 (if nlabel (add-to-list 'macros-with-labels env-or-mac)))
5384 (add-to-list 'reftex-label-mac-list env-or-mac))
5385 (t
5386 (setq nargs nil nlabel nil opt-args nil)
5387 (cond ((string= env-or-mac "any"))
5388 ((string= env-or-mac ""))
5389 ((string= env-or-mac "section"))
5390 (t
5391 (add-to-list 'reftex-label-env-list env-or-mac)
5392 ;; Translate some special context cases
5393 (when (assq context reftex-default-context-regexps)
5394 (setq context
5395 (format
5396 (cdr (assq context reftex-default-context-regexps))
5397 (regexp-quote env-or-mac))))))))
5398 (and reffmt
5399 (not (assoc typekey reftex-typekey-to-format-alist))
5400 (push (cons typekey reffmt) reftex-typekey-to-format-alist))
5401 (and (not (string= env-or-mac "any"))
5402 (not (string= env-or-mac ""))
5403 (not (assoc env-or-mac reftex-env-or-mac-alist))
5404 (push (list env-or-mac typekey context labelfmt
5405 nargs nlabel opt-args)
5406 reftex-env-or-mac-alist))
5407 (while (and (setq word (pop wordlist))
5408 (stringp word))
5409 (setq word (downcase word))
5410 (or (assoc word reftex-words-to-typekey-alist)
5411 (push (cons word typekey) reftex-words-to-typekey-alist)))
5412 (cond
5413 ((string= "" env-or-mac) nil)
5414 ((setq cell (assoc typekey qh-list))
5415 (push env-or-mac (cdr cell)))
5416 (t
5417 (push (list typekey env-or-mac) qh-list)))))
5418
5419 (setq qh-list (sort qh-list '(lambda (x1 x2) (string< (car x1) (car x2)))))
5420 (setq reftex-typekey-to-prefix-alist
5421 (nreverse reftex-typekey-to-prefix-alist))
5422 (setq reftex-type-query-prompt
5423 (concat "Label type: "
5424 (mapconcat '(lambda(x)
5425 (format "[%s]" (car x)))
5426 qh-list " ")
5427 " (?=Help)"))
5428 (setq reftex-type-query-help
5429 (concat "SELECT A LABEL TYPE:\n--------------------\n"
5430 (mapconcat
5431 '(lambda(x)
5432 (setq sum 0)
5433 (format " [%s] %s"
5434 (car x)
5435 (mapconcat
5436 '(lambda(x)
5437 (setq sum (+ sum (length x)))
5438 (if (< sum 60)
5439 x
5440 (setq sum 0)
5441 (concat "\n " x)))
5442 (cdr x) " ")))
5443 qh-list "\n")))
5444
5445 ;; Calculate the regular expressions
5446 (let ((label-re "\\\\label{\\([^}]*\\)}")
5447 (include-re "\\(\\`\\|[\n\r]\\)[ \t]*\\\\\\(include\\|input\\)[{ \t]+\\([^} \t\n\r]+\\)")
5448 (section-re
5449 (concat "\\(\\`\\|[\n\r]\\)[ \t]*\\\\\\("
5450 (mapconcat 'car reftex-section-levels "\\|")
5451 "\\)\\*?\\(\\[[^]]*\\]\\)?{"))
5452 (macro-re
5453 (if macros-with-labels
5454 (concat "\\("
5455 (mapconcat 'regexp-quote macros-with-labels "\\|")
5456 "\\)[[{]")
5457 ""))
5458 (find-label-re-format
5459 (concat "\\("
5460 (mapconcat 'regexp-quote (append '("\\label")
5461 macros-with-labels) "\\|")
5462 "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]")))
5463 (setq reftex-section-regexp section-re
5464 reftex-section-or-include-regexp
5465 (concat section-re "\\|" include-re)
5466 reftex-everything-regexp
5467 (concat label-re "\\|" section-re "\\|" include-re
5468 (if macros-with-labels "\\|" "") macro-re)
5469 reftex-find-label-regexp-format find-label-re-format
5470 reftex-find-label-regexp-format2
5471 "\\([]} \t\n\r]\\)\\([[{]\\)\\(%s\\)[]}]"))))
5472
5473 ;;; Keybindings --------------------------------------------------------------
5474
5475 (define-key reftex-mode-map "\C-c=" 'reftex-toc)
5476 (define-key reftex-mode-map "\C-c(" 'reftex-label)
5477 (define-key reftex-mode-map "\C-c)" 'reftex-reference)
5478 (define-key reftex-mode-map "\C-c[" 'reftex-citation)
5479 (define-key reftex-mode-map "\C-c&" 'reftex-view-crossref)
5480
5481 ;; If the user requests so, she can have a few more bindings:
5482 (cond
5483 (reftex-extra-bindings
5484 (define-key reftex-mode-map "\C-ct" 'reftex-toc)
5485 (define-key reftex-mode-map "\C-cl" 'reftex-label)
5486 (define-key reftex-mode-map "\C-cr" 'reftex-reference)
5487 (define-key reftex-mode-map "\C-cc" 'reftex-citation)
5488 (define-key reftex-mode-map "\C-cv" 'reftex-view-crossref)
5489 (define-key reftex-mode-map "\C-cg" 'reftex-grep-document)
5490 (define-key reftex-mode-map "\C-cs" 'reftex-search-document)))
5491
5492 ;;; Menus --------------------------------------------------------------------
5493
5494 ;; Define a menu for the menu bar if Emacs is running under X
5495
5496 (require 'easymenu)
5497
5498 (easy-menu-define
5499 reftex-mode-menu reftex-mode-map
5500 "Menu used in RefTeX mode"
5501 `("Ref"
5502 ["Table of Contents" reftex-toc t]
5503 "----"
5504 ["\\label" reftex-label t]
5505 ["\\ref" reftex-reference t]
5506 ["\\cite" reftex-citation t]
5507 ["View Crossref" reftex-view-crossref t]
5508 "----"
5509 ("Parse Document"
5510 ["Only this File" reftex-parse-one t]
5511 ["Entire Document" reftex-parse-all (reftex-is-multi)]
5512 ["Save to File" (reftex-access-parse-file 'write)
5513 (> (length (symbol-value reftex-docstruct-symbol)) 0)]
5514 ["Restore from File" (reftex-access-parse-file 'restore)
5515 (reftex-access-parse-file 'readable)]
5516 "----"
5517 ["Enable Partial Scans"
5518 (setq reftex-enable-partial-scans (not reftex-enable-partial-scans))
5519 :style toggle :selected reftex-enable-partial-scans]
5520 ["Auto-Save Parse Info"
5521 (setq reftex-save-parse-info (not reftex-save-parse-info))
5522 :style toggle :selected reftex-save-parse-info]
5523 "---"
5524 ["Reset RefTeX Mode" reftex-reset-mode t])
5525 ("Multifile"
5526 ["Search Whole Document" reftex-search-document t]
5527 ["Replace in Document" reftex-query-replace-document t]
5528 ["Grep on Document" reftex-grep-document t]
5529 "----"
5530 ["Create TAGS File" reftex-create-tags-file t]
5531 "----"
5532 ["Find Duplicate Labels" reftex-find-duplicate-labels t]
5533 ["Change Label and Refs" reftex-change-label t])
5534 ("Citation Options"
5535 "Citation Style"
5536 ,@(mapcar
5537 (function
5538 (lambda (x)
5539 (vector
5540 (symbol-name (car x))
5541 (list 'setq 'reftex-cite-format (list 'quote (car x)))
5542 :style 'radio :selected
5543 (list 'eq 'reftex-cite-format (list 'quote (car x))))))
5544 reftex-cite-format-builtin)
5545 "----"
5546 "Bibinfo in Comments"
5547 ["Attach Comments"
5548 (setq reftex-comment-citations (not reftex-comment-citations))
5549 :style toggle :selected reftex-comment-citations]
5550 "---"
5551 "Sort Database Matches"
5552 ["by Author" (setq reftex-sort-bibtex-matches 'author)
5553 :style radio :selected (eq reftex-sort-bibtex-matches 'author)]
5554 ["by Year" (setq reftex-sort-bibtex-matches 'year)
5555 :style radio :selected (eq reftex-sort-bibtex-matches 'year)]
5556 ["by Year, reversed" (setq reftex-sort-bibtex-matches 'reverse-year)
5557 :style radio :selected (eq reftex-sort-bibtex-matches 'reverse-year)]
5558 ["Not" (setq reftex-sort-bibtex-matches nil)
5559 :style radio :selected (eq reftex-sort-bibtex-matches nil)])
5560 "----"
5561 ["Customize RefTeX" reftex-customize t]
5562 "----"
5563 ["Show Documentation" reftex-show-commentary t]))
5564
5565 ;;; Run Hook ------------------------------------------------------------------
5566
5567 (run-hooks 'reftex-load-hook)
5568
5569 ;;; That's it! ----------------------------------------------------------------
5570
5571 (provide 'reftex)
5572
5573 ; Make sure tabels are compiled
5574 (message "updating internal tables...")
5575 (reftex-compute-ref-cite-tables)
5576 (message "updating internal tables...done")
5577 (setq reftex-tables-dirty nil)
5578
5579 ;;;============================================================================
5580
5581 ;;; reftex.el ends here