]> code.delx.au - gnu-emacs/blob - lisp/textmodes/reftex.el
(reftex-finding-files): New customize group.
[gnu-emacs] / lisp / textmodes / reftex.el
1 ;;; reftex.el --- Minor mode for doing \label, \ref and \cite in LaTeX
2 ;; Copyright (c) 1997, 1998 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 ;;
36 ;; INSTALLATION
37 ;; ------------
38 ;;
39 ;; If you got reftex.el with an Emacs distribution, it is already
40 ;; installed. If not, follow the instructions in the INSTALL file of
41 ;; the distribution.
42 ;;
43 ;; To turn RefTeX Mode on and off in a particular buffer, use
44 ;; `M-x reftex-mode'.
45 ;;
46 ;; To turn on RefTeX Mode for all LaTeX files, add one of the following
47 ;; lines to your .emacs file:
48 ;;
49 ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
50 ;; (add-hook 'latex-mode-hook 'turn-on-reftex) ; with Emacs latex mode
51 ;;
52 ;;
53 ;; DOCUMENTATION
54 ;; -------------
55 ;;
56 ;; See below for a short summary of how to use RefTeX.
57 ;;
58 ;; There is an extensive texinfo document describing RefTeX in detail.
59 ;; When you are getting reftex.el with the Emacs distribution, the
60 ;; info files should already be installed. To view this
61 ;; documentation, use `M-x reftex-info RET'.
62 ;;
63 ;; The documentation in various formats is also available at
64 ;;
65 ;; http://www.strw.leidenuniv.nl/~dominik/Tools/
66 ;;
67 ;;---------------------------------------------------------------------------
68 ;;
69 ;; RefTeX in a Nutshell
70 ;; ====================
71 ;;
72 ;; 1. Labels and References
73 ;; RefTeX distinguishes labels for different environments. It knows
74 ;; about all standard environments (and many others), and can be
75 ;; configured to recognize any additional labeled environments you
76 ;; have defined yourself (variable REFTEX-LABEL-ALIST).
77 ;;
78 ;; * Creating Labels
79 ;; Type `C-c (' (`reftex-label') to insert a label at point.
80 ;; RefTeX will either
81 ;; - derive a label from context (default for section labels)
82 ;; - prompt for a label string (default for figures and
83 ;; tables) or
84 ;; - insert a simple label made of a prefix and a number (all
85 ;; other environments).
86 ;; Which labels are created how is configurable (variable
87 ;; REFTEX-INSERT-LABEL-FLAGS).
88 ;;
89 ;; * Referencing Labels
90 ;; In order to make a reference, type `C-c )'
91 ;; (`reftex-reference'). This shows an outline of the document
92 ;; with all labels of a certain type (figure, equation,...) and
93 ;; context of the label definition. Selecting a label inserts a
94 ;; `\ref{LABEL}' macro into the original buffer.
95 ;;
96 ;; 2. Citations
97 ;; After typing `C-c [' (`reftex-citation'), RefTeX will let you
98 ;; specify a regular expression to search in current BibTeX database
99 ;; files (as specified in the `\bibliography' command) and pull out a
100 ;; list of matches for you to choose from. The list is *formatted*
101 ;; and sorted. The selected article is referenced as `\cite{KEY}'
102 ;; (customizable with variable REFTEX-CITE-FORMAT).
103 ;;
104 ;; 3. Viewing Cross References
105 ;; When no other message occupies the echo area and point is idle on
106 ;; the argument of a `\ref' or `\cite' macro, the echo area will
107 ;; display information about the citation/cross reference.
108 ;; With point on the argument of such a macro, press `C-c &'
109 ;; (`reftex-view-crossref'), or click with `S-mouse-2' on the macro
110 ;; argument. This will display the corresponding label definition or
111 ;; BibTeX database entry in another window.
112 ;;
113 ;; 4. Table of Contents
114 ;; Typing `C-c =' (`reftex-toc') will show a table of contents of the
115 ;; document. From that buffer, you can jump quickly to every part of
116 ;; your document.
117 ;;
118 ;; 5. Multifile Documents
119 ;; Multifile Documents are fully supported. RefTeX will provide cross
120 ;; referencing information from all files which are part of the
121 ;; document, and even across document borders (`xr.sty').
122 ;;
123 ;; 6. Document Parsing
124 ;; RefTeX needs to parse the document in order to find labels and
125 ;; other information. It does it automatically once, when you start
126 ;; working with a document. RefTeX updates its lists internally when
127 ;; you make a new label with `reftex-label'. To enforce reparsing,
128 ;; call any of the commands described above with a raw `C-u' prefix,
129 ;; or press the `r' key in the label selection buffer or the table of
130 ;; contents buffer.
131 ;;
132 ;; 7. Useful Settings
133 ;; To make RefTeX faster for large documents include, and to integrate
134 ;; it with AUCTeX, try these:
135 ;;
136 ;; (setq reftex-enable-partial-scans t)
137 ;; (setq reftex-save-parse-info t)
138 ;; (setq reftex-use-multiple-selection-buffers t)
139 ;; (setq reftex-plug-into-AUCTeX t)
140 ;;
141 ;;---------------------------------------------------------------------------
142 ;;
143 ;; AUTHOR
144 ;; ======
145 ;;
146 ;; Carsten Dominik <dominik@strw.LeidenUniv.nl>
147 ;;
148 ;; with contributions from Stephen Eglen
149 ;;
150 ;; The newest version of RefTeX can be found at
151 ;;
152 ;; http://www.strw.leidenuniv.nl/~dominik/Tools/
153 ;; ftp://ftp.strw.leidenuniv.nl/pub/dominik/
154 ;;
155 ;; At that site you can also get version 3.22 of RefTeX which is still
156 ;; compatible with Emacs 19. The file you are reading now as well as the
157 ;; ones distributed with Emacs 20 are not.
158 ;;
159 ;; THANKS TO:
160 ;; ---------
161 ;; Thanks to the people on the Net who have used RefTeX and helped
162 ;; developing it with their reports. In particular thanks to
163 ;;
164 ;; F. Burstall, Alastair Burt, Soren Dayton, Stephen Eglen,
165 ;; Karl Eichwalder, Peter Galbraith, Dieter Kraft, Kai Grossjohann,
166 ;; Adrian Lanz, Rory Molinari, Laurent Mugnier, Sudeep Kumar Palat,
167 ;; Daniel Polani, Robin Socha, Richard Stanton, Allan Strand,
168 ;; Jan Vroonhof, Christoph Wedler, Alan Williams.
169 ;;
170 ;; Finally thanks to Uwe Bolick who first got me (some years ago) into
171 ;; supporting LaTeX labels and references with an Editor (which was
172 ;; MicroEmacs at the time).
173 ;;
174 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
175 ;;
176 ;;;;;;
177 \f
178 ;;; Code:
179
180 (eval-when-compile (require 'cl))
181
182 ;; Stuff that needs to be there when we use defcustom
183 (require 'custom)
184
185 (defvar reftex-tables-dirty t
186 "Flag showing if tables need to be re-computed.")
187
188 (eval-and-compile
189 (defun reftex-set-dirty (symbol value)
190 (setq reftex-tables-dirty t)
191 (set symbol value)))
192
193 ;;; ======================================================================
194 ;;;
195 ;;; Configuration Section
196
197 ;; Define the two constants which are needed during compilation
198
199 (eval-and-compile
200 (defconst reftex-label-alist-builtin
201 '(
202 ;; Some aliases, mostly for backward compatibility
203 (Sideways "Alias for -->rotating" (rotating))
204 (AMSTeX "amsmath with eqref macro"
205 ((nil ?e nil "~\\eqref{%s}")
206 amsmath))
207
208 ;; Individual package defaults
209 (amsmath "AMS-LaTeX math environments"
210 (("align" ?e nil nil eqnarray-like)
211 ("gather" ?e nil nil eqnarray-like)
212 ("multline" ?e nil nil t)
213 ("flalign" ?e nil nil eqnarray-like)
214 ("alignat" ?e nil nil alignat-like)
215 ("xalignat" ?e nil nil alignat-like)
216 ("xxalignat" ?e nil nil alignat-like)
217 ("subequations" ?e nil nil t)))
218
219 (endnotes "The \\endnote macro"
220 (("\\endnote[]{}" ?n nil nil 2 (regexp "Endnotes?"))))
221
222 (fancybox "The Beqnarray environment"
223 (("Beqnarray" ?e nil nil eqnarray-like)))
224
225 (floatfig "The floatingfigure environment"
226 (("floatingfigure" ?f nil nil caption)))
227
228 (longtable "The longtable environment"
229 (("longtable" ?t nil nil caption)))
230
231 (picinpar "The figwindow and tabwindow environments"
232 (("figwindow" ?f nil nil 1)
233 ("tabwindow" ?f nil nil 1)))
234
235 (rotating "Sidewaysfigure and table"
236 (("sidewaysfigure" ?f nil nil caption)
237 ("sidewaystable" ?t nil nil caption)))
238
239 (sidecap "CSfigure and SCtable"
240 (("SCfigure" ?f nil nil caption)
241 ("SCtable" ?t nil nil caption)))
242
243 (subfigure "Subfigure environments/macro"
244 (("subfigure" ?f nil nil caption)
245 ("subfigure*" ?f nil nil caption)
246 ("\\subfigure[]{}" ?f nil nil 1)))
247
248 (supertab "Supertabular environment"
249 (("supertabular" ?t nil nil "\\tablecaption{")))
250
251 (wrapfig "The wrapfigure environment"
252 (("wrapfigure" ?f nil nil caption)))
253
254 ;; The LaTeX core stuff
255 (LaTeX "LaTeX default environments"
256 (("section" ?s "sec:" "~\\ref{%s}" (nil . t)
257 (regexp "parts?" "chapters?" "chap\\." "sections?" "sect?\\."
258 "paragraphs?" "par\\."
259 "\\\\S" "\247" "Teile?" "Kapitel" "Kap\\." "Abschnitte?"
260 "appendi\\(x\\|ces\\)" "App\\." "Anh\"?ange?" "Anh\\."))
261
262 ("enumerate" ?i "item:" "~\\ref{%s}" item
263 (regexp "items?" "Punkte?"))
264
265 ("equation" ?e "eq:" "~(\\ref{%s})" t
266 (regexp "equations?" "eqs?\\." "eqn\\." "Gleichung\\(en\\)?" "Gl\\."))
267 ("eqnarray" ?e "eq:" nil eqnarray-like)
268
269 ("figure" ?f "fig:" "~\\ref{%s}" caption
270 (regexp "figure?[sn]?" "figs?\\." "Abbildung\\(en\\)?" "Abb\\."))
271 ("figure*" ?f nil nil caption)
272
273 ("table" ?t "tab:" "~\\ref{%s}" caption
274 (regexp "tables?" "tab\\." "Tabellen?"))
275 ("table*" ?t nil nil caption)
276
277 ("\\footnote[]{}" ?n "note:" "~\\ref{%s}" 2
278 (regexp "footnotes?" "notes?" "Anmerkung\\(en\\)?" "Anm\\."))
279
280 ("any" ?\ " " "~\\ref{%s}" nil)
281
282 ;; The label macro is hard coded, but it *could* be defined like this:
283 ;;("\\label{*}" nil nil nil nil)
284 ))
285
286 )
287 "The default label environment descriptions.
288 Lower-case symbols correspond to a style file of the same name in the LaTeX
289 distribution. Mixed-case symbols are convenience aliases.")
290
291 (defconst reftex-cite-format-builtin
292 '(
293 (default "Default macro \\cite{%l}"
294 "\\cite{%l}")
295 (natbib "The Natbib package"
296 ((?\C-m . "\\cite{%l}")
297 (?t . "\\citet{%l}")
298 (?T . "\\citet*{%l}")
299 (?p . "\\citep{%l}")
300 (?P . "\\citep*{%l}")
301 (?e . "\\citep[e.g.][]{%l}")
302 (?s . "\\citep[see][]{%l}")
303 (?a . "\\citeauthor{%l}")
304 (?A . "\\citeauthor*{%l}")
305 (?y . "\\citeyear{%l}")))
306 (harvard "The Harvard package"
307 ((?\C-m . "\\cite{%l}")
308 (?p . "\\cite{%l}")
309 (?t . "\\citeasnoun{%l}")
310 (?n . "\\citeasnoun{%l}")
311 (?s . "\\possessivecite{%l}")
312 (?e . "\\citeaffixed{%l}{?}")
313 (?y . "\\citeyear{%l}")
314 (?a . "\\citename{%l}")))
315 (chicago "The Chicago package"
316 ((?\C-m . "\\cite{%l}")
317 (?t . "\\citeN{%l}")
318 (?T . "\\shortciteN{%l}")
319 (?p . "\\cite{%l}")
320 (?P . "\\shortcite{%l}")
321 (?a . "\\citeA{%l}")
322 (?A . "\\shortciteA{%l}")
323 (?y . "\\citeyear{%l}")))
324 (astron "The Astron package"
325 ((?\C-m . "\\cite{%l}")
326 (?p . "\\cite{%l}" )
327 (?t . "%2a (\\cite{%l})")))
328 (author-year "Do-it-yourself Author-year"
329 ((?\C-m . "\\cite{%l}")
330 (?t . "%2a (%y)\\nocite{%l}")
331 (?p . "(%2a %y\\nocite{%l})")))
332 (locally "Full info in parenthesis"
333 "(%2a %y, %j %v, %P, %e: %b, %u, %s %<)")
334 )
335 "Builtin versions of the citation format.
336 The following conventions are valid for all alist entries:
337 `?\C-m' should always point to a straight \\cite{%l} macro.
338 `?t' should point to a textual citation (citation as a noun).
339 `?p' should point to a parenthetical citation.")
340 )
341
342 ;; Configuration Variables and User Options for RefTeX ------------------
343
344 (defgroup reftex nil
345 "LaTeX label and citation support."
346 :tag "RefTeX"
347 :link '(url-link :tag "Home Page"
348 "http://strw.leidenuniv.nl/~dominik/Tools/")
349 :link '(emacs-commentary-link :tag "Commentary in reftex.el" "reftex.el")
350 :prefix "reftex-"
351 :group 'tex)
352
353 (defgroup reftex-label-support nil
354 "Support for creation, insertion and referencing of labels in LaTeX."
355 :group 'reftex)
356
357 (defgroup reftex-defining-label-environments nil
358 "Definition of environments and macros to do with label."
359 :group 'reftex-label-support)
360
361 (defcustom reftex-default-label-alist-entries
362 '(amsmath endnotes fancybox floatfig longtable picinpar
363 rotating sidecap subfigure supertab wrapfig LaTeX)
364 "Default label alist specifications. LaTeX should be the last entry.
365 This list describes the default label environments RefTeX should always use.
366 It is probably a mistake to remove the LaTeX symbol from this list.
367
368 The options include:
369 LaTeX The standard LaTeX environments.
370 Sideways The sidewaysfigure and sidewaystable environments.
371 AMSTeX The math environments in the AMS-LaTeX amsmath package.
372
373 For the full list of options, try
374
375 M-x customize-variable RET reftex-default-label-alist-entries RET."
376 :group 'reftex-defining-label-environments
377 :set 'reftex-set-dirty
378 :type `(set
379 :indent 4
380 :inline t
381 :greedy t
382 ,@(mapcar
383 (function
384 (lambda (x)
385 (list 'const ':tag (concat (symbol-name (nth 0 x))
386 ": " (nth 1 x))
387 (nth 0 x))))
388 reftex-label-alist-builtin)))
389
390 (defcustom reftex-label-alist nil
391 "Alist with information on environments for \\label-\\ref use.
392
393 This docstring is easier to understand after reading the configuration
394 examples in `reftex.el'. Looking at the builtin defaults in the constant
395 `reftex-label-alist-builtin' may also be instructive.
396
397 Set this variable to define additions and changes to the default. The only
398 things you MUST NOT change is that `?s' is the type indicator for section
399 labels, and SPC for the `any' label type. These are hard-coded at other
400 places in the code.
401
402 Each list entry describes either an environment carrying a counter for use
403 with \\label and \\ref, or a LaTeX macro defining a label as (or inside)
404 one of its arguments. The elements of each list entry are:
405
406 0. Name of the environment (like \"table\") or macro (like \"\\\\myfig\").
407 For macros, indicate the macro arguments for best results, as in
408 \"\\\\myfig[]{}{}{*}{}\". Use square brackets for optional arguments,
409 a star to mark the label argument, if any. The macro does not have to
410 have a label argument - you could also use \\label{..} inside one of
411 its arguments.
412 Special names: `section' for section labels, `any' to define a group
413 which contains all labels.
414 This may also be nil if the entry is only meant to change some settings
415 associated with the type indicator character (see below).
416
417 1. Type indicator character, like `?t', must be a printable ASCII character.
418 The type indicator is a single character which defines a label type.
419 Any label inside the environment or macro is assumed to belong to this
420 type. The same character may occur several times in this list, to cover
421 cases in which different environments carry the same label type (like
422 `equation' and `eqnarray').
423 If the type indicator is nil and the macro has a label argument {*},
424 the macro defines neutral labels just like \label. In this case
425 the reminder of this entry is ignored.
426
427 2. Label prefix string, like \"tab:\".
428 The prefix is a short string used as the start of a label. It may be the
429 empty string. The prefix may contain the following `%' escapes:
430 %f Current file name with directory and extension stripped.
431 %F Current file name relative to directory of master file.
432 %u User login name, on systems which support this.
433
434 Example: In a file `intro.tex', \"eq:%f:\" will become \"eq:intro:\").
435
436 3. Format string for reference insert in buffer. `%s' will be replaced by
437 the label.
438 When the format starts with `~', the `~' will only be inserted if
439 there is not already a whitespace before point.
440
441 4. Indication on how to find the short context.
442 - If nil, use the text following the \\label{...} macro.
443 - If t, use
444 - the section heading for section labels.
445 - text following the \\begin{...} statement of environments.
446 (not a good choice for environments like eqnarray or enumerate,
447 where one has several labels in a single environment).
448 - text after the macro name (starting with the first arg) for macros.
449 - If an integer, use the nth argument of the macro. As a special case,
450 1000 means to get text after the last macro argument.
451 - If a string, use as regexp to search *backward* from the label. Context
452 is then the text following the end of the match. E.g. putting this to
453 \"\\\\\\\\caption[[{]\" will use the caption in a figure or table
454 environment.
455 \"\\\\\\\\begin{eqnarray}\\\\|\\\\\\\\\\\\\\\\\" works for eqnarrays.
456 - If any of `caption', `item', `eqnarray-like', `alignat-like', this
457 symbol will internally be translated into an appropriate regexp
458 (see also the variable `reftex-default-context-regexps').
459 - If a function, call this function with the name of the environment/macro
460 as argument. On call, point will be just after the \\label macro. The
461 function is expected to return a suitable context string. It should
462 throw an exception (error) when failing to find context.
463 As an example, here is a function returning the 10 chars following
464 the label macro as context:
465
466 (defun my-context-function (env-or-mac)
467 (if (> (point-max) (+ 10 (point)))
468 (buffer-substring (point) (+ 10 (point)))
469 (error \"Buffer too small\")))
470
471 Label context is used in two ways by RefTeX: For display in the label
472 menu, and to derive a label string. If you want to use a different
473 method for each of these, specify them as a dotted pair.
474 E.g. `(nil . t)' uses the text after the label (nil) for display, and
475 text from the default position (t) to derive a label string. This is
476 actually used for section labels.
477
478 Setting the variable `reftex-use-text-after-label-as-context' to t
479 overrides the setting here.
480
481 5. List of magic words which identify a reference to be of this type.
482 If the word before point is equal to one of these words when calling
483 `reftex-reference', the label list offered will be automatically
484 restricted to labels of the correct type.
485 If the first element of this wordlist is the symbol `regexp', the
486 strings are interpreted as regular expressions. RefTeX will add
487 a \"\\\\W\" to the beginning and other stuff to the end of the regexp.
488
489 If the type indicator characters of two or more entries are the same, RefTeX
490 will use
491 - the first non-nil format and prefix
492 - the magic words of all involved entries.
493
494 Any list entry may also be a symbol. If that has an association in
495 `reftex-label-alist-builtin', the cddr of that association is spliced into the
496 list. However, builtin defaults should normally be set with the variable
497 `reftex-default-label-alist-entries."
498 :group 'reftex-defining-label-environments
499 :set 'reftex-set-dirty
500 :type
501 `(repeat
502 (choice :tag "Package or Detailed "
503 :value ("" ?a nil nil nil nil)
504 (list :tag "Detailed Entry"
505 :value ("" ?a nil nil nil nil)
506 (choice :tag "Environment or \\macro "
507 (const :tag "Ignore, just use typekey" nil)
508 (string ""))
509 (choice :tag "Type specification "
510 (const :tag "unspecified, like in \\label" nil)
511 (character :tag "Char " ?a))
512 (choice :tag "Label prefix string "
513 (const :tag "Default" nil)
514 (string :tag "String" "lab:"))
515 (choice :tag "Label reference format"
516 (const :tag "Default" nil)
517 (string :tag "String" "~\\ref{%s}"))
518 (choice :tag "Context method "
519 (const :tag "Default position" t)
520 (const :tag "After label" nil)
521 (number :tag "Macro arg nr" 1)
522 (regexp :tag "Regexp" "")
523 (const :tag "Caption in float" caption)
524 (const :tag "Item in list" item)
525 (const :tag "Eqnarray-like" eqnarray-like)
526 (const :tag "Alignat-like" alignat-like)
527 (symbol :tag "Function" my-func))
528 (repeat :tag "Magic words" :extra-offset 2 (string)))
529 (choice
530 :tag "Package"
531 :value AMSTeX
532 ,@(mapcar
533 (function
534 (lambda (x)
535 (list 'const ':tag (concat (symbol-name (nth 0 x)))
536 (nth 0 x))))
537 reftex-label-alist-builtin)))))
538
539 ;; LaTeX section commands and level numbers
540 (defcustom reftex-section-levels
541 '(
542 ("part" . 0)
543 ("chapter" . 1)
544 ("section" . 2)
545 ("subsection" . 3)
546 ("subsubsection" . 4)
547 ("paragraph" . 5)
548 ("subparagraph" . 6)
549 ("subsubparagraph" . 7)
550 )
551 "Commands and levels used for defining sections in the document.
552 The car of each cons cell is the name of the section macro. The cdr is a
553 number indicating its level."
554 :group 'reftex-defining-label-environments
555 :set 'reftex-set-dirty
556 :type '(repeat
557 (cons (string :tag "sectioning macro" "")
558 (number :tag "level " 0))))
559
560 (defcustom reftex-default-context-regexps
561 '((caption . "\\\\\\(rot\\)?caption\\*?[[{]")
562 (item . "\\\\item\\(\\[[^]]*\\]\\)?")
563 (eqnarray-like . "\\\\begin{%s}\\|\\\\\\\\")
564 (alignat-like . "\\\\begin{%s}{[0-9]*}\\|\\\\\\\\"))
565 "Alist with default regular expressions for finding context.
566 The form (format regexp (regexp-quote environment)) is used to calculate
567 the final regular expression - so %s will be replaced with the environment
568 or macro."
569 :group 'reftex-defining-label-environments
570 :type '(repeat (cons (symbol) (regexp))))
571
572 (defcustom reftex-use-text-after-label-as-context nil
573 "*t means, grab context from directly after the \\label{..} macro.
574 This is the fastest method for obtaining context of the label definition, but
575 requires discipline when placing labels. Setting this variable to t takes
576 precedence over the individual settings in `reftex-label-alist'.
577 This variable may be set to t, nil, or a string of label type letters
578 indicating the label types for which it should be true."
579 :group 'reftex-defining-label-environments
580 :set 'reftex-set-dirty
581 :type '(choice
582 (const :tag "on" t) (const :tag "off" nil)
583 (string :tag "Selected label types")))
584
585 ;; Label insertion
586
587 (defgroup reftex-making-and-inserting-labels nil
588 "Options on how to create new labels."
589 :group 'reftex-label-support)
590
591 (defcustom reftex-insert-label-flags '("s" "sft")
592 "Flags governing label insertion. First flag DERIVE, second flag PROMPT.
593
594 If DERIVE is t, RefTeX will try to derive a sensible label from context.
595 A section label for example will be derived from the section heading.
596 The conversion of the context to a legal label is governed by the
597 specifications given in `reftex-derive-label-parameters'.
598 If RefTeX fails to derive a label, it will prompt the user.
599 If DERIVE is nil, the label generated will consist of the prefix and a
600 unique number, like `eq:23'.
601
602 If PROMPT is t, the user will be prompted for a label string. The prompt will
603 already contain the prefix, and (if DERIVE is t) a default label derived from
604 context. When PROMPT is nil, the default label will be inserted without
605 query.
606
607 So the combination of DERIVE and PROMPT controls label insertion. Here is a
608 table describing all four possibilities:
609
610 DERIVE PROMPT ACTION
611 -------------------------------------------------------------------------
612 nil nil Insert simple label, like eq:22 or sec:13. No query.
613 nil t Prompt for label.
614 t nil Derive a label from context and insert without query.
615 t t Derive a label from context and prompt for confirmation.
616
617 Each flag may be set to t, nil, or a string of label type letters
618 indicating the label types for which it should be true. The strings work
619 like character classes.
620 Thus, the combination may be set differently for each label type. The
621 default settings \"s\" and \"sft\" mean: Derive section labels from headings
622 (with confirmation). Prompt for figure and table labels. Use simple labels
623 without confirmation for everything else.
624 The available label types are: s (section), f (figure), t (table), i (item),
625 e (equation), n (footnote), plus any definitions in `reftex-label-alist'."
626 :group 'reftex-making-and-inserting-labels
627 :type '(list (choice :tag "Derive label from context"
628 (const :tag "always" t)
629 (const :tag "never" nil)
630 (string :tag "selected label types" ""))
631 (choice :tag "Prompt for label string "
632 :entry-format " %b %v"
633 (const :tag "always" t)
634 (const :tag "never" nil)
635 (string :tag "selected label types" ""))))
636
637 (defcustom reftex-string-to-label-function 'reftex-string-to-label
638 "Function to turn an arbitrary string into a legal label.
639 RefTeX's default function uses the variable `reftex-derive-label-parameters'."
640 :group 'reftex-making-and-inserting-labels
641 :type 'symbol)
642
643 (defcustom reftex-translate-to-ascii-function 'reftex-latin1-to-ascii
644 "Filter function which will process a context string before it is used
645 to derive a label from it. The intended application is to convert ISO or
646 Mule characters into something legal in labels. The default function
647 removes the accents from Latin-1 characters. X-Symbol (>=2.6) sets this
648 variable to the much more general `x-symbol-translate-to-ascii'."
649 :group 'reftex-making-and-inserting-labels
650 :type 'symbol)
651
652 (defcustom reftex-derive-label-parameters '(3 20 t 1 "-"
653 ("the" "on" "in" "off" "a" "for" "by" "of" "and" "is" "to") t)
654 "Parameters for converting a string into a label.
655 NWORDS Number of words to use.
656 MAXCHAR Maximum number of characters in a label string.
657 ILLEGAL nil: Throw away any words containing characters illegal in labels.
658 t: Throw away only the illegal characters, not the whole word.
659 ABBREV nil: Never abbreviate words.
660 t: Always abbreviate words (see `reftex-abbrev-parameters').
661 not t and not nil: Abbreviate words if necessary to shorten
662 label string below MAXCHAR.
663 SEPARATOR String separating different words in the label.
664 IGNOREWORDS List of words which should not be part of labels.
665 DOWNCASE t: Downcase words before using them."
666 :group 'reftex-making-and-inserting-labels
667 :type '(list (integer :tag "Number of words " 3)
668 (integer :tag "Maximum label length " 20)
669 (choice :tag "Illegal characters in words"
670 (const :tag "throw away entire word" nil)
671 (const :tag "throw away single chars" t))
672 (choice :tag "Abbreviate words "
673 (const :tag "never" nil)
674 (const :tag "always" t)
675 (const :tag "when label is too long" 1))
676 (string :tag "Separator between words " "-")
677 (repeat :tag "Ignore words"
678 :entry-format " %i %d %v"
679 (string :tag ""))
680 (option (boolean :tag "Downcase words "))))
681
682 (defcustom reftex-label-illegal-re "[^-a-zA-Z0-9_+=:;,.]"
683 "Regexp matching characters not legal in labels."
684 :group 'reftex-making-and-inserting-labels
685 :type '(regexp :tag "Regular Expression"))
686
687 (defcustom reftex-abbrev-parameters '(4 2 "^aeiou" "aeiou")
688 "Parameters for abbreviation of words.
689 MIN-CHARS Minimum number of characters remaining after abbreviation.
690 MIN-KILL Minimum number of characters to remove when abbreviating words.
691 BEFORE Character class before abbrev point in word.
692 AFTER Character class after abbrev point in word."
693 :group 'reftex-making-and-inserting-labels
694 :type '(list
695 (integer :tag "Minimum chars per word" 4)
696 (integer :tag "Shorten by at least " 2)
697 (string :tag "cut before char class " "^saeiou")
698 (string :tag "cut after char class " "aeiou")))
699
700 (defcustom reftex-format-label-function nil
701 "Function which produces the string to insert as a label definition.
702 Normally should be nil, unless you want to do something fancy.
703 The function will be called with two arguments, the LABEL and the DEFAULT
704 FORMAT, which usually is `\label{%s}'. The function should return the
705 string to insert into the buffer."
706 :group 'reftex-making-and-inserting-labels
707 :type 'function)
708
709 ;; Label referencing
710
711 (defgroup reftex-referencing-labels nil
712 "Options on how to reference labels."
713 :group 'reftex-label-support)
714
715 (eval-and-compile
716 (defconst reftex-tmp
717 '((const :tag "on" t)
718 (const :tag "off" nil)
719 (string :tag "Selected label types"))))
720
721 (defcustom reftex-label-menu-flags '(t t nil nil nil nil t nil)
722 "List of flags governing the label menu makeup.
723 The flags are:
724
725 TABLE-OF-CONTENTS Show the labels embedded in a table of context.
726 SECTION-NUMBERS Include section numbers (like 4.1.3) in table of contents.
727 COUNTERS Show counters. This just numbers the labels in the menu.
728 NO-CONTEXT Non-nil means do NOT show the short context.
729 FOLLOW Follow full context in other window.
730 SHOW-COMMENTED Show labels from regions which are commented out.
731 MATCH-IN-TOC Obsolete flag.
732 SHOW FILES Show begin and end of included files.
733
734 Each of these flags can be set to t or nil, or to a string of type letters
735 indicating the label types for which it should be true. These strings work
736 like character classes in regular expressions. Thus, setting one of the
737 flags to \"sf\" makes the flag true for section and figure labels, nil
738 for everything else. Setting it to \"^sf\" makes it the other way round.
739 The available label types are: s (section), f (figure), t (table), i (item),
740 e (equation), n (footnote), plus any definitions in `reftex-label-alist'.
741
742 Most options can also be switched from the label menu itself - so if you
743 decide here to not have a table of contents in the label menu, you can still
744 get one interactively during selection from the label menu."
745 :group 'reftex-referencing-labels
746 :type
747 `(list
748 (choice :tag "Embed in table of contents " ,@reftex-tmp)
749 (choice :tag "Show section numbers " ,@reftex-tmp)
750 (choice :tag "Show individual counters " ,@reftex-tmp)
751 (choice :tag "Hide short context " ,@reftex-tmp)
752 (choice :tag "Follow context in other window " ,@reftex-tmp)
753 (choice :tag "Show commented labels " ,@reftex-tmp)
754 (choice :tag "Obsolete flag, Don't use. " ,@reftex-tmp)
755 (choice :tag "Show begin/end of included files" ,@reftex-tmp)))
756
757 (defcustom reftex-vref-is-default nil
758 "*Non-nil means, the varioref macro \\vref is used as default.
759 In the selection buffer, the `v' key toggles the reference macro between
760 `\\ref' and `\\vref'. The value of this variable determines the default
761 which is active when entering the selection process.
762 Instead of nil or t, this may also be a string of type letters indicating
763 the label types for which it should be true."
764 :group 'reftex-referencing-labels
765 :type `(choice :tag "\\vref is default macro" ,@reftex-tmp))
766
767 (defcustom reftex-level-indent 2
768 "*Number of spaces to be used for indentation per section level."
769 :group 'reftex-referencing-labels
770 :type 'integer)
771
772 (defcustom reftex-guess-label-type t
773 "*Non-nil means, `reftex-reference' will try to guess the label type.
774 To do that, RefTeX will look at the word before the cursor and compare it with
775 the words given in `reftex-label-alist'. When it finds a match, RefTeX will
776 immediately offer the correct label menu - otherwise it will prompt you for
777 a label type. If you set this variable to nil, RefTeX will always prompt."
778 :group 'reftex-referencing-labels
779 :type 'boolean)
780
781 (defcustom reftex-format-ref-function nil
782 "Function which produces the string to insert as a reference.
783 Normally should be nil, because the format to insert a reference can
784 already be specified in `reftex-label-alist'.
785 The function will be called with two arguments, the LABEL and the DEFAULT
786 FORMAT, which normally is `~\ref{%s}'. The function should return the
787 string to insert into the buffer."
788 :group 'reftex-referencing-labels
789 :type 'function)
790
791 (defcustom reftex-select-label-mode-hook nil
792 "Mode hook for reftex-select-label-mode."
793 :group 'reftex-referencing-labels
794 :type 'hook)
795
796 ;; BibteX citation configuration ----------------------------------------
797
798 (defgroup reftex-citation-support nil
799 "Support for referencing bibliographic data with BibTeX."
800 :group 'reftex)
801
802 (defvar reftex-bibfile-ignore-list nil) ; compatibility
803 (defcustom reftex-bibfile-ignore-regexps nil
804 "*List of regular expressions to exclude files in \\bibliography{..}.
805 File names matched by these regexps will not be parsed by RefTeX.
806 Intended for files which contain only `@string' macro definitions and the
807 like, which are ignored by RefTeX anyway."
808 :group 'reftex-citation-support
809 :set 'reftex-set-dirty
810 :type '(repeat (regexp)))
811
812 (defcustom reftex-default-bibliography nil
813 "*List of BibTeX database files which should be used if none are specified.
814 When `reftex-citation' is called from a document which has neither a
815 `\bibliography{..}' statement nor a `thebibliography' environment,
816 RefTeX will scan these files instead. Intended for using
817 `reftex-citation' in non-LaTeX files."
818 :group 'reftex-citation-support
819 :type '(repeat (file)))
820
821 (defcustom reftex-sort-bibtex-matches 'reverse-year
822 "*Sorting of the entries found in BibTeX databases by reftex-citation.
823 Possible values:
824 nil Do not sort entries.
825 'author Sort entries by author name.
826 'year Sort entries by increasing year.
827 'reverse-year Sort entries by decreasing year."
828 :group 'reftex-citation-support
829 :type '(choice (const :tag "not" nil)
830 (const :tag "by author" author)
831 (const :tag "by year" year)
832 (const :tag "by year, reversed" reverse-year)))
833
834 (defcustom reftex-cite-format 'default
835 "*The format of citations to be inserted into the buffer.
836 It can be a string or an alist. In the simplest case this is just
837 the string \"\\cite{%l}\", which is also the default. See the
838 definition of `reftex-cite-format-builtin' for more complex examples.
839
840 If `reftex-cite-format' is a string, it will be used as the format.
841 In the format, the following percent escapes will be expanded.
842
843 %l The BibTeX label of the citation.
844 %a List of author names, see also `reftex-cite-punctuation.
845 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
846 %A First author name only.
847 %e Works like %a, but on list of editor names. (%2e and %E work a well)
848
849 It is also possible to access all other BibTeX database fields:
850 %b booktitle %c chapter %d edition %h howpublished
851 %i institution %j journal %k key %m month
852 %n number %o organization %p pages %P first page
853 %r address %s school %u publisher %t title
854 %v volume %y year
855 %B booktitle, abbreviated %T title, abbreviated
856
857 Usually, only %l is needed. The other stuff is mainly for the echo area
858 display, and for (setq reftex-comment-citations t).
859
860 %< as a special operator kills punctuation and space around it after the
861 string has been formatted.
862
863 Beware that all this only works with BibTeX database files. When
864 citations are made from the \\bibitems in an explicit thebibliography
865 environment, only %l is available.
866
867 If `reftex-cite-format' is an alist of characters and strings, the user
868 will be prompted for a character to select one of the possible format
869 strings.
870 In order to configure this variable, you can either set
871 `reftex-cite-format' directly yourself or set it to the SYMBOL of one of
872 the predefined styles (see `reftex-cite-format-builtin'). E.g.:
873 (setq reftex-cite-format 'natbib)"
874 :group 'reftex-citation-support
875 :type
876 `(choice
877 :format "%{%t%}: \n%[Value Menu%] %v"
878 (radio :tag "Symbolic Builtins"
879 :indent 4
880 :value default
881 ,@(mapcar
882 (function
883 (lambda (x)
884 (list 'const ':tag (concat (symbol-name (nth 0 x))
885 ": " (nth 1 x))
886 (nth 0 x))))
887 reftex-cite-format-builtin))
888 (string :tag "format string" "\\cite{%l}")
889 (repeat :tag "key-ed format strings"
890 :value ((?\r . "\\cite{%l}")
891 (?t . "\\cite{%l}") (?p . "\\cite{%l}"))
892 (cons (character :tag "Key character" ?\r)
893 (string :tag "Format string" "")))))
894
895 (defcustom reftex-comment-citations nil
896 "*Non-nil means add a comment for each citation describing the full entry.
897 The comment is formatted according to `reftex-cite-comment-format'."
898 :group 'reftex-citation-support
899 :type 'boolean)
900
901 (defcustom reftex-cite-comment-format
902 "%% %2a %y, %j %v, %P, %b, %e, %u, %s %<\n"
903 "Citation format used for commented citations. Must NOT contain %l.
904 See the variable `reftex-cite-format' for possible percent escapes."
905 :group 'reftex-citation-support
906 :type 'string)
907
908 (defcustom reftex-cite-view-format
909 "%2a %y, %T, %B, %j %v:%P, %s %<"
910 "Citation format used to display citation info in the message area.
911 Must NOT contain %l. See the variable `reftex-cite-format' for
912 possible percent escapes."
913 :group 'reftex-citation-support
914 :group 'reftex-viewing-cross-references-and-citations
915 :type 'string)
916
917 (defcustom reftex-cite-punctuation '(", " " \\& " " {\\it et al.}")
918 "Punctuation for formatting of name lists in citations.
919 This is a list of 3 strings.
920 1. normal names separator, like \", \" in Jones, Brown and Miller
921 2. final names separator, like \" and \" in Jones, Brown and Miller
922 3. The \"et al\" string, like \" {\\it et al.}\" in Jones {\\it et al.}"
923 :group 'reftex-citation-support
924 :type '(list
925 (string :tag "Separator for names ")
926 (string :tag "Separator for last name in list")
927 (string :tag "string used as et al. ")))
928
929 (defcustom reftex-format-cite-function nil
930 "Function which produces the string to insert as a citation.
931 Normally should be nil, because the format to insert a reference can
932 already be specified in `reftex-cite-format'.
933 The function will be called with two arguments, the CITATION KEY and the
934 DEFAULT FORMAT, which is taken from `reftex-cite-format'. The function
935 should return the string to insert into the buffer."
936 :group 'reftex-citation-support
937 :type 'function)
938
939 (defcustom reftex-select-bib-mode-hook nil
940 "Mode hook for reftex-select-bib-mode."
941 :group 'reftex-citation-support
942 :type 'hook)
943
944 ;; Table of contents configuration --------------------------------------
945
946 (defgroup reftex-table-of-contents-browser nil
947 "A multifile table of contents browser."
948 :group 'reftex)
949
950 (defcustom reftex-toc-follow-mode nil
951 "*Non-nil means, point in *toc* buffer will cause other window to follow.
952 The other window will show the corresponding part of the document.
953 This flag can be toggled from within the *toc* buffer with the `f' key."
954 :group 'reftex-table-of-contents-browser
955 :type 'boolean)
956
957 (defcustom reftex-revisit-to-follow nil
958 "*Non-nil means, follow-mode will revisit files if necessary.
959 When nil, follow-mode will be suspended for stuff in unvisited files."
960 :group 'reftex-table-of-contents-browser
961 :group 'reftex-referencing-labels
962 :type 'boolean)
963
964 (defcustom reftex-toc-mode-hook nil
965 "Mode hook for reftex-toc-mode."
966 :group 'reftex-table-of-contents-browser
967 :type 'hook)
968
969 ;; Viewing Cross References and Citations
970 (defgroup reftex-viewing-cross-references-and-citations nil
971 "Displaying cross references and citations."
972 :group 'reftex)
973
974 (defcustom reftex-auto-view-crossref t
975 "*Non-nil means, initially turn automatic viewing of crossref info on.
976 Automatic viewing of crossref info normally uses the echo area.
977 Whenever point is on the argument of a \\ref or \\cite macro, and no
978 other message is being displayed, the echo area will display
979 information about that cross reference. You can also set the variable
980 to the symbol `window'. In this case a small temporary window is
981 used for the display.
982 This feature can be turned on and of from the menu
983 (Ref->Options->Crossref Viewing)."
984 :group 'reftex-viewing-cross-references-and-citations
985 :type '(choice (const :tag "off" nil)
986 (const :tag "in Echo Area" t)
987 (const :tag "in Other Window" window)))
988
989 (defcustom reftex-idle-time 1.2
990 "*Time (secs) Emacs has to be idle before automatic crossref display is done."
991 :group 'reftex-viewing-cross-references-and-citations
992 :type 'number)
993
994 (defcustom reftex-revisit-to-echo nil
995 "*Non-nil means, automatic citation display will revisit files if necessary.
996 When nil, citation display in echo area will only be active for cached
997 entries and for BibTeX database files with live associated buffers."
998 :group 'reftex-viewing-cross-references-and-citations
999 :type 'boolean)
1000
1001 (defcustom reftex-cache-cite-echo t
1002 "*Non-nil means, the information displayed in the echo area for cite macros
1003 is cached and even saved along with the parsing information. The cache
1004 survives document scans. In order to clear it, use M-x reftex-reset-mode."
1005 :group 'reftex-viewing-cross-references-and-citations
1006 :type 'boolean)
1007
1008 (defcustom reftex-display-copied-context-hook nil
1009 "Normal Hook which is run before context is displayed anywhere. Designed
1010 for X-Symbol, but may have other uses as well."
1011 :group 'reftex-viewing-cross-references-and-citations
1012 :group 'reftex-referencing-labels
1013 :type 'hook)
1014
1015 ;; Finding Files --------------------------------------------------------
1016
1017 (defgroup reftex-finding-files nil
1018 "Displaying cross references and citations."
1019 :group 'reftex)
1020
1021 (defcustom reftex-texpath-environment-variables '("TEXINPUTS")
1022 "*List of specifications how to retrieve the search path for TeX files.
1023 Several entries are possible.
1024 - If an element is the name of an environment variable, its content is used.
1025 - If an element starts with an exclamation mark, it is used as a command
1026 to retrieve the path. A typical command with the kpathsearch library would
1027 be `!kpsewhich -show-path=.tex'.
1028 - Otherwise the element itself is interpreted as a path.
1029 Multiple directories can be separated by the system dependent `path-separator'.
1030 Directories ending in `//' or `!!' will be expanded recursively.
1031 See also `reftex-use-external-file-finders'."
1032 :group 'reftex-finding-files
1033 :set 'reftex-set-dirty
1034 :type '(repeat (string :tag "Specification")))
1035
1036 (defcustom reftex-bibpath-environment-variables '("BIBINPUTS" "TEXBIB")
1037 "*List of specifications how to retrieve search path for .bib database files.
1038 Several entries are possible.
1039 - If an element is the name of an environment variable, its content is used.
1040 - If an element starts with an exclamation mark, it is used as a command
1041 to retrieve the path. A typical command with the kpathsearch library would
1042 be `!kpsewhich -show-path=.bib'.
1043 - Otherwise the element itself is interpreted as a path.
1044 Multiple directories can be separated by the system dependent `path-separator'.
1045 Directories ending in `//' or `!!' will be expanded recursively.
1046 See also `reftex-use-external-file-finders'."
1047 :group 'reftex-citation-support
1048 :group 'reftex-finding-files
1049 :set 'reftex-set-dirty
1050 :type '(repeat (string :tag "Specification")))
1051
1052 (defcustom reftex-search-unrecursed-path-first t
1053 "*Non-nil means, search all specified directories before trying recursion.
1054 Thus, in a path \".//:/tex/\", search first \"./\", then \"/tex/\" and then
1055 all subdirectories of \"./\". If this option is nil, the subdirectories of
1056 \"./\" are searched before \"/tex/\". This is mainly for speed - most of the
1057 time the recursive path is for the system files and not for the user files.
1058 Set this to nil if the default makes RefTeX finding files with equal names
1059 in wrong sequence."
1060 :group 'reftex-finding-files
1061 :type 'boolean)
1062
1063 (defcustom reftex-use-external-file-finders nil
1064 "*Non-nil means, use external programs to find files.
1065 Normally, RefTeX searches the paths given in the environment variables
1066 TEXINPUTS and BIBINPUTS to find TeX files and BibTeX database files.
1067 With this option turned on, it calls an external program specified in the
1068 option `reftex-external-file-finders' instead. As a side effect,
1069 the variables `reftex-texpath-environment-variables' and
1070 `reftex-bibpath-environment-variables' will be ignored."
1071 :group 'reftex-finding-files
1072 :type 'boolean)
1073
1074 (defcustom reftex-external-file-finders '(("tex" . "kpsewhich -format=.tex %f")
1075 ("bib" . "kpsewhich -format=.bib %f"))
1076 "*Association list with external programs to call for finding files.
1077 Each entry is a cons cell (TYPE . PROGRAM).
1078 Type is either \"tex\" or \"bib\". PROGRAM is the external program to use with
1079 any arguments. %f will be replaced by the name of the file to be found.
1080 Note that these commands will be executed directly, not via a shell.
1081 Only relevant when `reftex-use-external-file-finders' is non-nil."
1082 :group 'reftex-finding-files
1083 :type '(repeat (cons (string :tag "File type")
1084 (string :tag "Program "))))
1085
1086 ;; Tuning the parser ----------------------------------------------------
1087
1088 (defgroup reftex-optimizations-for-large-documents nil
1089 "Configuration of parser speed and memory usage."
1090 :group 'reftex)
1091
1092 (defcustom reftex-keep-temporary-buffers 1
1093 "*Non-nil means, keep buffers created for parsing and lookup.
1094 RefTeX sometimes needs to visit files related to the current document.
1095 We distinguish files visited for
1096 PARSING: Parts of a multifile document loaded when (re)-parsing the document.
1097 LOOKUP: BibTeX database files and TeX files loaded to find a reference,
1098 to display label context, etc.
1099 The created buffers can be kept for later use, or be thrown away immediately
1100 after use, depending on the value of this variable:
1101
1102 nil Throw away as much as possible.
1103 t Keep everything.
1104 1 Throw away buffers created for parsing, but keep the ones created
1105 for lookup.
1106
1107 If a buffer is to be kept, the file is visited normally (which is potentially
1108 slow but will happen only once).
1109 If a buffer is to be thrown away, the initialization of the buffer depends
1110 upon the variable `reftex-initialize-temporary-buffers'."
1111 :group 'reftex-optimizations-for-large-documents
1112 :type '(choice
1113 (const :tag "Throw away everything" nil)
1114 (const :tag "Keep everything" t)
1115 (const :tag "Keep lookup buffers only" 1)))
1116
1117 (defcustom reftex-initialize-temporary-buffers nil
1118 "*Non-nil means do initializations even when visiting file temporarily.
1119 When nil, RefTeX may turn off find-file hooks and other stuff to briefly
1120 visit a file.
1121 When t, the full default initializations are done (find-file-hook etc.).
1122 Instead of t or nil, this variable may also be a list of hook functions to
1123 do a minimal initialization."
1124 :group 'reftex-optimizations-for-large-documents
1125 :type '(choice
1126 (const :tag "Read files literally" nil)
1127 (const :tag "Fully initialize buffers" t)
1128 (repeat :tag "Hook functions" :value (nil)
1129 (function-item))))
1130
1131 (defcustom reftex-no-include-regexps '("\\.pstex_t\\'")
1132 "*List of regular expressions to exclude certain input files from parsing.
1133 If the name of a file included via \\include or \\input is matched by any
1134 of the regular expressions in this list, that file is not parsed by RefTeX."
1135 :group 'reftex-optimizations-for-large-documents
1136 :type '(repeat (regexp)))
1137
1138 (defcustom reftex-enable-partial-scans nil
1139 "*Non-nil means, re-parse only 1 file when asked to re-parse.
1140 Re-parsing is normally requested with a `C-u' prefix to many RefTeX commands,
1141 or with the `r' key in menus. When this option is t in a multifile document,
1142 we will only parse the current buffer, or the file associated with the label
1143 or section heading near point in a menu. Requesting re-parsing of an entire
1144 multifile document then requires a `C-u C-u' prefix or the capital `R' key
1145 in menus."
1146 :group 'reftex-optimizations-for-large-documents
1147 :type 'boolean)
1148
1149 (defcustom reftex-allow-automatic-rescan t
1150 "*Non-nil means, RefTeX may rescan the document when this seems necessary.
1151 Currently this applies only to rescanning after label insertion, when
1152 the new label cannot be inserted correctly into the internal label
1153 list."
1154 :group 'reftex-optimizations-for-large-documents
1155 :type 'boolean)
1156
1157 (defcustom reftex-save-parse-info nil
1158 "*Non-nil means, save information gathered with parsing in a file.
1159 The file MASTER.rel in the same directory as MASTER.tex is used to save the
1160 information. When this variable is t,
1161 - accessing the parsing information for the first time in an editing session
1162 will read that file (if available) instead of parsing the document.
1163 - exiting Emacs or killing a buffer in reftex-mode will cause a new version
1164 of the file to be written."
1165 :group 'reftex-optimizations-for-large-documents
1166 :type 'boolean)
1167
1168 (defcustom reftex-use-multiple-selection-buffers nil
1169 "*Non-nil means use a separate selection buffer for each label type.
1170 These buffers are kept from one selection to the next and need not to be
1171 created for each use - so the menu generally comes up faster. The
1172 selection buffers will be erased (and therefore updated) automatically
1173 when new labels in its category are added. See the variable
1174 `reftex-auto-update-selection-buffers'."
1175 :group 'reftex-optimizations-for-large-documents
1176 :group 'reftex-referencing-labels
1177 :type 'boolean)
1178
1179 (defcustom reftex-auto-update-selection-buffers t
1180 "*Non-nil means, selection buffers will be updated automatically.
1181 When a new label is defined with `reftex-label', all selection buffers
1182 associated with that label category are emptied, in order to force an
1183 update upon next use. When nil, the buffers are left alone and have to be
1184 updated by hand, with the `g' key from the label selection process.
1185 The value of this variable will only have any effect when
1186 `reftex-use-multiple-selection-buffers' is non-nil."
1187 :group 'reftex-optimizations-for-large-documents
1188 :group 'reftex-referencing-labels
1189 :type 'boolean)
1190
1191 ;; Fontification and Faces ----------------------------------------------
1192
1193 (defgroup reftex-fontification-configurations nil
1194 "Options concerning the faces used in RefTeX."
1195 :group 'reftex)
1196
1197 (defcustom reftex-use-fonts t
1198 "*Non-nil means, use fonts in *toc* and selection buffers.
1199 Font-lock must be loaded as well to actually get fontified display.
1200 When changing this option, a rescan may be necessary to activate the change."
1201 :group 'reftex-fontification-configurations
1202 :type 'boolean)
1203
1204 (defcustom reftex-refontify-context 1
1205 "*Non-nil means, re-fontify the context in the label menu with font-lock.
1206 This slightly slows down the creation of the label menu. It is only necessary
1207 when you definitely want the context fontified.
1208
1209 This option may have 3 different values:
1210 nil Never refontify.
1211 t Always refontify.
1212 1 Refontify when absolutely necessary, e.g. when old versions of X-Symbol.
1213 The option is ignored when `reftex-use-fonts' is nil."
1214 :group 'reftex-fontification-configurations
1215 :group 'reftex-referencing-labels
1216 :type '(choice
1217 (const :tag "Never" nil)
1218 (const :tag "Always" t)
1219 (const :tag "When necessary" 1)))
1220
1221 (defcustom reftex-highlight-selection 'cursor
1222 "*Non-nil mean, highlight selected text in selection and *toc* buffers.
1223 Normally, the text near the cursor is the selected text, and it is
1224 highlighted. This is the entry most keys in the selction and *toc*
1225 buffers act on. However, if you mainly use the mouse to select an
1226 item, you may find it nice to have mouse-triggered highlighting
1227 instead or as well. The variable may have one of these values:
1228
1229 nil No highlighting.
1230 cursor Highlighting is cursor driven.
1231 mouse Highlighting is mouse driven.
1232 both Both cursor and mouse trigger highlighting.
1233
1234 Changing this variable requires to rebuild the selection and *toc* buffers
1235 to become effective (keys `g' or `r')."
1236 :group 'reftex-fontification-configurations
1237 :type '(choice
1238 (const :tag "Never" nil)
1239 (const :tag "Cursor driven" cursor)
1240 (const :tag "Mouse driven" mouse)
1241 (const :tag "Mouse and Cursor driven." both)))
1242
1243 (defcustom reftex-cursor-selected-face 'highlight
1244 "Face name to highlight cursor selected item in toc and selection buffers.
1245 See also the variable `reftex-highlight-selection'."
1246 :group 'reftex-fontification-configurations
1247 :type 'symbol)
1248 (defcustom reftex-mouse-selected-face 'secondary-selection
1249 "Face name to highlight mouse selected item in toc and selection buffers.
1250 See also the variable `reftex-highlight-selection'."
1251 :group 'reftex-fontification-configurations
1252 :type 'symbol)
1253 (defcustom reftex-file-boundary-face 'font-lock-comment-face
1254 "Face name for file boundaries in selection buffer."
1255 :group 'reftex-fontification-configurations
1256 :type 'symbol)
1257 (defcustom reftex-label-face 'font-lock-constant-face
1258 "Face name for labels in selection buffer."
1259 :group 'reftex-fontification-configurations
1260 :type 'symbol)
1261 (defcustom reftex-section-heading-face 'font-lock-function-name-face
1262 "Face name for section headings in toc and selection buffers."
1263 :group 'reftex-fontification-configurations
1264 :type 'symbol)
1265 (defcustom reftex-toc-header-face 'font-lock-comment-face
1266 "Face name for the header of a toc buffer."
1267 :group 'reftex-fontification-configurations
1268 :type 'symbol)
1269 (defcustom reftex-bib-author-face 'font-lock-keyword-face
1270 "Face name for author names in bib selection buffer."
1271 :group 'reftex-fontification-configurations
1272 :type 'symbol)
1273 (defcustom reftex-bib-year-face 'font-lock-comment-face
1274 "Face name for year in bib selection buffer."
1275 :group 'reftex-fontification-configurations
1276 :type 'symbol)
1277 (defcustom reftex-bib-title-face 'font-lock-function-name-face
1278 "Face name for article title in bib selection buffer."
1279 :group 'reftex-fontification-configurations
1280 :type 'symbol)
1281 (defcustom reftex-bib-extra-face 'font-lock-comment-face
1282 "Face name for bibliographic information in bib selection buffer."
1283 :group 'reftex-fontification-configurations
1284 :type 'symbol)
1285
1286 (defcustom reftex-pre-refontification-functions nil
1287 "X-Symbol specific hook.
1288 Functions get two arguments, the buffer from where the command started and a
1289 symbol indicating in what context the hook is called."
1290 :group 'reftex-fontification-configurations
1291 :type 'hook)
1292
1293 ;; Miscellaneous configurations -----------------------------------------
1294
1295 (defgroup reftex-miscellaneous-configurations nil
1296 "Collection of further configurations."
1297 :group 'reftex)
1298
1299 (defcustom reftex-extra-bindings nil
1300 "Non-nil means, make additional key bindings on startup.
1301 These extra bindings are located in the users `C-c letter' map."
1302 :group 'reftex-miscellaneous-configurations
1303 :type 'boolean)
1304
1305 (defcustom reftex-plug-into-AUCTeX nil
1306 "*Plug-in flags for AUCTeX interface.
1307 This variable is a list of 4 boolean flags. When a flag is non-nil,
1308 RefTeX will
1309
1310 - supply labels in new sections and environments (flag 1)
1311 - supply arguments for macros like `\\label'. (flag 2)
1312 - supply arguments for macros like `\\ref'. (flag 3)
1313 - supply arguments for macros like `\\cite'. (flag 4)
1314
1315 You may also set the variable itself to t or nil in order to turn all
1316 plug-ins on or off, respectively.
1317 \\<LaTeX-mode-map>Supplying labels in new sections and environments aplies when creating
1318 sections with \\[LaTeX-section] and environments with \\[LaTeX-environment].
1319 Supplying macro arguments applies when you insert such a macro interactively
1320 with \\[TeX-insert-macro].
1321 See the AUCTeX documentation for more information.
1322 RefTeX uses `fset' to take over the function calls. Changing the variable
1323 may require a restart of Emacs in order to become effective."
1324 :group 'reftex-miscellaneous-configurations
1325 :group 'LaTeX
1326 :type '(choice
1327 (const :tag "No plug-ins" nil)
1328 (const :tag "All possible plug-ins" t)
1329 (list
1330 :tag "Individual choice"
1331 :value (t t t t)
1332 (boolean :tag "supply label in new sections and environments")
1333 (boolean :tag "supply argument for macros like `\\label' ")
1334 (boolean :tag "supply argument for macros like `\\ref' ")
1335 (boolean :tag "supply argument for macros like `\\cite' ")
1336 )))
1337
1338 (defcustom reftex-allow-detached-macro-args nil
1339 "*Non-nil means, allow arguments of macros to be detached by whitespace.
1340 When this is t, `aaa' will be considered as argument of \\bb in the following
1341 construct: \\bbb [xxx] {aaa}."
1342 :group 'texmathp
1343 :type 'boolean)
1344
1345
1346 (defcustom reftex-load-hook nil
1347 "Hook which is being run when loading reftex.el."
1348 :group 'reftex-miscellaneous-configurations
1349 :type 'hook)
1350
1351 (defcustom reftex-mode-hook nil
1352 "Hook which is being run when turning on RefTeX mode."
1353 :group 'reftex-miscellaneous-configurations
1354 :type 'hook)
1355
1356 ;;; =========================================================================
1357 ;;;
1358 ;;; Define the formal stuff for a minor mode named RefTeX.
1359 ;;;
1360
1361 (defconst reftex-version "RefTeX version 3.41"
1362 "Version string for RefTeX.")
1363
1364 (defvar reftex-mode nil
1365 "Determines if RefTeX mode is active.")
1366 (make-variable-buffer-local 'reftex-mode)
1367
1368 (defvar reftex-mode-map (make-sparse-keymap)
1369 "Keymap for RefTeX mode.")
1370
1371 (defvar reftex-mode-menu nil)
1372
1373 ;;;###autoload
1374 (defun turn-on-reftex ()
1375 "Turn on RefTeX mode."
1376 (reftex-mode t))
1377
1378 ;;;###autoload
1379 (defun reftex-mode (&optional arg)
1380 "Minor mode with distinct support for \\label, \\ref and \\cite in LaTeX.
1381
1382 Labels can be created with `\\[reftex-label]' and referenced with `\\[reftex-reference]'.
1383 When referencing, you get a menu with all labels of a given type and
1384 context of the label definition. The selected label is inserted as a
1385 \\ref macro.
1386
1387 Citations can be made with `\\[reftex-citation]' which will use a regular expression
1388 to pull out a *formatted* list of articles from your BibTeX
1389 database. The selected citation is inserted as a \\cite macro.
1390
1391 A Table of Contents of the entire (multifile) document with browsing
1392 capabilities is available with `\\[reftex-toc]'.
1393
1394 Most command have help available on the fly. This help is accessed by
1395 pressing `?' to any prompt mentioning this feature.
1396
1397 Extensive documentation about RefTeX is in the file header of `reftex.el'.
1398 You can view this information with `\\[reftex-show-commentary]'.
1399
1400 \\{reftex-mode-map}
1401 Under X, these and other functions will also be available as `Ref' menu
1402 on the menu bar.
1403
1404 ------------------------------------------------------------------------------"
1405
1406 (interactive "P")
1407 (setq reftex-mode (not (or (and (null arg) reftex-mode)
1408 (<= (prefix-numeric-value arg) 0))))
1409
1410 ; Add or remove the menu, and run the hook
1411 (if reftex-mode
1412 (progn
1413 (easy-menu-add reftex-mode-menu)
1414 (and reftex-plug-into-AUCTeX
1415 (reftex-plug-into-AUCTeX))
1416 (run-hooks 'reftex-mode-hook))
1417 (easy-menu-remove reftex-mode-menu)))
1418
1419 (if (fboundp 'add-minor-mode)
1420 ;; Use it so that we get the extras
1421 (progn
1422 (put 'reftex-mode ':included '(memq major-mode '(latex-mode tex-mode)))
1423 (put 'reftex-mode ':menu-tag "RefTeX Mode")
1424 (add-minor-mode 'reftex-mode " Ref" reftex-mode-map))
1425 ;; The standard way
1426 (unless (assoc 'reftex-mode minor-mode-alist)
1427 (push '(reftex-mode " Ref") minor-mode-alist))
1428 (unless (assoc 'reftex-mode minor-mode-map-alist)
1429 (push (cons 'reftex-mode reftex-mode-map) minor-mode-map-alist)))
1430
1431 ;;; =========================================================================
1432 ;;;
1433 ;;; Silence warnings about variables in other packages.
1434 (defvar TeX-master)
1435 (defvar LaTeX-section-hook)
1436 (defvar LaTeX-label-function)
1437 (defvar tex-main-file)
1438 (defvar outline-minor-mode)
1439 (defvar font-lock-mode)
1440 (defvar font-lock-fontify-region-function)
1441 (defvar font-lock-syntactic-keywords)
1442
1443 ;;; =========================================================================
1444 ;;;
1445 ;;; Multibuffer Variables
1446 ;;;
1447 ;;; Technical notes: These work as follows: We keep just one list
1448 ;;; of labels for each master file - this can save a lot of memory.
1449 ;;; `reftex-master-index-list' is an alist which connects the true file name
1450 ;;; of each master file with the symbols holding the information on that
1451 ;;; document. Each buffer has local variables which point to these symbols.
1452
1453 ;; List of variables which handle the multifile stuff.
1454 ;; This list is used to tie, untie, and reset these symbols.
1455 (defconst reftex-multifile-symbols
1456 '(reftex-docstruct-symbol))
1457
1458 ;; Alist connecting master file names with the corresponding lisp symbols.
1459 (defvar reftex-master-index-list nil)
1460
1461 ;; Last index used for a master file.
1462 (defvar reftex-multifile-index 0)
1463
1464 ;; Variable holding the symbol with the label list of the document.
1465 (defvar reftex-docstruct-symbol nil)
1466 (make-variable-buffer-local 'reftex-docstruct-symbol)
1467
1468 (defun reftex-next-multifile-index ()
1469 ;; Return the next free index for multifile symbols.
1470 (incf reftex-multifile-index))
1471
1472 (defun reftex-tie-multifile-symbols ()
1473 ;; Tie the buffer-local symbols to globals connected with the master file.
1474 ;; If the symbols for the current master file do not exist, they are created.
1475
1476 (let* ((master (file-truename (reftex-TeX-master-file)))
1477 (index (assoc master reftex-master-index-list))
1478 (symlist reftex-multifile-symbols)
1479 symbol symname newflag)
1480 ;; Find the correct index.
1481 (if index
1482 ;; symbols do exist
1483 (setq index (cdr index))
1484 ;; Get a new index and add info to the alist.
1485 (setq index (reftex-next-multifile-index)
1486 newflag t)
1487 (push (cons master index) reftex-master-index-list))
1488
1489 ;; Get/create symbols and tie them.
1490 (while symlist
1491 (setq symbol (car symlist)
1492 symlist (cdr symlist)
1493 symname (symbol-name symbol))
1494 (set symbol (intern (concat symname "-" (int-to-string index))))
1495 (put (symbol-value symbol) ':master-index index)
1496 ;; Initialize if new symbols.
1497 (if newflag (set (symbol-value symbol) nil)))
1498
1499 ;; Return t if the symbols did already exist, nil when we've made them.
1500 (not newflag)))
1501
1502 (defun reftex-untie-multifile-symbols ()
1503 ;; Remove ties from multifile symbols, so that next use makes new ones.
1504 (let ((symlist reftex-multifile-symbols)
1505 (symbol nil))
1506 (while symlist
1507 (setq symbol (car symlist)
1508 symlist (cdr symlist))
1509 (set symbol nil))))
1510
1511 (defun reftex-TeX-master-file ()
1512 ;; Return the name of the master file associated with the current buffer.
1513 ;; When AUCTeX is loaded, we will use it's more sophisticated method.
1514 ;; We also support the default TeX and LaTeX modes by checking for a
1515 ;; variable tex-main-file.
1516 (let
1517 ((master
1518 (cond
1519 ((fboundp 'TeX-master-file) ; AUCTeX is loaded. Use its mechanism.
1520 (TeX-master-file t))
1521 ((boundp 'TeX-master) ; The variable is defined - lets use it.
1522 (cond
1523 ((eq TeX-master t)
1524 (buffer-file-name))
1525 ((eq TeX-master 'shared)
1526 (setq TeX-master (read-file-name "Master file: "
1527 nil nil t nil)))
1528 (TeX-master)
1529 (t
1530 (setq TeX-master (read-file-name "Master file: "
1531 nil nil t nil)))))
1532 ((boundp 'tex-main-file)
1533 ;; This is the variable from the default TeX modes.
1534 (cond
1535 ((stringp tex-main-file)
1536 ;; ok, this must be it
1537 tex-main-file)
1538 (t
1539 ;; In this case, the buffer is its own master.
1540 (buffer-file-name))))
1541 (t
1542 ;; Know nothing about master file. Assume this is a master file.
1543 (buffer-file-name)))))
1544 (cond
1545 ((null master)
1546 (error "Need a filename for this buffer, please save it first"))
1547 ((or (file-exists-p (concat master ".tex"))
1548 (reftex-get-buffer-visiting (concat master ".tex")))
1549 ;; Ahh, an extra .tex was missing...
1550 (setq master (concat master ".tex")))
1551 ((or (file-exists-p master)
1552 (reftex-get-buffer-visiting master))
1553 ;; We either see the file, or have a buffer on it. OK.
1554 )
1555 (t
1556 ;; Use buffer file name.
1557 (buffer-file-name)))
1558 (expand-file-name master)))
1559
1560 ;;; =========================================================================
1561 ;;;
1562 ;;; Functions to parse the buffer and to create and reference labels.
1563
1564 ;; The following constants are derived from `reftex-label-alist'.
1565
1566 ;; Prompt used for label type queries directed to the user.
1567 (defconst reftex-type-query-prompt nil)
1568
1569 ;; Help string for label type queries.
1570 (defconst reftex-type-query-help nil)
1571
1572 ;; Alist relating label type to reference format.
1573 (defconst reftex-typekey-to-format-alist nil)
1574
1575 ;; Alist relating label type to label affix.
1576 (defconst reftex-typekey-to-prefix-alist nil)
1577
1578 ;; Alist relating environments or macros to label type and context regexp.
1579 (defconst reftex-env-or-mac-alist nil)
1580
1581 ;; List of macros carrying a label.
1582 (defconst reftex-label-mac-list nil)
1583
1584 ;; List of environments carrying a label.
1585 (defconst reftex-label-env-list nil)
1586
1587 ;; List of all typekey letters in use.
1588 (defconst reftex-typekey-list nil)
1589
1590 ;; Alist relating magic words to a label type.
1591 (defconst reftex-words-to-typekey-alist nil)
1592
1593 ;; The last list-of-labels entry used in a reference.
1594 (defvar reftex-last-used-reference (list nil nil nil nil))
1595
1596 ;; The message when follow-mode is suspended
1597 (defconst reftex-no-follow-message
1598 "No follow-mode into unvisited file. Press SPC to visit it.")
1599 (defconst reftex-no-info-message
1600 "%s: info not available, use `\\[reftex-view-crossref]' to get it.")
1601
1602 ;; Global variables used for communication between functions.
1603 (defvar reftex-default-context-position nil)
1604 (defvar reftex-location-start nil)
1605 (defvar reftex-call-back-to-this-buffer nil)
1606 (defvar reftex-select-return-marker (make-marker))
1607 (defvar reftex-active-toc nil)
1608 (defvar reftex-tex-path nil)
1609 (defvar reftex-bib-path nil)
1610 (defvar reftex-last-follow-point nil)
1611 (defvar reftex-latex-syntax-table nil)
1612 (defvar reftex-prefix nil)
1613 (defvar reftex-section-levels-all nil)
1614 (defvar reftex-buffers-with-changed-invisibility nil)
1615
1616 ;; List of buffers created temporarily for lookup, which should be killed.
1617 (defvar reftex-buffers-to-kill nil)
1618
1619 ;; Regexp to find anything.
1620 (defvar reftex-section-regexp nil)
1621 (defvar reftex-section-or-include-regexp nil)
1622 (defvar reftex-everything-regexp nil)
1623 (defvar reftex-find-label-regexp-format nil)
1624 (defvar reftex-find-label-regexp-format2 nil)
1625
1626 ;;; The parser functions -----------------------------------------------------
1627
1628 (defvar reftex-memory nil
1629 "Memorizes old variable values to indicate changes in these variables.")
1630
1631 (defun reftex-access-scan-info (&optional rescan file)
1632 "Ensure access to the scanning info for the current file."
1633 ;; When the multifile symbols are not yet tied,
1634 ;; tie them. When they are empty or RESCAN is non-nil, scan the document.
1635 ;; But, when RESCAN is -1, don't rescan even if docstruct is empty.
1636 ;; When FILE is non-nil, parse only from that file.
1637
1638 ;; Make sure we have the symbols tied
1639 (if (eq reftex-docstruct-symbol nil)
1640 ;; Symbols are not yet tied: Tie them.
1641 (reftex-tie-multifile-symbols))
1642
1643 (reftex-ensure-compiled-variables)
1644
1645 (when (or (null (symbol-value reftex-docstruct-symbol))
1646 (member rescan '(t 1 (4) (16))))
1647 ;; The docstruct will change: Remove selection buffers.
1648 (save-excursion
1649 (reftex-erase-all-selection-buffers)))
1650
1651 (if (and (null (symbol-value reftex-docstruct-symbol))
1652 (not (member rescan '(t 1 (4) (16))))
1653 reftex-save-parse-info)
1654 ;; Try to read the stuff from a file
1655 (reftex-access-parse-file 'read))
1656
1657 (cond
1658 ((equal rescan -1)) ;; We are not allowed to scan.
1659 ((not (symbol-value reftex-docstruct-symbol))
1660 ;; Scan the whole document
1661 (reftex-do-parse 1 file))
1662 ((member rescan '(t 1 (4) (16)))
1663 ;; Scan whatever was required by the caller.
1664 (reftex-do-parse rescan file))))
1665
1666 (defun reftex-parse-one ()
1667 "Re-parse this file."
1668 (interactive)
1669 (let ((reftex-enable-partial-scans t))
1670 (reftex-access-scan-info '(4))))
1671
1672 (defun reftex-parse-all ()
1673 "Re-parse entire document."
1674 (interactive)
1675 (reftex-access-scan-info '(16)))
1676
1677 (defun reftex-do-parse (rescan &optional file)
1678 "Do a document rescan. When allowed, do only a partial scan from FILE."
1679
1680 ;; Normalize the rescan argument
1681 (setq rescan (cond ((eq rescan t) t)
1682 ((eq rescan 1) 1)
1683 ((equal rescan '(4)) t)
1684 ((equal rescan '(16)) 1)
1685 (t 1)))
1686
1687 ;; Partial scans only when allowed
1688 (unless reftex-enable-partial-scans
1689 (setq rescan 1))
1690
1691 ;; Do the scanning.
1692
1693 (let* ((old-list (symbol-value reftex-docstruct-symbol))
1694 (master (reftex-TeX-master-file))
1695 (true-master (file-truename master))
1696 (master-dir (file-name-as-directory (file-name-directory master)))
1697 (file (or file (buffer-file-name)))
1698 (true-file (file-truename file))
1699 (bibview-cache (assq 'bibview-cache old-list))
1700 from-file appendix docstruct tmp)
1701
1702 ;; Make sure replacement is really an option here
1703 (when (and (eq rescan t)
1704 (not (and (member (list 'bof file) old-list)
1705 (member (list 'eof file) old-list))))
1706 ;; Scan whole document because no such file section exists
1707 (setq rescan 1))
1708 (when (string= true-file true-master)
1709 ;; Scan whole document because this file is the master
1710 (setq rescan 1))
1711
1712 ;; From which file do we start?
1713 (setq from-file
1714 (cond ((eq rescan t) (or file master))
1715 ((eq rescan 1) master)
1716 (t (error "This should not happen (reftex-do-parse)"))))
1717
1718 ;; Find active toc entry and initialize section-numbers
1719 (setq reftex-active-toc (reftex-last-assoc-before-elt
1720 'toc (list 'bof from-file) old-list)
1721 appendix (reftex-last-assoc-before-elt
1722 'appendix (list 'bof from-file) old-list))
1723
1724 (reftex-init-section-numbers reftex-active-toc appendix)
1725
1726 (if (eq rescan 1)
1727 (message "Scanning entire document...")
1728 (message "Scanning document from %s..." from-file))
1729
1730 (save-window-excursion
1731 (save-excursion
1732 (unwind-protect
1733 (setq docstruct
1734 (reftex-parse-from-file
1735 from-file docstruct master-dir))
1736 (reftex-kill-temporary-buffers))))
1737
1738 (message "Scanning document... done")
1739
1740 ;; Turn the list around.
1741 (setq docstruct (nreverse docstruct))
1742
1743 ;; Set or insert
1744 (setq docstruct (reftex-replace-label-list-segment
1745 old-list docstruct (eq rescan 1)))
1746
1747 ;; Add all missing information
1748 (unless (assq 'label-numbers docstruct)
1749 (push (cons 'label-numbers nil) docstruct))
1750 (unless (assq 'master-dir docstruct)
1751 (push (cons 'master-dir master-dir) docstruct))
1752 (unless (assq 'bibview-cache docstruct)
1753 (push (cons 'bibview-cache (cdr bibview-cache)) docstruct))
1754 (let* ((bof1 (memq (assq 'bof docstruct) docstruct))
1755 (bof2 (assq 'bof (cdr bof1)))
1756 (is-multi (not (not (and bof1 bof2))))
1757 (entry (or (assq 'is-multi docstruct)
1758 (car (push (list 'is-multi is-multi) docstruct)))))
1759 (setcdr entry (cons is-multi nil)))
1760 (unless (assq 'xr docstruct)
1761 (let* ((allxr (reftex-all-assq 'xr-doc docstruct))
1762 (alist (mapcar
1763 (function
1764 (lambda (x)
1765 (if (setq tmp (reftex-find-tex-file (nth 2 x)
1766 master-dir))
1767 (cons (nth 1 x) tmp)
1768 (message "Can't find external document %s"
1769 (nth 2 x))
1770 nil)))
1771 allxr))
1772 (alist (delq nil alist))
1773 (allprefix (delq nil (mapcar 'car alist)))
1774 (regexp (if allprefix
1775 (concat "\\`\\("
1776 (mapconcat 'identity allprefix "\\|")
1777 "\\)")
1778 "\\\\\\\\\\\\"))) ; this will never match
1779 (push (list 'xr alist regexp) docstruct)))
1780
1781 (set reftex-docstruct-symbol docstruct)
1782 (put reftex-docstruct-symbol 'modified t)))
1783
1784 (defun reftex-parse-from-file (file docstruct master-dir)
1785 ;; Scan the buffer for labels and save them in a list.
1786 (let ((regexp reftex-everything-regexp)
1787 (bound 0)
1788 file-found tmp include-file
1789 (level 1)
1790 (highest-level 100)
1791 toc-entry next-buf buf)
1792
1793 (catch 'exit
1794 (setq file-found (reftex-find-tex-file file master-dir))
1795 (if (and (not file-found)
1796 (setq buf (reftex-get-buffer-visiting file)))
1797 (setq file-found (buffer-file-name buf)))
1798
1799 (unless file-found
1800 (push (list 'file-error file) docstruct)
1801 (throw 'exit nil))
1802
1803 (save-excursion
1804
1805 (message "Scanning file %s" file)
1806 (set-buffer
1807 (setq next-buf
1808 (reftex-get-file-buffer-force
1809 file-found
1810 (not (eq t reftex-keep-temporary-buffers)))))
1811
1812 ;; Begin of file mark
1813 (setq file (buffer-file-name))
1814 (push (list 'bof file) docstruct)
1815
1816 (save-excursion
1817 (save-restriction
1818 (widen)
1819 (goto-char 1)
1820
1821 (while (re-search-forward regexp nil t)
1822
1823 (cond
1824
1825 ((match-end 1)
1826 ;; It is a label
1827 (push (reftex-label-info (reftex-match-string 1) file bound)
1828 docstruct))
1829
1830 ((match-end 3)
1831 ;; It is a section
1832 (setq bound (point))
1833
1834 ;; Insert in List
1835 (setq toc-entry (reftex-section-info file))
1836 (setq level (nth 5 toc-entry))
1837 (setq highest-level (min highest-level level))
1838 (if (= level highest-level)
1839 (message
1840 "Scanning %s %s ..."
1841 (car (rassoc level reftex-section-levels))
1842 (nth 6 toc-entry)))
1843
1844 (push toc-entry docstruct)
1845 (setq reftex-active-toc toc-entry))
1846
1847 ((match-end 7)
1848 ;; It's an include or input
1849 (setq include-file (reftex-match-string 7))
1850 ;; Test if this file should be ignored
1851 (unless (delq nil (mapcar
1852 (lambda (x) (string-match x include-file))
1853 reftex-no-include-regexps))
1854 ;; Parse it
1855 (setq docstruct
1856 (reftex-parse-from-file
1857 include-file
1858 docstruct master-dir))))
1859
1860 ((match-end 9)
1861 ;; Appendix starts here
1862 (reftex-init-section-numbers nil t)
1863 (push (cons 'appendix t) docstruct))
1864
1865 ((match-end 10)
1866 ;; A macro with label
1867 (save-excursion
1868 (let* ((mac (reftex-match-string 10))
1869 (label (progn (goto-char (match-end 10))
1870 (save-match-data
1871 (reftex-no-props
1872 (reftex-nth-arg-wrapper
1873 mac)))))
1874 (typekey (nth 1 (assoc mac reftex-env-or-mac-alist)))
1875 (entry (progn (if typekey
1876 ;; A typing macro
1877 (goto-char (match-end 0))
1878 ;; A newtral macro
1879 (goto-char (match-end 10))
1880 (reftex-move-over-touching-args))
1881 (reftex-label-info
1882 label file bound nil nil))))
1883 (push entry docstruct))))
1884 (t (error "This should not happen (reftex-parse-from-file)")))
1885 )
1886
1887 ;; Find bibliography statement
1888 (when (setq tmp (reftex-locate-bibliography-files master-dir))
1889 (push (cons 'bib tmp) docstruct))
1890
1891 (goto-char 1)
1892 (when (re-search-forward
1893 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
1894 (push (cons 'thebib file) docstruct))
1895
1896 ;; Find external document specifications
1897 (goto-char 1)
1898 (while (re-search-forward "[\n\r][ \t]*\\\\externaldocument\\(\\[\\([^]]*\\)\\]\\)?{\\([^}]+\\)}" nil t)
1899 (push (list 'xr-doc (reftex-match-string 2)
1900 (reftex-match-string 3))
1901 docstruct))
1902
1903 ;; End of file mark
1904 (push (list 'eof file) docstruct))))
1905
1906 ;; Kill the scanned buffer
1907 (reftex-kill-temporary-buffers next-buf))
1908
1909 ;; Return the list
1910 docstruct))
1911
1912 (defun reftex-locate-bibliography-files (master-dir)
1913 ;; Scan buffer for bibliography macro and return file list.
1914 (let (files)
1915 (save-excursion
1916 (goto-char (point-min))
1917 (when (re-search-forward
1918 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\bibliography{[ \t]*\\([^}]+\\)" nil t)
1919 (setq files (split-string (reftex-match-string 2)
1920 "[ \t\n\r]*,[ \t\n\r]*"))
1921 (setq files
1922 (mapcar
1923 (lambda (x)
1924 (if (or (member x reftex-bibfile-ignore-list)
1925 (delq nil (mapcar (lambda (re) (string-match re x))
1926 reftex-bibfile-ignore-regexps)))
1927 ;; excluded file
1928 nil
1929 ;; find the file
1930 (reftex-find-bib-file
1931 (if (string-match "\\.bib\\'" x) x (concat x ".bib"))
1932 master-dir)))
1933 files))
1934 (delq nil files)))))
1935
1936 (defun reftex-replace-label-list-segment (old insert &optional entirely)
1937 ;; Replace the segment in OLD which corresponds to INSERT.
1938 ;; Works with side effects, directly changes old.
1939 ;; If entirely is t, just return INSERT.
1940 ;; This function also makes sure the old toc markers do not point anywhere.
1941
1942 (cond
1943 (entirely
1944 (reftex-silence-toc-markers old (length old))
1945 insert)
1946 (t (let* ((new old)
1947 (file (nth 1 (car insert)))
1948 (eof-list (member (list 'eof file) old))
1949 (bof-list (member (list 'bof file) old))
1950 n)
1951 (if (not (and bof-list eof-list))
1952 (error "Cannot splice")
1953 ;; Splice
1954 (reftex-silence-toc-markers bof-list (- (length bof-list)
1955 (length eof-list)))
1956 (setq n (- (length old) (length bof-list)))
1957 (setcdr (nthcdr n new) (cdr insert))
1958 (setcdr (nthcdr (1- (length new)) new) (cdr eof-list)))
1959 new))))
1960
1961 (defun reftex-silence-toc-markers (list n)
1962 ;; Set all toc markers in the first N entries in list to nil
1963 (while (and list (> (decf n) -1))
1964 (and (eq (car (car list)) 'toc)
1965 (markerp (nth 4 (car list)))
1966 (set-marker (nth 4 (car list)) nil))
1967 (pop list)))
1968
1969 (defun reftex-access-parse-file (action)
1970 "Perform ACTION on the parse file (the .rel file).
1971 Valid actions are: readable, restore, read, kill, write."
1972 (let* ((list (symbol-value reftex-docstruct-symbol))
1973 (docstruct-symbol reftex-docstruct-symbol)
1974 (master (reftex-TeX-master-file))
1975 (enable-local-variables nil)
1976 (file (if (string-match "\\.[a-zA-Z]+\\'" master)
1977 (concat (substring master 0 (match-beginning 0)) ".rel")
1978 (concat master ".rel"))))
1979 (cond
1980 ((eq action 'readable)
1981 (file-readable-p file))
1982 ((eq action 'restore)
1983 (put reftex-docstruct-symbol 'modified nil)
1984 (if (eq reftex-docstruct-symbol nil)
1985 ;; Symbols are not yet tied: Tie them.
1986 (reftex-tie-multifile-symbols))
1987 (if (file-exists-p file)
1988 ;; load the file and return t for success
1989 (condition-case nil
1990 (progn (load-file file) t)
1991 (error (set reftex-docstruct-symbol nil)
1992 (error "Error while loading file %s" file)))
1993 ;; Throw an exception if the file does not exist
1994 (error "No restore file %s" file)))
1995 ((eq action 'read)
1996 (put reftex-docstruct-symbol 'modified nil)
1997 (if (file-exists-p file)
1998 ;; load the file and return t for success
1999 (condition-case nil
2000 (progn (load-file file) t)
2001 (error (message "Error while loading file %s" file)
2002 (set reftex-docstruct-symbol nil)
2003 nil))
2004 ;; return nil for failure, but no exception
2005 nil))
2006 ((eq action 'kill)
2007 ;; Remove the file
2008 (when (and (file-exists-p file) (file-writable-p file))
2009 (message "Unlinking file %s" file)
2010 (delete-file file)))
2011 (t
2012 (put docstruct-symbol 'modified nil)
2013 (save-excursion
2014 (if (file-writable-p file)
2015 (progn
2016 (message "Writing parse file %s" (abbreviate-file-name file))
2017 (find-file file)
2018 (erase-buffer)
2019 (insert (format ";; RefTeX parse info file\n"))
2020 (insert (format ";; File: %s\n" master))
2021 (insert (format ";; User: %s (%s)\n\n"
2022 (user-login-name) (user-full-name)))
2023 (insert "(set reftex-docstruct-symbol '(\n\n")
2024 (let ((standard-output (current-buffer)))
2025 (mapcar
2026 (function
2027 (lambda (x)
2028 (cond ((eq (car x) 'toc)
2029 ;; A toc entry. Do not save the marker.
2030 ;; Save the markers position at position 8
2031 (print (list 'toc "toc" (nth 2 x) (nth 3 x)
2032 nil (nth 5 x) (nth 6 x) (nth 7 x)
2033 (or (and (markerp (nth 4 x))
2034 (marker-position (nth 4 x)))
2035 (nth 8 x)))))
2036 (t (print x)))))
2037 list))
2038 (insert "))\n\n")
2039 (save-buffer 0)
2040 (kill-buffer (current-buffer)))
2041 (error "Cannot write to file %s" file)))
2042 t))))
2043
2044 (defun reftex-kill-buffer-hook ()
2045 "Save RefTeX's parse file for this buffer if the information has changed."
2046 ;; Save the parsing information if it was modified.
2047 ;; This function should be installed in `kill-buffer-hook'.
2048 ;; We are careful to make sure nothing goes wring in this function.
2049 (when (and (boundp 'reftex-mode) reftex-mode
2050 (boundp 'reftex-save-parse-info) reftex-save-parse-info
2051 (boundp 'reftex-docstruct-symbol) reftex-docstruct-symbol
2052 (symbol-value reftex-docstruct-symbol)
2053 (get reftex-docstruct-symbol 'modified))
2054 ;; Write the file.
2055 (condition-case nil
2056 (reftex-access-parse-file 'write)
2057 (error nil))))
2058
2059 (defun reftex-kill-emacs-hook ()
2060 "Call `reftex-kill-buffer-hook' on all buffers."
2061 ;; This function should be installed in `kill-emacs-hook'.
2062 (save-excursion
2063 (mapcar (lambda (buf)
2064 (set-buffer buf)
2065 (reftex-kill-buffer-hook))
2066 (buffer-list))))
2067
2068 (defun reftex-section-info (file)
2069 ;; Return a section entry for the current match.
2070 ;; Carefull: This function expects the match-data to be still in place!
2071 (let* ((marker (set-marker (make-marker) (1- (match-beginning 3))))
2072 (macro (reftex-match-string 3))
2073 (star (= ?* (char-after (match-end 3))))
2074 (level (cdr (assoc macro reftex-section-levels-all)))
2075 (section-number (reftex-section-number level star))
2076 (text1 (save-match-data (save-excursion (reftex-context-substring))))
2077 (literal (buffer-substring-no-properties
2078 (1- (match-beginning 3))
2079 (min (point-max) (+ (match-end 0) (length text1) 1))))
2080 ;; Literal can be too short since text1 too short. No big problem.
2081 (text (reftex-nicify-text text1)))
2082
2083 ;; Add section number and indentation
2084 (setq text
2085 (concat
2086 (make-string (* reftex-level-indent level) ?\ )
2087 (if (nth 1 reftex-label-menu-flags) ; section number flag
2088 (concat section-number " "))
2089 text))
2090 (list 'toc "toc" text file marker level section-number
2091 literal (marker-position marker))))
2092
2093 (defun reftex-label-info-update (cell)
2094 ;; Update information about just one label in a different file.
2095 ;; CELL contains the old info list
2096 (let* ((label (nth 0 cell))
2097 (typekey (nth 1 cell))
2098 ;; (text (nth 2 cell))
2099 (file (nth 3 cell))
2100 (comment (nth 4 cell))
2101 (note (nth 5 cell))
2102 (buf (reftex-get-file-buffer-force
2103 file (not (eq t reftex-keep-temporary-buffers)))))
2104 (if (not buf)
2105 (list label typekey "" file comment "LOST LABEL. RESCAN TO FIX.")
2106 (save-excursion
2107 (set-buffer buf)
2108 (save-restriction
2109 (widen)
2110 (goto-char 1)
2111
2112 (if (or (re-search-forward
2113 (format reftex-find-label-regexp-format
2114 (regexp-quote label)) nil t)
2115 (re-search-forward
2116 (format reftex-find-label-regexp-format2
2117 (regexp-quote label)) nil t))
2118
2119 (progn
2120 (backward-char 1)
2121 (append (reftex-label-info label file) (list note)))
2122 (list label typekey "" file "LOST LABEL. RESCAN TO FIX.")))))))
2123
2124 (defun reftex-label-info (label &optional file bound derive env-or-mac)
2125 ;; Return info list on LABEL at point.
2126 (let* ((env-or-mac (or env-or-mac (reftex-label-location bound)))
2127 (typekey (nth 1 (assoc env-or-mac reftex-env-or-mac-alist)))
2128 (file (or file (buffer-file-name)))
2129 (parse (if (reftex-typekey-check
2130 typekey reftex-use-text-after-label-as-context)
2131 nil
2132 (nth 2 (assoc env-or-mac reftex-env-or-mac-alist))))
2133 (text (reftex-short-context env-or-mac parse reftex-location-start
2134 derive))
2135 (in-comment (reftex-in-comment)))
2136 (list label typekey text file in-comment)))
2137
2138 (defun reftex-in-comment ()
2139 (save-excursion
2140 (skip-chars-backward "^%\n\r")
2141 (eq (preceding-char) ?%)))
2142
2143 (defun reftex-short-context (env parse &optional bound derive)
2144 ;; Get about one line of useful context for the label definition at point.
2145
2146 (if (consp parse)
2147 (setq parse (if derive (cdr parse) (car parse))))
2148
2149 (reftex-nicify-text
2150
2151 (cond
2152
2153 ((null parse)
2154 (save-excursion
2155 (reftex-context-substring)))
2156
2157 ((eq parse t)
2158 (if (string= env "section")
2159 ;; special treatment for section labels
2160 (save-excursion
2161 (if (and (re-search-backward reftex-section-or-include-regexp
2162 (point-min) t)
2163 (match-end 2))
2164 (progn
2165 (goto-char (match-end 0))
2166 (reftex-context-substring))
2167 (if reftex-active-toc
2168 (progn
2169 (string-match "{\\([^}]*\\)" (nth 7 reftex-active-toc))
2170 (match-string 1 (nth 7 reftex-active-toc)))
2171 "SECTION HEADING NOT FOUND")))
2172 (save-excursion
2173 (goto-char reftex-default-context-position)
2174 (unless (eq (string-to-char env) ?\\)
2175 (reftex-move-over-touching-args))
2176 (reftex-context-substring))))
2177
2178 ((stringp parse)
2179 (save-excursion
2180 (if (re-search-backward parse bound t)
2181 (progn
2182 (goto-char (match-end 0))
2183 (reftex-context-substring))
2184 "NO MATCH FOR CONTEXT REGEXP")))
2185
2186 ((integerp parse)
2187 (or (save-excursion
2188 (goto-char reftex-default-context-position)
2189 (reftex-nth-arg
2190 parse
2191 (nth 6 (assoc env reftex-env-or-mac-alist))))
2192 ""))
2193
2194 ((fboundp parse)
2195 ;; A hook function. Call it.
2196 (save-excursion
2197 (condition-case error-var
2198 (funcall parse env)
2199 (error (format "HOOK ERROR: %s" (cdr error-var))))))
2200 (t
2201 "ILLEGAL VALUE OF PARSE"))))
2202
2203 (defun reftex-nicify-text (text)
2204 ;; Make TEXT nice for inclusion as context into label menu
2205 ;; remove line breaks and extra white space
2206 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
2207 (setq text (replace-match " " nil t text)))
2208 ;; cut before the next `\end{' or `\item' or `\\'
2209 (if (string-match "\\(\\\\end{\\|\\\\item\\|\\\\\\\\\\).*" text)
2210 (setq text (replace-match "" nil t text)))
2211 ;; kill the embedded label
2212 (if (string-match "\\\\label{[^}]*}" text)
2213 (setq text (replace-match "" nil t text)))
2214 ;; remove leading garbage
2215 (if (string-match "\\`[ }]+" text)
2216 (setq text (replace-match "" nil t text)))
2217 ;; limit length
2218 (cond
2219 ((> (length text) 100) (substring text 0 100))
2220 ((= (length text) 0) (make-string 1 ?\ ))
2221 (t text)))
2222
2223 (defun reftex-where-am-I ()
2224 ;; Return the docstruct entry above point. Actually returns a cons
2225 ;; cell in which the cdr is a flag indicating if the information is
2226 ;; exact (t) or approximate (nil).
2227
2228 (let ((docstruct (symbol-value reftex-docstruct-symbol))
2229 (cnt 0) rtn
2230 found)
2231 (save-excursion
2232 (while (not rtn)
2233 (incf cnt)
2234 (setq found (re-search-backward reftex-everything-regexp nil t))
2235 (setq rtn
2236 (cond
2237 ((not found)
2238 ;; no match
2239 (or
2240 (car (member (list 'bof (buffer-file-name)) docstruct))
2241 (not (setq cnt 2))
2242 (assq 'bof docstruct) ;; for safety reasons
2243 'corrupted))
2244 ((match-end 1)
2245 ;; Label
2246 (assoc (reftex-match-string 1)
2247 (symbol-value reftex-docstruct-symbol)))
2248 ((match-end 3)
2249 ;; Section
2250 (goto-char (1- (match-beginning 3)))
2251 (let* ((list (member (list 'bof (buffer-file-name))
2252 docstruct))
2253 (endelt (car (member (list 'eof (buffer-file-name))
2254 list)))
2255 rtn1)
2256 (while (and list (not (eq endelt (car list))))
2257 (if (and (eq (car (car list)) 'toc)
2258 (string= (buffer-file-name)
2259 (nth 3 (car list))))
2260 (cond
2261 ((equal (point)
2262 (or (and (markerp (nth 4 (car list)))
2263 (marker-position (nth 4 (car list))))
2264 (nth 8 (car list))))
2265 ;; Fits with marker position or recorded position
2266 (setq rtn1 (car list) list nil))
2267 ((looking-at (reftex-make-regexp-allow-for-ctrl-m
2268 (nth 7 (car list))))
2269 ;; Same title
2270 (setq rtn1 (car list) list nil cnt 2))))
2271 (pop list))
2272 rtn1))
2273 ((match-end 7)
2274 ;; Input or include...
2275 (car
2276 (member (list 'eof (reftex-find-tex-file
2277 (reftex-match-string 7)
2278 (cdr (assq 'master-dir docstruct))))
2279 docstruct)))
2280 ((match-end 9)
2281 (assq 'appendix (symbol-value reftex-docstruct-symbol)))
2282 ((match-end 10)
2283 (save-excursion
2284 (goto-char (match-end 10))
2285 (assoc (reftex-no-props
2286 (reftex-nth-arg-wrapper
2287 (reftex-match-string 10)))
2288 (symbol-value reftex-docstruct-symbol))))
2289 (t
2290 (error "This should not happen (reftex-where-am-I)"))))))
2291 (cons rtn (eq cnt 1))))
2292
2293 (defun reftex-label-location (&optional bound)
2294 "Return the environment or macro which determines the label type at point.
2295 If optional BOUND is an integer, limit backward searches to that point."
2296
2297 (let* ((loc1 (reftex-what-macro reftex-label-mac-list bound))
2298 (loc2 (reftex-what-environment reftex-label-env-list bound))
2299 (p1 (or (cdr loc1) 0))
2300 (p2 (or (cdr loc2) 0)))
2301
2302 (setq reftex-location-start (max p1 p2))
2303 (if (>= p1 p2)
2304 (progn
2305 (setq reftex-default-context-position (+ p1 (length (car loc1))))
2306 (or (car loc1) "section"))
2307 (setq reftex-default-context-position (+ p2 8 (length (car loc2))))
2308 (or (car loc2) "section"))))
2309
2310 (defun reftex-parse-args (macro)
2311 ;; Return a list of macro name, nargs, arg-nr which is label and a list of
2312 ;; optional argument indices.
2313 (if (string-match "[[{]\\*?[]}]" macro)
2314 (progn
2315 (let ((must-match (substring macro 0 (match-beginning 0)))
2316 (args (substring macro (match-beginning 0)))
2317 opt-list nlabel (cnt 0))
2318 (while (string-match "\\`[[{]\\(\\*\\)?[]}]" args)
2319 (incf cnt)
2320 (when (eq ?\[ (string-to-char args))
2321 (push cnt opt-list))
2322 (when (and (match-end 1)
2323 (not nlabel))
2324 (setq nlabel cnt))
2325 (setq args (substring args (match-end 0))))
2326 (list must-match cnt nlabel opt-list)))
2327 nil))
2328
2329 (defsubst reftex-move-to-next-arg (&optional ignore)
2330 ;; Assuming that we are at the end of a macro name or a macro argument,
2331 ;; move forward to the opening parenthesis of the next argument.
2332 ;; This function understands the splitting of macros over several lines
2333 ;; in TeX.
2334 (cond
2335 ;; Just to be quick:
2336 ((memq (following-char) '(?\[ ?\{)))
2337 ;; Do a search
2338 ((and reftex-allow-detached-macro-args
2339 (looking-at "[ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*[[{]"))
2340 (goto-char (1- (match-end 0)))
2341 t)
2342 (t nil)))
2343
2344 (defsubst reftex-move-to-previous-arg (&optional bound)
2345 ;; Assuming that we are in front of a macro argument,
2346 ;; move backward to the closing parenthesis of the previous argument.
2347 ;; This function understands the splitting of macros over several lines
2348 ;; in TeX.
2349 (cond
2350 ;; Just to be quick:
2351 ((memq (preceding-char) '(?\] ?\})))
2352 ;; Do a search
2353 ((and reftex-allow-detached-macro-args
2354 (re-search-backward
2355 "[]}][ \t]*[\n\r]?\\([ \t]*%[^\n\r]*[\n\r]\\)*[ \t]*\\=" bound t))
2356 (goto-char (1+ (match-beginning 0)))
2357 t)
2358 (t nil)))
2359
2360 (defun reftex-nth-arg-wrapper (key)
2361 (let ((entry (assoc key reftex-env-or-mac-alist)))
2362 (reftex-nth-arg (nth 5 entry) (nth 6 entry))))
2363
2364 (defun reftex-nth-arg (n &optional opt-args)
2365 ;; Return the nth following {} or [] parentheses content.
2366 ;; OPT-ARGS is a list of argument numbers which are optional.
2367
2368 ;; If we are sitting at a macro start, skip to end of macro name.
2369 (and (eq (following-char) ?\\) (skip-chars-forward "a-zA-Z*\\\\"))
2370
2371 (if (= n 1000)
2372 ;; Special case: Skip all touching arguments
2373 (progn
2374 (reftex-move-over-touching-args)
2375 (reftex-context-substring))
2376
2377 ;; Do the real thing.
2378 (let ((cnt 1))
2379
2380 (when (reftex-move-to-next-arg)
2381
2382 (while (< cnt n)
2383 (while (and (member cnt opt-args)
2384 (eq (following-char) ?\{))
2385 (incf cnt))
2386 (when (< cnt n)
2387 (unless (and (condition-case nil
2388 (or (forward-list 1) t)
2389 (error nil))
2390 (reftex-move-to-next-arg)
2391 (incf cnt))
2392 (setq cnt 1000))))
2393
2394 (while (and (memq cnt opt-args)
2395 (eq (following-char) ?\{))
2396 (incf cnt)))
2397 (if (and (= n cnt)
2398 (> (skip-chars-forward "{\\[") 0))
2399 (reftex-context-substring)
2400 nil))))
2401
2402 (defun reftex-move-over-touching-args ()
2403 (condition-case nil
2404 (while (memq (following-char) '(?\[ ?\{))
2405 (forward-list 1))
2406 (error nil)))
2407
2408 (defun reftex-context-substring ()
2409 ;; Return up to 100 chars from point
2410 ;; When point is just after a { or [, limit string to matching parenthesis
2411 (cond
2412 ((or (= (preceding-char) ?\{)
2413 (= (preceding-char) ?\[))
2414 ;; Inside a list - get only the list.
2415 (buffer-substring-no-properties
2416 (point)
2417 (min (+ (point) 150)
2418 (point-max)
2419 (condition-case nil
2420 (progn
2421 (up-list 1)
2422 (1- (point)))
2423 (error (point-max))))))
2424 (t
2425 ;; no list - just grab 100 characters
2426 (buffer-substring-no-properties (point)
2427 (min (+ (point) 150) (point-max))))))
2428
2429 ;; Variable holding the vector with section numbers
2430 (defvar reftex-section-numbers [0 0 0 0 0 0 0 0])
2431
2432 (defun reftex-init-section-numbers (&optional toc-entry appendix)
2433 ;; Initialize the section numbers with zeros or with what is found
2434 ;; in the toc entry.
2435 (let* ((level (or (nth 5 toc-entry) -1))
2436 (numbers (nreverse (split-string (or (nth 6 toc-entry) "") "\\.")))
2437 (depth (1- (length reftex-section-numbers)))
2438 (i depth) number-string)
2439 (while (>= i 0)
2440 (if (> i level)
2441 (aset reftex-section-numbers i 0)
2442 (setq number-string (or (car numbers) "0"))
2443 (if (string-match "\\`[A-Z]\\'" number-string)
2444 (aset reftex-section-numbers i
2445 (- (string-to-char number-string) ?A -1))
2446 (aset reftex-section-numbers i (string-to-int number-string)))
2447 (pop numbers))
2448 (decf i)))
2449 (put 'reftex-section-numbers 'appendix appendix))
2450
2451 (defun reftex-section-number (&optional level star)
2452 ;; Return a string with the current section number.
2453 ;; When LEVEL is non-nil, increase section numbers on that level.
2454 (let* ((depth (1- (length reftex-section-numbers))) idx n (string "")
2455 (appendix (get 'reftex-section-numbers 'appendix)))
2456 (when level
2457 (when (and (> level -1) (not star))
2458 (aset reftex-section-numbers
2459 level (1+ (aref reftex-section-numbers level))))
2460 (setq idx (1+ level))
2461 (when (not star)
2462 (while (<= idx depth)
2463 (aset reftex-section-numbers idx 0)
2464 (incf idx))))
2465 (setq idx 0)
2466 (while (<= idx depth)
2467 (setq n (aref reftex-section-numbers idx))
2468 (setq string (concat string (if (not (string= string "")) "." "")
2469 (int-to-string n)))
2470 (incf idx))
2471 (save-match-data
2472 (if (string-match "\\`\\([@0]\\.\\)+" string)
2473 (setq string (replace-match "" nil nil string)))
2474 (if (string-match "\\(\\.0\\)+\\'" string)
2475 (setq string (replace-match "" nil nil string)))
2476 (if (and appendix
2477 (string-match "\\`[0-9]+" string))
2478 (setq string
2479 (concat
2480 (char-to-string
2481 (1- (+ ?A (string-to-int (match-string 0 string)))))
2482 (substring string (match-end 0))))))
2483 (if star
2484 (concat (make-string (1- (length string)) ?\ ) "*")
2485 string)))
2486
2487 (defun reftex-is-multi ()
2488 ;; Tell if this is a multifile document. When not sure, say yes.
2489 (let ((entry (assq 'is-multi (symbol-value reftex-docstruct-symbol))))
2490 (if entry
2491 (nth 1 entry)
2492 t)))
2493
2494 (defun reftex-typekey-check (typekey conf-variable &optional n)
2495 ;; Check if CONF-VARIABLE is true or contains TYPEKEY
2496 (and n (setq conf-variable (nth n conf-variable)))
2497 (or (eq conf-variable t)
2498 (and (stringp conf-variable)
2499 (string-match (concat "[" conf-variable "]") typekey))))
2500
2501 (defun reftex-all-document-files (&optional relative)
2502 "Return a list of all files belonging to the current document.
2503 When RELATIVE is non-nil, give file names relative to directory
2504 of master file."
2505 (let* ((all (symbol-value reftex-docstruct-symbol))
2506 (master-dir (file-name-directory (reftex-TeX-master-file)))
2507 (re (concat "\\`" (regexp-quote master-dir)))
2508 file-list tmp file)
2509 (while (setq tmp (assoc 'bof all))
2510 (setq file (nth 1 tmp)
2511 all (cdr (memq tmp all)))
2512 (and relative
2513 (string-match re file)
2514 (setq file (substring file (match-end 0))))
2515 (push file file-list))
2516 (nreverse file-list)))
2517
2518 ;;; Creating labels ---------------------------------------------------------
2519
2520 (defun reftex-label (&optional environment no-insert)
2521 "Insert a unique label. Return the label.
2522 If ENVIRONMENT is given, don't bother to find out yourself.
2523 If NO-INSERT is non-nil, do not insert label into buffer.
2524 With prefix arg, force to rescan document first.
2525 When you are prompted to enter or confirm a label, and you reply with
2526 just the prefix or an empty string, no label at all will be inserted.
2527 A new label is also recorded into the label list.
2528 This function is controlled by the settings of reftex-insert-label-flags."
2529
2530 (interactive)
2531
2532 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4).
2533 (reftex-access-scan-info current-prefix-arg)
2534
2535 ;; Find out what kind of environment this is and abort if necessary.
2536 (if (or (not environment)
2537 (not (assoc environment reftex-env-or-mac-alist)))
2538 (setq environment (reftex-label-location)))
2539 (unless environment
2540 (error "Can't figure out what kind of label should be inserted"))
2541
2542 ;; Ok, go ahead.
2543 (catch 'exit
2544 (let* ((entry (assoc environment reftex-env-or-mac-alist))
2545 (typekey (nth 1 entry))
2546 (format (nth 3 entry))
2547 (macro-cell (reftex-what-macro 1))
2548 (entry1 (assoc (car macro-cell) reftex-env-or-mac-alist))
2549 label naked prefix valid default force-prompt rescan-is-useful)
2550 (when (and (or (nth 5 entry) (nth 5 entry1))
2551 (memq (preceding-char) '(?\[ ?\{)))
2552 ;; This is an argument of a label macro. Insert naked label.
2553 (setq naked t format "%s"))
2554
2555 (setq prefix (or (cdr (assoc typekey reftex-typekey-to-prefix-alist))
2556 (concat typekey "-")))
2557 ;; Replace any escapes in the prefix
2558 (setq prefix (reftex-replace-prefix-escapes prefix))
2559
2560 ;; Make a default label.
2561 (cond
2562
2563 ((reftex-typekey-check typekey (nth 0 reftex-insert-label-flags))
2564 ;; Derive a label from context.
2565 (setq reftex-active-toc (reftex-last-assoc-before-elt
2566 'toc (car (reftex-where-am-I))
2567 (symbol-value reftex-docstruct-symbol)))
2568 (setq default (reftex-no-props
2569 (nth 2 (reftex-label-info " " nil nil t))))
2570 ;; Catch the cases where the is actually no context available.
2571 (if (or (string-match "NO MATCH FOR CONTEXT REGEXP" default)
2572 (string-match "ILLEGAL VALUE OF PARSE" default)
2573 (string-match "SECTION HEADING NOT FOUND" default)
2574 (string-match "HOOK ERROR" default)
2575 (string-match "^[ \t]*$" default))
2576 (setq default prefix
2577 force-prompt t) ; need to prompt
2578 (setq default
2579 (concat prefix
2580 (funcall reftex-string-to-label-function default)))
2581
2582 ;; Make it unique.
2583 (setq default (reftex-uniquify-label default nil "-"))))
2584
2585 ((reftex-typekey-check typekey (nth 1 reftex-insert-label-flags))
2586 ;; Minimal default: the user will be prompted.
2587 (setq default prefix))
2588
2589 (t
2590 ;; Make an automatic label.
2591 (setq default (reftex-uniquify-label prefix t))))
2592
2593 ;; Should we ask the user?
2594 (if (or (reftex-typekey-check typekey
2595 (nth 1 reftex-insert-label-flags)) ; prompt
2596 force-prompt)
2597
2598 (while (not valid)
2599 ;; iterate until we get a legal label
2600
2601 (setq label (read-string
2602 (if naked "Naked Label: " "Label: ")
2603 default))
2604
2605 ;; Lets make sure that this is a legal label
2606 (cond
2607
2608 ((string-match (concat "\\`\\(" (regexp-quote prefix)
2609 "\\)?[ \t]*\\'")
2610 label)
2611 ;; No label at all, please
2612 (message "No label inserted.")
2613 (throw 'exit nil))
2614
2615 ;; Test if label contains strange characters
2616 ((string-match reftex-label-illegal-re label)
2617 (message "Label \"%s\" contains illegal characters" label)
2618 (ding)
2619 (sit-for 2))
2620
2621 ;; Look it up in the label list
2622 ((setq entry (assoc label
2623 (symbol-value reftex-docstruct-symbol)))
2624 (ding)
2625 (if (y-or-n-p
2626 (format "Label '%s' exists. Use anyway? " label))
2627 (setq valid t)))
2628
2629 ;; Label is ok
2630 (t
2631 (setq valid t))))
2632 (setq label default))
2633
2634 ;; Insert the label into the label list
2635 (let* ((here-I-am-info
2636 (save-excursion
2637 (if (and (or naked no-insert)
2638 (integerp (cdr macro-cell)))
2639 (goto-char (cdr macro-cell)))
2640 (reftex-where-am-I)))
2641 (here-I-am (car here-I-am-info))
2642 (note (if (cdr here-I-am-info)
2643 ""
2644 "POSITION UNCERTAIN. RESCAN TO FIX."))
2645 (file (buffer-file-name))
2646 (text nil)
2647 (tail (memq here-I-am (symbol-value reftex-docstruct-symbol))))
2648
2649 (or (cdr here-I-am-info) (setq rescan-is-useful t))
2650
2651 (when tail
2652 (push (list label typekey text file nil note) (cdr tail))
2653 (put reftex-docstruct-symbol 'modified t)))
2654
2655 ;; Insert the label into the buffer
2656 (unless no-insert
2657 (insert
2658 (if reftex-format-label-function
2659 (funcall reftex-format-label-function label format)
2660 (format format label)))
2661 (if (and reftex-plug-into-AUCTeX
2662 (fboundp 'LaTeX-add-labels))
2663 ;; Tell AUCTeX about this
2664 (LaTeX-add-labels label)))
2665
2666 ;; Delete the corresponding selection buffers to force update on next use.
2667 (when reftex-auto-update-selection-buffers
2668 (reftex-erase-buffer (reftex-make-selection-buffer-name typekey))
2669 (reftex-erase-buffer (reftex-make-selection-buffer-name " ")))
2670
2671 (when (and rescan-is-useful reftex-allow-automatic-rescan)
2672 (reftex-parse-one))
2673
2674 ;; return value of the function is the label
2675 label)))
2676
2677 (defun reftex-string-to-label (string)
2678 "Convert a string (a sentence) to a label.
2679 Uses `reftex-derive-label-parameters' and `reftex-label-illegal-re'. It
2680 also applies `reftex-translate-to-ascii-function' to the string."
2681 (when (and reftex-translate-to-ascii-function
2682 (fboundp reftex-translate-to-ascii-function))
2683 (setq string (funcall reftex-translate-to-ascii-function string)))
2684 (apply 'reftex-convert-string string
2685 "[-~ \t\n\r,;]+" reftex-label-illegal-re nil nil
2686 reftex-derive-label-parameters))
2687
2688 (defun reftex-abbreviate-title (string)
2689 (reftex-convert-string string "[-~ \t\n\r,;]" nil t t
2690 5 40 nil 1 " " (nth 5 reftex-derive-label-parameters)))
2691
2692 (defun reftex-convert-string (string split-re illegal-re dot keep-fp
2693 nwords maxchar illegal abbrev sep
2694 ignore-words &optional downcase)
2695 "Convert a string (a sentence) to something shorter.
2696 SPLIT-RE is the regular expression used to split the string into words.
2697 ILLEGAL-RE matches characters which are illegal in the final string.
2698 DOT t means add dots to abbreviated words.
2699 KEEP-FP t means to keep a final punctuation when applicable.
2700 NWORDS Number of words to use.
2701 MAXCHAR Maximum number of characters in the final string.
2702 ILLEGAL nil: Throw away any words containing stuff matched with ILLEGAL-RE.
2703 t: Throw away only the matched part, not the whole word.
2704 ABBREV nil: Never abbreviate words.
2705 t: Always abbreviate words (see `reftex-abbrev-parameters').
2706 not t and not nil: Abbreviate words if necessary to shorten
2707 string below MAXCHAR.
2708 SEP String separating different words in the output string.
2709 IGNORE-WORDS List of words which should be removed from the string."
2710
2711 (let* ((words0 (split-string string (or split-re "[ \t\n\r]")))
2712 (reftex-label-illegal-re (or illegal-re "\000"))
2713 (abbrev-re (concat
2714 "\\`\\("
2715 (make-string (nth 0 reftex-abbrev-parameters) ?.)
2716 "[" (nth 2 reftex-abbrev-parameters) "]*"
2717 "\\)"
2718 "[" (nth 3 reftex-abbrev-parameters) "]"
2719 (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
2720 words word)
2721
2722 ;; Remove words from the ignore list or with funny characters
2723 (while (setq word (pop words0))
2724 (if downcase (setq word (downcase word)))
2725 (cond
2726 ((member (downcase word) ignore-words))
2727 ((string-match reftex-label-illegal-re word)
2728 (when illegal
2729 (while (string-match reftex-label-illegal-re word)
2730 (setq word (replace-match "" nil nil word)))
2731 (push word words)))
2732 (t
2733 (push word words))))
2734 (setq words (nreverse words))
2735
2736 ;; Restrict number of words
2737 (if (> (length words) nwords)
2738 (setcdr (nthcdr (1- nwords) words) nil))
2739
2740 ;; First, try to use all words
2741 (setq string (mapconcat 'identity words sep))
2742
2743 ;; Abbreviate words if enforced by user settings or string length
2744 (if (or (eq t abbrev)
2745 (and abbrev
2746 (> (length string) maxchar)))
2747 (setq words
2748 (mapcar
2749 (function
2750 (lambda (w) (if (string-match abbrev-re w)
2751 (if dot
2752 (concat (match-string 1 w) ".")
2753 (match-string 1 w))
2754 w)))
2755 words)
2756 string (mapconcat 'identity words sep)))
2757
2758 ;; Shorten if still to long
2759 (setq string
2760 (if (> (length string) maxchar)
2761 (substring string 0 maxchar)
2762 string))
2763
2764 ;; Delete the final punctuation, if any
2765 (if (and (not keep-fp) (string-match "\\s.+\\'" string))
2766 (setq string (replace-match "" nil nil string)))
2767 string))
2768
2769 (defun reftex-latin1-to-ascii (string)
2770 ;; Translate the upper 127 chars in the ISO1 charset to ASCII equivalents
2771 (let ((tab "@@@@@@@@@@@@@@@@@@'@@@@@@@@@@@@@ icLxY|S\"ca<--R-o|23'uq..1o>423?AAAAAAACEEEEIIIIDNOOOOOXOUUUUYP3aaaaaaaceeeeiiiidnooooo:ouuuuypy") c)
2772 (loop for i from 0 to (1- (length string)) do
2773 (setq c (aref string i))
2774 (cond ((and (> c 127) (< c 256)) ; 8 bit Latin-1
2775 (aset string i (aref tab (- c 128))))
2776 ((and (> c 2175) (< c 2304)) ; Mule Latin-1,
2777 (aset string i (aref tab (- c 2176)))))) ; Std. Emacs only
2778 string))
2779
2780 (defun reftex-replace-prefix-escapes (prefix)
2781 ;; Replace %escapes in a label prefix
2782 (save-match-data
2783 (let (letter (num 0) replace)
2784 (while (string-match "\\%\\([a-zA-Z]\\)" prefix num)
2785 (setq letter (match-string 1 prefix))
2786 (setq replace
2787 (cond
2788 ((equal letter "f")
2789 (file-name-sans-extension
2790 (file-name-nondirectory (buffer-file-name))))
2791 ((equal letter "F")
2792 (let ((masterdir (file-name-directory (reftex-TeX-master-file)))
2793 (file (file-name-sans-extension (buffer-file-name))))
2794 (if (string-match (concat "\\`" (regexp-quote masterdir))
2795 file)
2796 (substring file (length masterdir))
2797 file)))
2798 ((equal letter "u")
2799 (or (user-login-name) ""))
2800 (t "")))
2801 (setq num (1- (+ (match-beginning 1) (length replace)))
2802 prefix (replace-match replace nil nil prefix)))
2803 prefix)))
2804
2805 (defun reftex-uniquify-label (label &optional force separator)
2806 ;; Make label unique by appending a number.
2807 ;; Optional FORCE means, force appending a number, even if label is unique.
2808 ;; Optional SEPARATOR is a string to stick between label and number.
2809
2810 ;; Ensure access to scanning info
2811 (reftex-access-scan-info)
2812
2813 (cond
2814 ((and (not force)
2815 (not (assoc label (symbol-value reftex-docstruct-symbol))))
2816 label)
2817 (t
2818 (let* ((label-numbers (assq 'label-numbers
2819 (symbol-value reftex-docstruct-symbol)))
2820 (label-numbers-alist (cdr label-numbers))
2821 (cell (or (assoc label label-numbers-alist)
2822 (car (setcdr label-numbers
2823 (cons (cons label 0)
2824 label-numbers-alist)))))
2825 (num (1+ (cdr cell)))
2826 (sep (or separator "")))
2827 (while (assoc (concat label sep (int-to-string num))
2828 (symbol-value reftex-docstruct-symbol))
2829 (incf num))
2830 (setcdr cell num)
2831 (concat label sep (int-to-string num))))))
2832
2833 ;;; Referencing labels ------------------------------------------------------
2834
2835 ;; Help string for the reference label menu
2836 (defconst reftex-select-label-prompt
2837 "Select: [n]ext [p]revious [r]escan [ ]context e[x]tern [q]uit RET [?]HELP+more")
2838
2839 (defconst reftex-select-label-help
2840 " n / p Go to next/previous label (Cursor motion works as well)
2841 C-c C-n/p Go to next/previous section heading.
2842 b / l Jump back to previous selection / Reuse last referenced label
2843 C-s / C-r Search forward/backward. Use repeated C-s/C-r as in isearch.
2844 g / s Update menu / Switch label type
2845 r / R Reparse document / Reparse entire document
2846 x Switch to label menu of external document (with LaTeX package `xr')
2847 t i c # % Toggle: [i]ncl. file borders, [t]able of contents, [c]ontext
2848 [#] label counters, [%] labels in comments
2849 SPC / f Show full context in other window / Toggle follow mode
2850 v / . Toggle \\ref <-> \\vref / Show insertion point in other window
2851 TAB Enter a label with completion
2852 q / RET Quit without referencing / Accept current label (also on mouse-2)")
2853
2854 (defvar reftex-select-label-map nil
2855 "Keymap used for *RefTeX Select* buffer, when selecting a label.
2856 This keymap can be used to configure the label selection process which is
2857 started with the command \\[reftex-reference].")
2858
2859 (defun reftex-select-label-mode ()
2860 "Major mode for selecting a label in a LaTeX document.
2861 This buffer was created with RefTeX.
2862 It only has a meaningful keymap when you are in the middle of a
2863 selection process.
2864 To select a label, move the cursor to it and press RET.
2865 Press `?' for a summary of important key bindings.
2866
2867 During a selection process, these are the local bindings.
2868
2869 \\{reftex-select-label-map}"
2870
2871 (interactive)
2872 (kill-all-local-variables)
2873 (make-local-hook 'pre-command-hook)
2874 (make-local-hook 'post-command-hook)
2875 (setq major-mode 'reftex-select-label-mode
2876 mode-name "RefTeX Select Label")
2877 (when (syntax-table-p reftex-latex-syntax-table)
2878 (set-syntax-table reftex-latex-syntax-table))
2879 ;; We do not set a local map - reftex-select-item does this.
2880 (run-hooks 'reftex-select-label-mode-hook))
2881
2882 (defun reftex-reference (&optional type no-insert cut)
2883 "Make a LaTeX reference. Look only for labels of a certain TYPE.
2884 With prefix arg, force to rescan buffer for labels. This should only be
2885 necessary if you have recently entered labels yourself without using
2886 reftex-label. Rescanning of the buffer can also be requested from the
2887 label selection menu.
2888 The function returns the selected label or nil.
2889 If NO-INSERT is non-nil, do not insert \\ref command, just return label.
2890 When called with 2 C-u prefix args, disable magic word recognition."
2891
2892 (interactive)
2893
2894 ;; check for active recursive edits
2895 (reftex-check-recursive-edit)
2896
2897 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
2898 (reftex-access-scan-info current-prefix-arg)
2899
2900 (unless type
2901 ;; guess type from context
2902 (if (and reftex-guess-label-type
2903 (setq type (reftex-guess-label-type)))
2904 (setq cut (cdr type)
2905 type (car type))
2906 (setq type (reftex-query-label-type))))
2907
2908 (let* ((varioref (if (reftex-typekey-check
2909 type reftex-vref-is-default)
2910 "\\vref" "\\ref"))
2911 (form "\\ref{%s}")
2912 label pair)
2913
2914 ;; Have the user select a label
2915 (set-marker reftex-select-return-marker (point))
2916 (setq pair (save-excursion
2917 (reftex-offer-label-menu type)))
2918 (reftex-ensure-compiled-variables)
2919 (set-marker reftex-select-return-marker nil)
2920 (setq label (car pair)
2921 type (cdr pair)
2922 form (or (cdr (assoc type reftex-typekey-to-format-alist))
2923 form))
2924
2925 (if (and label
2926 (not no-insert))
2927 (progn
2928 (if cut (backward-delete-char cut))
2929
2930 ;; remove ~ if we do already have a space
2931 (when (and (= ?~ (string-to-char form))
2932 (member (preceding-char) '(?\ ?\t ?\n)))
2933 (setq form (substring form 1)))
2934 ;; do we need to switch from \ref to \vref?
2935 (when (string= varioref "\\vref")
2936 (while (string-match "\\\\ref{" form)
2937 (setq form (replace-match "\\vref{" t t form))))
2938 ;; ok, insert the reference
2939 (insert
2940 (if reftex-format-ref-function
2941 (funcall reftex-format-ref-function label form)
2942 (format form label label)))
2943 (message ""))
2944 (message "Quit"))
2945 ;; return the label
2946 label))
2947
2948 (defun reftex-guess-label-type ()
2949 ;; Examine context to guess what a \ref might want to reference.
2950 (let ((words reftex-words-to-typekey-alist)
2951 (case-fold-search t)
2952 (bound (max (point-min) (- (point) 35)))
2953 matched cell)
2954 (save-excursion
2955 (while (and (setq cell (pop words))
2956 (not (setq matched
2957 (re-search-backward (car cell) bound t))))))
2958 (if matched
2959 (cons (cdr cell) (- (match-end 0) (match-end 1)))
2960 nil)))
2961
2962 (defun reftex-offer-label-menu (typekey)
2963 ;; Offer a menu with the appropriate labels. Return (label . typekey).
2964 (let* ((buf (current-buffer))
2965 (xr-data (assq 'xr (symbol-value reftex-docstruct-symbol)))
2966 (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
2967 (xr-index 0)
2968 (here-I-am (car (reftex-where-am-I)))
2969 (here-I-am1 here-I-am)
2970 (toc (reftex-typekey-check typekey reftex-label-menu-flags 0))
2971 (files (reftex-typekey-check typekey reftex-label-menu-flags 7))
2972 (context (not (reftex-typekey-check
2973 typekey reftex-label-menu-flags 3)))
2974 (counter (reftex-typekey-check
2975 typekey reftex-label-menu-flags 2))
2976 (follow (reftex-typekey-check
2977 typekey reftex-label-menu-flags 4))
2978 (commented (nth 5 reftex-label-menu-flags))
2979 (prefix "")
2980 selection-buffers
2981 offset rtn key data last-data entry)
2982
2983 (setq entry (cons nil nil))
2984
2985 (unwind-protect
2986 (catch 'exit
2987 (while t
2988 (save-window-excursion
2989 (delete-other-windows)
2990 (setq reftex-call-back-to-this-buffer buf
2991 reftex-latex-syntax-table (syntax-table))
2992 (let ((default-major-mode 'reftex-select-label-mode))
2993 (if reftex-use-multiple-selection-buffers
2994 (switch-to-buffer-other-window
2995 (save-excursion
2996 (set-buffer buf)
2997 (reftex-make-selection-buffer-name typekey)))
2998 (switch-to-buffer-other-window "*RefTeX Select*")
2999 (reftex-erase-buffer)))
3000 (unless (eq major-mode 'reftex-select-label-mode)
3001 (reftex-select-label-mode))
3002 (add-to-list 'selection-buffers (current-buffer))
3003 (setq truncate-lines t)
3004 (setq mode-line-format
3005 (list "---- " 'mode-line-buffer-identification
3006 " " 'varioref
3007 " " (abbreviate-file-name
3008 (buffer-file-name buf))
3009 " -%-"))
3010 (cond
3011 ((= 0 (buffer-size))
3012 (let ((buffer-read-only nil))
3013 (setq offset (reftex-make-and-insert-label-list
3014 typekey buf toc files context counter commented
3015 (or here-I-am offset) prefix))))
3016 (here-I-am
3017 (setq offset (reftex-get-offset buf here-I-am typekey)))
3018 (t (setq offset t)))
3019 (setq buffer-read-only t)
3020 (setq offset (or offset t))
3021
3022 (setq here-I-am nil) ; turn off determination of offset
3023 (setq rtn
3024 (reftex-select-item
3025 reftex-select-label-prompt
3026 reftex-select-label-help
3027 reftex-select-label-map
3028 offset
3029 'reftex-select-label-callback follow))
3030 (setq key (car rtn)
3031 data (nth 1 rtn)
3032 last-data (nth 2 rtn)
3033 offset t)
3034 (unless key (throw 'exit nil))
3035 (cond
3036 ((eq key ?g)
3037 ;; update buffer
3038 (reftex-erase-buffer))
3039 ((or (eq key ?r)
3040 (eq key ?R))
3041 ;; rescan buffer
3042 (reftex-erase-buffer)
3043 (reftex-reparse-document buf last-data key))
3044 ((eq key ?c)
3045 ;; toggle context mode
3046 (reftex-erase-buffer)
3047 (setq context (not context)))
3048 ((eq key ?s)
3049 ;; switch type
3050 (setq here-I-am here-I-am1)
3051 (setq typekey (reftex-query-label-type)))
3052 ((eq key ?t)
3053 ;; toggle table of contents display
3054 (reftex-erase-buffer)
3055 (setq toc (not toc)))
3056 ((eq key ?i)
3057 ;; toggle display of included file borders
3058 (reftex-erase-buffer)
3059 (setq files (not files)))
3060 ((eq key ?#)
3061 ;; toggle counter display
3062 (reftex-erase-buffer)
3063 (setq counter (not counter)))
3064 ((eq key ?%)
3065 ;; toggle display of commented labels
3066 (reftex-erase-buffer)
3067 (setq commented (not commented)))
3068 ((eq key ?l)
3069 ;; reuse the last referenced label again
3070 (setq entry reftex-last-used-reference)
3071 (throw 'exit t))
3072 ((eq key ?x)
3073 ;; select an external document
3074 (setq xr-index (reftex-select-external-document
3075 xr-alist xr-index))
3076 (setq buf (or (reftex-get-file-buffer-force
3077 (cdr (nth xr-index xr-alist)))
3078 (error "Cannot switch document"))
3079 prefix (or (car (nth xr-index xr-alist)) ""))
3080 (set-buffer buf)
3081 (reftex-access-scan-info))
3082 ((stringp key)
3083 (setq entry
3084 (or (assoc key (symbol-value reftex-docstruct-symbol))
3085 (list key typekey)))
3086 (throw 'exit t))
3087 (t
3088 (set-buffer buf)
3089 (if data
3090 (progn
3091 (setq entry data)
3092 (setq reftex-last-used-reference entry))
3093 (setq entry nil))
3094 (throw 'exit t))))))
3095 (save-excursion
3096 (while reftex-buffers-with-changed-invisibility
3097 (set-buffer (car (car reftex-buffers-with-changed-invisibility)))
3098 (setq buffer-invisibility-spec
3099 (cdr (pop reftex-buffers-with-changed-invisibility)))))
3100 (mapcar (function (lambda (buf)
3101 (and (buffer-live-p buf)
3102 (bury-buffer buf))))
3103 selection-buffers)
3104 (reftex-kill-temporary-buffers))
3105 (cons (if (nth 0 entry) (concat prefix (nth 0 entry)) nil)
3106 (nth 1 entry))))
3107
3108 (defun reftex-select-external-document (xr-alist xr-index)
3109 ;; Return index of an external document.
3110 (let* ((len (length xr-alist)) (highest (1- (+ ?0 len)))
3111 (prompt (format "[%c-%c] Select TAB: Read prefix with completion"
3112 ?0 highest))
3113 key prefix)
3114 (cond
3115 ((= len 1)
3116 (message "No external documents available")
3117 (ding) (sit-for 1) 0)
3118 ((= len 2)
3119 (- 1 xr-index))
3120 (t
3121 (save-excursion
3122 (let* ((length (apply 'max (mapcar
3123 (lambda(x) (length (car x))) xr-alist)))
3124 (fmt (format " [%%c] %%-%ds %%s\n" length))
3125 (n (1- ?0)))
3126 (setq key
3127 (reftex-select-with-char
3128 prompt
3129 (concat
3130 "SELECT EXTERNAL DOCUMENT\n------------------------\n"
3131 (mapconcat
3132 (function
3133 (lambda (x)
3134 (format fmt (incf n) (or (car x) "")
3135 (abbreviate-file-name (cdr x)))))
3136 xr-alist ""))
3137 nil t))
3138 (cond
3139 ((and (>= key ?0) (<= key highest)) (- key ?0))
3140 ((= key ?\C-i)
3141 (setq prefix (completing-read "Prefix: " xr-alist nil t))
3142 (- len (length (memq (assoc prefix xr-alist) xr-alist))))
3143 (t (error "Illegal document selection [%c]" key)))))))))
3144
3145 (defun reftex-reparse-document (&optional buffer data key)
3146 ;; Rescan the document.
3147 (save-window-excursion
3148 (save-excursion
3149 (if buffer
3150 (if (not (bufferp buffer))
3151 (error "No such buffer %s" (buffer-name buffer))
3152 (set-buffer buffer)))
3153 (let ((arg (if (eq key ?R) '(16) '(4)))
3154 (file (nth 3 data)))
3155 (reftex-access-scan-info arg file)))))
3156
3157 (defun reftex-make-selection-buffer-name (type &optional index)
3158 ;; Make unique name for a selection buffer.
3159 (format " *RefTeX[%s][%d]*"
3160 type (or index (get reftex-docstruct-symbol ':master-index) 0)))
3161
3162 (defun reftex-get-offset (buf here-am-I typekey)
3163 ;; Find the correct offset data, like make-and-insert would, but faster.
3164 (save-excursion
3165 (set-buffer buf)
3166 (reftex-access-scan-info)
3167 (let* ((rest (memq here-am-I (symbol-value reftex-docstruct-symbol)))
3168 entry)
3169 (while (and (setq entry (pop rest))
3170 (not (and (stringp (car entry))
3171 (equal typekey (nth 1 entry))))))
3172 entry)))
3173
3174 (defun reftex-make-and-insert-label-list
3175 (typekey0 buf toc files context counter show-commented here-I-am xr-prefix)
3176 ;; Insert a menu of all labels in buffer BUF into current buffer.
3177 ;; Return the data property of the entry corresponding to HERE-I-AM.
3178 (let* ((font (reftex-use-fonts))
3179 (cnt 0)
3180 (index -1)
3181 (toc-indent " ")
3182 (label-indent
3183 (concat "> "
3184 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
3185 (context-indent
3186 (concat ". "
3187 (if toc (make-string (* 7 reftex-level-indent) ?\ ) "")))
3188 (mouse-face
3189 (if (memq reftex-highlight-selection '(mouse both))
3190 reftex-mouse-selected-face
3191 nil))
3192 (label-face (reftex-verified-face reftex-label-face
3193 'font-lock-constant-face
3194 'font-lock-reference-face))
3195 all cell text label typekey note comment master-dir-re
3196 offset from to docstruct-symbol)
3197
3198 (message "Creating Selection Buffer...")
3199
3200 ;; Pop to buffer buf to get the correct buffer-local variables
3201 (save-excursion
3202 (set-buffer buf)
3203
3204 ;; Ensure access to scanning info
3205 (reftex-access-scan-info)
3206
3207 (setq docstruct-symbol reftex-docstruct-symbol
3208 all (symbol-value reftex-docstruct-symbol)
3209 reftex-active-toc nil
3210 master-dir-re
3211 (concat "\\`" (regexp-quote
3212 (file-name-directory (reftex-TeX-master-file))))))
3213
3214 (set (make-local-variable 'reftex-docstruct-symbol) docstruct-symbol)
3215 (set (make-local-variable 'reftex-prefix)
3216 (cdr (assoc typekey0 reftex-typekey-to-prefix-alist)))
3217 (if (equal reftex-prefix " ") (setq reftex-prefix nil))
3218
3219 ;; Walk the docstruct and insert the appropriate stuff
3220 (while (setq cell (pop all))
3221
3222 (incf index)
3223 (setq from (point))
3224
3225 (if (eq cell here-I-am) (setq offset 'attention))
3226
3227 (cond
3228
3229 ((memq (car cell) '(bib thebib label-numbers appendix
3230 master-dir bibview-cache is-multi xr xr-doc)))
3231 ;; These are currently ignored
3232
3233 ((memq (car cell) '(bof eof file-error))
3234 ;; Beginning or end of a file
3235 (when files
3236 (insert
3237 " File " (if (string-match master-dir-re (nth 1 cell))
3238 (substring (nth 1 cell) (match-end 0))
3239 (nth 1 cell))
3240 (cond ((eq (car cell) 'bof) " starts here\n")
3241 ((eq (car cell) 'eof) " ends here\n")
3242 ((eq (car cell) 'file-error) " was not found\n")))
3243 (when font
3244 (put-text-property from (point)
3245 'face reftex-file-boundary-face))))
3246
3247 ((eq (car cell) 'toc)
3248 ;; a table of contents entry
3249 (when toc
3250 (setq reftex-active-toc cell)
3251 (insert (concat toc-indent (nth 2 cell) "\n"))
3252 (setq to (point))
3253 (when font
3254 (put-text-property from to
3255 'face reftex-section-heading-face))
3256 (goto-char to)))
3257
3258 ((stringp (car cell))
3259 ;; a label
3260 (when (null (nth 2 cell))
3261 ;; No context yet. Quick update.
3262 (setcdr cell (cdr (reftex-label-info-update cell)))
3263 (put docstruct-symbol 'modified t))
3264
3265 (setq label (car cell)
3266 typekey (nth 1 cell)
3267 text (nth 2 cell)
3268 comment (nth 4 cell)
3269 note (nth 5 cell))
3270
3271 (when (and (or (string= typekey typekey0) (string= typekey0 " "))
3272 (or show-commented (null comment)))
3273
3274 ;; Yes we want this one
3275 (incf cnt)
3276 (if (eq offset 'attention) (setq offset cell))
3277
3278 (setq label (concat xr-prefix label))
3279 (when comment (setq label (concat "% " label)))
3280 (insert label-indent label)
3281 (when font
3282 (setq to (point))
3283 (put-text-property
3284 (- (point) (length label)) to
3285 'face (if comment
3286 'font-lock-comment-face
3287 label-face))
3288 (goto-char to))
3289
3290 (insert (if counter (format " (%d) " cnt) "")
3291 (if comment " LABEL IS COMMENTED OUT " "")
3292 (if (stringp note) (concat " " note) "")
3293 "\n")
3294 (setq to (point))
3295
3296 (when context
3297 (insert context-indent text "\n")
3298 (setq to (point)))
3299 (put-text-property from to ':data cell)
3300 (when mouse-face
3301 (put-text-property from (1- to)
3302 'mouse-face mouse-face))
3303 (goto-char to)))))
3304
3305 (when (reftex-refontify)
3306 (reftex-fontify-select-label-buffer buf))
3307 (run-hooks 'reftex-display-copied-context-hook)
3308 offset))
3309
3310 (defun reftex-query-label-type ()
3311 ;; Ask for label type
3312 (let ((key (reftex-select-with-char
3313 reftex-type-query-prompt reftex-type-query-help 3)))
3314 (unless (member (char-to-string key) reftex-typekey-list)
3315 (error "No such label type: %s" (char-to-string key)))
3316 (char-to-string key)))
3317
3318 (defun reftex-select-label-callback (data forward no-revisit)
3319 ;; Callback function called from the label selection in order to
3320 ;; show context in another window
3321 (let* ((this-window (selected-window))
3322 label file buffer re found)
3323 ;; pop to original buffer in order to get correct variables
3324 (catch 'exit
3325 (setq label (nth 0 data)
3326 file (nth 3 data))
3327
3328 ;; goto the file in another window
3329 (setq buffer
3330 (if no-revisit
3331 (reftex-get-buffer-visiting file)
3332 (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 (message reftex-no-follow-message)
3341 (throw 'exit nil))
3342
3343 ;; search for that label
3344 (setq re (format reftex-find-label-regexp-format (regexp-quote label)))
3345 (setq found
3346 (if forward
3347 (re-search-forward re nil t)
3348 (re-search-backward re nil t)))
3349 (unless found
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 (setq reftex-latex-syntax-table (syntax-table))
3357 (reftex-highlight 0 (match-beginning 3) (match-end 3))
3358 (reftex-show-entry (match-beginning 3) (match-end 3))
3359 (recenter '(4)))
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 '(4))
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-show-entry (beg-hlt end-hlt)
3390 ;; Show entry if point is hidden
3391 (let* ((n (/ (window-height) 2))
3392 (beg (save-excursion
3393 (re-search-backward "[\n\r]" nil 1 n) (point)))
3394 (end (save-excursion
3395 (re-search-forward "[\n\r]" nil 1 n) (point))))
3396 (cond
3397 ((and (boundp 'buffer-invisibility-spec) buffer-invisibility-spec
3398 (get-char-property (1+ beg-hlt) 'invisible))
3399 ;; Invisible with text properties. That is easy to change.
3400 (push (cons (current-buffer) buffer-invisibility-spec)
3401 reftex-buffers-with-changed-invisibility)
3402 (setq buffer-invisibility-spec nil))
3403 ((string-match "\r" (buffer-substring beg end))
3404 ;; Invisible with selective display. We need to copy it.
3405 (let ((string (buffer-substring-no-properties beg end)))
3406 (switch-to-buffer "*RefTeX Context Copy*")
3407 (setq buffer-read-only nil)
3408 (erase-buffer)
3409 (insert string)
3410 (subst-char-in-region (point-min) (point-max) ?\r ?\n t)
3411 (goto-char (- beg-hlt beg))
3412 (reftex-highlight 0 (1+ (- beg-hlt beg)) (1+ (- end-hlt beg)))
3413 (if (reftex-refontify)
3414 (when (or (not (eq major-mode 'latex-mode))
3415 (not font-lock-mode))
3416 (latex-mode)
3417 (run-hook-with-args
3418 'reftex-pre-refontification-functions
3419 reftex-call-back-to-this-buffer 'reftex-hidden)
3420 (turn-on-font-lock))
3421 (when (or (not (eq major-mode 'fundamental-mode))
3422 font-lock-mode)
3423 (fundamental-mode)))
3424 (run-hooks 'reftex-display-copied-context-hook)
3425 (setq buffer-read-only t))))))
3426
3427 ;;; =========================================================================
3428 ;;;
3429 ;;; Table of contents
3430
3431 ;; We keep at most one *toc* buffer - it is easy to make them
3432
3433 (defvar reftex-toc-map (make-sparse-keymap)
3434 "Keymap used for *toc* buffer.")
3435
3436 (defun reftex-toc-mode ()
3437 "Major mode for managing Table of Contents for LaTeX files.
3438 This buffer was created with RefTeX.
3439 Press `?' for a summary of important key bindings.
3440
3441 Here are all local bindings.
3442
3443 \\{reftex-toc-map}"
3444 (interactive)
3445 (kill-all-local-variables)
3446 (setq major-mode 'reftex-toc-mode
3447 mode-name "RefTeX Table of Contents")
3448 (use-local-map reftex-toc-map)
3449 (set (make-local-variable 'revert-buffer-function) 'reftex-toc-revert)
3450 (setq truncate-lines t)
3451 (make-local-hook 'post-command-hook)
3452 (make-local-hook 'pre-command-hook)
3453 (make-local-variable 'reftex-last-follow-point)
3454 (add-hook 'post-command-hook 'reftex-toc-post-command-hook nil t)
3455 (add-hook 'pre-command-hook 'reftex-toc-pre-command-hook nil t)
3456 (run-hooks 'reftex-toc-mode-hook))
3457
3458 (defvar reftex-last-toc-master nil
3459 "Stores the name of the tex file that `reftex-toc' was last run on.")
3460
3461 (defvar reftex-last-toc-file nil
3462 "Stores the file name from which `reftex-toc' was called. For redo command.")
3463
3464 (defvar reftex-last-window-height nil)
3465
3466 (defvar reftex-toc-return-marker (make-marker)
3467 "Marker which makes it possible to return from toc to old position.")
3468
3469 (defconst reftex-toc-help
3470 " AVAILABLE KEYS IN TOC BUFFER
3471 ============================
3472 n / p next-line / previous-line
3473 SPC Show the corresponding section of the LaTeX document.
3474 TAB Goto the section.
3475 RET Goto the section and hide the *toc* buffer (also on mouse-2).
3476 q / Q Hide/Kill *toc* buffer, return to position of last reftex-toc command.
3477 f / g Toggle follow mode on and off / Refresh *toc* buffer.
3478 r / R Reparse the LaTeX document / Reparse entire LaTeX document.
3479 . In other window, show position from where `reftex-toc' was called.
3480 x Switch to TOC of external document (with LaTeX package `xr').")
3481
3482 (defun reftex-toc ()
3483 "Show the table of contents for the current document.
3484 When called with a raw C-u prefix, rescan the document first."
3485
3486 (interactive)
3487
3488 (if (or (not (string= reftex-last-toc-master (reftex-TeX-master-file)))
3489 current-prefix-arg)
3490 (reftex-erase-buffer "*toc*"))
3491
3492 (setq reftex-last-toc-file (buffer-file-name))
3493 (setq reftex-last-toc-master (reftex-TeX-master-file))
3494
3495 (set-marker reftex-toc-return-marker (point))
3496
3497 ;; If follow mode is active, arrange to delay it one command
3498 (if reftex-toc-follow-mode
3499 (setq reftex-toc-follow-mode 1))
3500
3501 ;; Ensure access to scanning info and rescan buffer if prefix are is '(4)
3502 (reftex-access-scan-info current-prefix-arg)
3503
3504 (let* ((all (symbol-value reftex-docstruct-symbol))
3505 (xr-data (assq 'xr all))
3506 (xr-alist (cons (cons "" (buffer-file-name)) (nth 1 xr-data)))
3507 (where (reftex-nearest-section))
3508 (mouse-face
3509 (if (memq reftex-highlight-selection '(mouse both))
3510 reftex-mouse-selected-face
3511 nil))
3512 (fontify (reftex-use-fonts))
3513 toc1 cell startpos)
3514
3515 (if (get-buffer-window "*toc*")
3516 (select-window (get-buffer-window "*toc*"))
3517 (when (< (window-height) (* 2 window-min-height))
3518 (delete-other-windows))
3519 (setq reftex-last-window-height (window-height)) ; remember
3520 (split-window)
3521 (let ((default-major-mode 'reftex-toc-mode))
3522 (switch-to-buffer "*toc*")))
3523
3524 (or (eq major-mode 'reftex-toc-mode) (reftex-toc-mode))
3525
3526 (cond
3527 ;; buffer is empty - fill it with the table of contents
3528 ((= (buffer-size) 0)
3529 (message "Building *toc* buffer...")
3530
3531 (setq buffer-read-only nil)
3532 (insert (format
3533 "TABLE-OF-CONTENTS on %s
3534 SPC=view TAB=goto RET=goto+hide [q]uit [r]escan [f]ollow-mode e[x]tern [?]Help
3535 -------------------------------------------------------------------------------
3536 " (abbreviate-file-name reftex-last-toc-master)))
3537 (setq startpos (point))
3538
3539 (if (reftex-use-fonts)
3540 (put-text-property 1 (point) 'face reftex-toc-header-face))
3541 (put-text-property 1 (point) 'intangible t)
3542 (put-text-property 1 2 'xr-alist xr-alist)
3543
3544 (while all
3545 (setq cell (car all)
3546 all (cdr all))
3547 (when (eq (car cell) 'toc)
3548 (setq toc1 (concat (nth 2 cell) "\n"))
3549 (put-text-property 0 (length toc1) 'toc cell toc1)
3550 (when fontify
3551 (put-text-property 0 (length toc1)
3552 'face reftex-section-heading-face toc1))
3553 (when mouse-face
3554 (put-text-property 0 (1- (length toc1))
3555 'mouse-face mouse-face toc1))
3556 (insert toc1)))
3557
3558 (backward-delete-char 1)
3559
3560 (run-hooks 'reftex-display-copied-context-hook)
3561 (message "Building *toc* buffer...done.")
3562 (setq buffer-read-only t))
3563 (t
3564 (goto-line 3)
3565 (beginning-of-line)
3566 (setq startpos (point))))
3567
3568 ;; Find the correct section
3569 (goto-char (point-max))
3570 (beginning-of-line)
3571 (while (and (> (point) startpos)
3572 (not (eq (get-text-property (point) 'toc) where)))
3573 (beginning-of-line 0))
3574 (setq reftex-last-follow-point (point))))
3575
3576 (defun reftex-nearest-section ()
3577 ;; Return (file . find) of nearest section command
3578 (let* ((here-I-am (car (reftex-where-am-I))))
3579 (reftex-last-assoc-before-elt
3580 'toc here-I-am (symbol-value reftex-docstruct-symbol))))
3581
3582 (defun reftex-toc-pre-command-hook ()
3583 ;; used as pre command hook in *toc* buffer
3584 (reftex-unhighlight 0)
3585 (reftex-unhighlight 1))
3586
3587 (defun reftex-toc-post-command-hook ()
3588 ;; used in the post-command-hook for the *toc* buffer
3589 (and (> (point) 1)
3590 (memq reftex-highlight-selection '(cursor both))
3591 (save-excursion
3592 (reftex-highlight 1
3593 (progn (beginning-of-line) (point))
3594 (progn (end-of-line) (point)))))
3595 (cond
3596 ((integerp reftex-toc-follow-mode)
3597 ;; remove delayed action
3598 (setq reftex-toc-follow-mode t))
3599 ((and reftex-toc-follow-mode
3600 (not (equal reftex-last-follow-point (point))))
3601 ;; show context in other window
3602 (setq reftex-last-follow-point (point))
3603 (condition-case nil
3604 (reftex-toc-visit-line nil (not reftex-revisit-to-follow))
3605 (error t)))))
3606
3607 (defun reftex-re-enlarge ()
3608 ;; Enlarge windiw to a remembered size
3609 (enlarge-window
3610 (max 0 (- (or reftex-last-window-height (window-height))
3611 (window-height)))))
3612
3613 (defun reftex-toc-show-help ()
3614 "Show a summary of special key bindings."
3615 (interactive)
3616 (with-output-to-temp-buffer "*RefTeX Help*"
3617 (princ reftex-toc-help))
3618 ;; If follow mode is active, arrange to delay it one command
3619 (if reftex-toc-follow-mode
3620 (setq reftex-toc-follow-mode 1)))
3621
3622 (defun reftex-toc-toggle-follow ()
3623 "Toggle toc-follow mode. (It is not really a mode, just a flag)."
3624 (interactive)
3625 (setq reftex-last-follow-point -1)
3626 (setq reftex-toc-follow-mode (not reftex-toc-follow-mode)))
3627 (defun reftex-toc-view-line ()
3628 "View document location in other window."
3629 (interactive)
3630 (reftex-toc-visit-line))
3631 (defun reftex-toc-mouse-view-line (ev)
3632 "View document location in other window."
3633 (interactive "e")
3634 (mouse-set-point ev)
3635 (reftex-toc-visit-line))
3636 (defun reftex-toc-goto-line-and-hide ()
3637 "Go to document location in other window. Hide the *toc* window."
3638 (interactive)
3639 (reftex-toc-visit-line 'hide))
3640 (defun reftex-toc-goto-line ()
3641 "Go to document location in other window. Hide the *toc* window."
3642 (interactive)
3643 (reftex-toc-visit-line t))
3644 (defun reftex-toc-mouse-goto-line-and-hide (ev)
3645 "Go to document location in other window. Hide the *toc* window."
3646 (interactive "e")
3647 (mouse-set-point ev)
3648 (reftex-toc-visit-line 'hide))
3649 (defun reftex-toc-show-insertion-point ()
3650 (interactive)
3651 (let ((this-window (selected-window)))
3652 (unwind-protect
3653 (progn
3654 (switch-to-buffer-other-window
3655 (marker-buffer reftex-toc-return-marker))
3656 (goto-char (marker-position reftex-toc-return-marker))
3657 (recenter '(4)))
3658 (select-window this-window))))
3659 (defun reftex-toc-quit ()
3660 "Hide the *toc* window and do not move point."
3661 (interactive)
3662 (or (one-window-p) (delete-window))
3663 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
3664 (reftex-re-enlarge)
3665 (goto-char (or (marker-position reftex-toc-return-marker) (point))))
3666 (defun reftex-toc-quit-and-kill ()
3667 "Kill the *toc* buffer."
3668 (interactive)
3669 (kill-buffer "*toc*")
3670 (or (one-window-p) (delete-window))
3671 (switch-to-buffer (marker-buffer reftex-toc-return-marker))
3672 (reftex-re-enlarge)
3673 (goto-char (marker-position reftex-toc-return-marker)))
3674 (defun reftex-toc-rescan (&rest ignore)
3675 "Regenerate the *toc* buffer by reparsing file of section at point."
3676 (interactive)
3677 (if reftex-enable-partial-scans
3678 (let ((file (nth 3 (get-text-property (point) 'toc))))
3679 (if (not file)
3680 (error "Don't know which file to rescan. Try `R'")
3681 (switch-to-buffer-other-window
3682 (reftex-get-file-buffer-force file))
3683 (setq current-prefix-arg '(4))
3684 (reftex-toc)))
3685 (reftex-toc-Rescan))
3686 (reftex-kill-temporary-buffers))
3687 (defun reftex-toc-Rescan (&rest ignore)
3688 "Regenerate the *toc* buffer by reparsing the entire document."
3689 (interactive)
3690 (switch-to-buffer-other-window
3691 (reftex-get-file-buffer-force reftex-last-toc-file))
3692 (setq current-prefix-arg '(16))
3693 (reftex-toc))
3694 (defun reftex-toc-revert (&rest ignore)
3695 "Regenerate the *toc* from the internal lists."
3696 (interactive)
3697 (switch-to-buffer-other-window
3698 (reftex-get-file-buffer-force reftex-last-toc-file))
3699 (reftex-erase-buffer "*toc*")
3700 (setq current-prefix-arg nil)
3701 (reftex-toc))
3702 (defun reftex-toc-external (&rest ignore)
3703 "Switch to table of contents of an external document."
3704 (interactive)
3705 (let* ((old-buf (current-buffer))
3706 (xr-alist (get-text-property 1 'xr-alist))
3707 (xr-index (reftex-select-external-document
3708 xr-alist 0)))
3709 (switch-to-buffer-other-window (or (reftex-get-file-buffer-force
3710 (cdr (nth xr-index xr-alist)))
3711 (error "Cannot switch document")))
3712 (reftex-toc)
3713 (if (equal old-buf (current-buffer))
3714 (message "")
3715 (message "Switched document"))))
3716
3717 (defun reftex-toc-visit-line (&optional final no-revisit)
3718 ;; Visit the tex file corresponding to the toc entry on the current line.
3719 ;; If FINAL is t, stay there
3720 ;; If FINAL is 'hide, hide the *toc* window.
3721 ;; Otherwise, move cursor back into *toc* window.
3722 ;; This function is pretty clever about finding back a section heading,
3723 ;; even if the buffer is not live, or things like outline, x-symbol etc.
3724 ;; have been active.
3725
3726 (let* ((toc (get-text-property (point) 'toc))
3727 (file (nth 3 toc))
3728 (marker (nth 4 toc))
3729 (level (nth 5 toc))
3730 (literal (nth 7 toc))
3731 (emergency-point (nth 8 toc))
3732 (toc-window (selected-window))
3733 show-window show-buffer match)
3734
3735 (unless toc (error "Don't know which toc line to visit"))
3736
3737 (setq match
3738 (cond
3739 ((and (markerp marker) (marker-buffer marker))
3740 ;; Buffer is still live and we have the marker. Should be easy.
3741 (switch-to-buffer-other-window (marker-buffer marker))
3742 (goto-char (marker-position marker))
3743 (or (looking-at (regexp-quote literal))
3744 (looking-at (reftex-make-regexp-allow-for-ctrl-m literal))
3745 (looking-at (reftex-make-desperate-section-regexp literal))
3746 (looking-at (concat "\\\\"
3747 (regexp-quote
3748 (car (rassq level
3749 reftex-section-levels-all)))
3750 "[[{]"))))
3751 ((or (not no-revisit)
3752 (reftex-get-buffer-visiting file))
3753 ;; Marker is lost. Use the backup method.
3754 (switch-to-buffer-other-window
3755 (reftex-get-file-buffer-force file nil))
3756 (goto-char (or emergency-point (point-min)))
3757 (or (looking-at (regexp-quote literal))
3758 (let ((pos (point)))
3759 (re-search-backward "\\`\\|[\r\n][ \t]*[\r\n]" nil t)
3760 (or (reftex-nearest-match (regexp-quote literal) pos)
3761 (reftex-nearest-match
3762 (reftex-make-regexp-allow-for-ctrl-m literal) pos)
3763 (reftex-nearest-match
3764 (reftex-make-desperate-section-regexp literal) pos)))))
3765 (t (message reftex-no-follow-message) nil)
3766 ))
3767
3768 (setq show-window (selected-window)
3769 show-buffer (current-buffer))
3770
3771 (unless match
3772 (select-window toc-window)
3773 (error "Cannot find line"))
3774
3775 (goto-char (match-beginning 0))
3776 (recenter 1)
3777 (reftex-highlight 0 (match-beginning 0) (match-end 0) (current-buffer))
3778
3779 (select-window toc-window)
3780
3781 ;; use the `final' parameter to decide what to do next
3782 (cond
3783 ((eq final t)
3784 (reftex-unhighlight 0)
3785 (select-window show-window))
3786 ((eq final 'hide)
3787 (reftex-unhighlight 0)
3788 (or (one-window-p) (delete-window))
3789 (switch-to-buffer show-buffer)
3790 (reftex-re-enlarge))
3791 (t nil))))
3792
3793 (defun reftex-make-desperate-section-regexp (old)
3794 ;; Return a regexp which will still match a section statement even if
3795 ;; x-symbol or isotex or the like have been at work in the mean time.
3796 (let* ((n (1+ (string-match "[[{]" old)))
3797 (new (regexp-quote (substring old 0 (1+ (string-match "[[{]" old)))))
3798 (old (substring old n)))
3799 (while (string-match
3800 "\\([\r\n]\\)\\|\\(\\`\\|[ \t\n\r]\\)\\([a-zA-Z0-9]+\\)\\([ \t\n\r]\\|}\\'\\)"
3801 old)
3802 (if (match-beginning 1)
3803 (setq new (concat new "[^\n\r]*[\n\r]"))
3804 (setq new (concat new "[^\n\r]*" (match-string 3 old))))
3805 (setq old (substring old (match-end 0))))
3806 new))
3807
3808 ;;; =========================================================================
3809 ;;;
3810 ;;; BibTeX citations.
3811
3812 ;; Variables and constants
3813
3814 ;; The history list of regular expressions used for citations
3815 (defvar reftex-cite-regexp-hist nil)
3816
3817 ;; Prompt and help string for citation selection
3818 (defconst reftex-citation-prompt
3819 "Select: [n]ext [p]revious [r]estrict [ ]full_entry [q]uit RET [?]Help+more")
3820
3821 (defconst reftex-citation-help
3822 " n / p Go to next/previous entry (Cursor motion works as well).
3823 C-s / C-r Search forward/backward. Use repeated C-s/C-r as in isearch.
3824 g / r Start over with new regexp / Refine with additional regexp.
3825 SPC Show full database entry in other window.
3826 f Toggle follow mode: Other window will follow with full db entry.
3827 . Show insertion point.
3828 q Quit without inserting \\cite macro into buffer.
3829 TAB Enter citation key with completion.
3830 RET Accept current entry (also on mouse-2)
3831 a / A Put all entries into single \cite / into many cite commands.")
3832
3833 (defvar reftex-select-bib-map nil
3834 "Keymap used for *RefTeX Select* buffer, when selecting a BibTeX entry.
3835 This keymap can be used to configure the BibTeX selection process which is
3836 started with the command \\[reftex-citation].")
3837
3838 (defun reftex-select-bib-mode ()
3839 "Major mode for selecting a citation key in a LaTeX document.
3840 This buffer was created with RefTeX.
3841 It only has a meaningful keymap when you are in the middle of a
3842 selection process.
3843 In order to select a citation, move the cursor to it and press RET.
3844 Press `?' for a summary of important key bindings.
3845
3846 During a selection process, these are the local bindings.
3847
3848 \\{reftex-select-label-map}"
3849 (interactive)
3850 (kill-all-local-variables)
3851 (make-local-hook 'pre-command-hook)
3852 (make-local-hook 'post-command-hook)
3853 (setq major-mode 'reftex-select-bib-mode
3854 mode-name "RefTeX Select Bib")
3855 ;; We do not set a local map - reftex-select-item does this.
3856 (run-hooks 'reftex-select-bib-mode-hook))
3857
3858 ;; Find bibtex files
3859
3860 (defun reftex-get-bibfile-list ()
3861 ;; Return list of bibfiles for current document.
3862 ;; When using the chapterbib or bibunits package you should either
3863 ;; use the same database files everywhere, or separate parts using
3864 ;; different databases into different files (included into the mater file).
3865 ;; Then this function will return the applicable database files.
3866
3867 ;; Ensure access to scanning info
3868 (reftex-access-scan-info)
3869 (or
3870 ;; Try inside this file (and its includes)
3871 (cdr (reftex-last-assoc-before-elt
3872 'bib (list 'eof (buffer-file-name))
3873 (member (list 'bof (buffer-file-name))
3874 (symbol-value reftex-docstruct-symbol))))
3875 ;; Try after the beginning of this file
3876 (cdr (assq 'bib (member (list 'bof (buffer-file-name))
3877 (symbol-value reftex-docstruct-symbol))))
3878 ;; Anywhere in the entire document
3879 (cdr (assq 'bib (symbol-value reftex-docstruct-symbol)))
3880 (error "\\bibliography statement missing or .bib files not found.")))
3881
3882 ;; Find a certain reference in any of the BibTeX files.
3883
3884 (defun reftex-pop-to-bibtex-entry (key file-list &optional mark-to-kill
3885 highlight item return)
3886 ;; Find BibTeX KEY in any file in FILE-LIST in another window.
3887 ;; If MARK-TO-KILL is non-nil, mark new buffer to kill.
3888 ;; If HIGHLIGHT is non-nil, highlight the match.
3889 ;; If ITEM in non-nil, search for bibitem instead of database entry.
3890 ;; If RETURN is non-nil, just return the entry.
3891
3892 (let* ((re
3893 (if item
3894 (concat "\\\\bibitem\\(\\[[^]]*\\]\\)?{" (regexp-quote key) "}")
3895 (concat "@[a-zA-Z]+[ \t\n\r]*[{(][ \t\n\r]*" (regexp-quote key)
3896 "[, \t\r\n}]")))
3897 (window-conf (current-window-configuration))
3898 file buf)
3899
3900 (catch 'exit
3901 (switch-to-buffer-other-window (current-buffer))
3902 (while file-list
3903 (setq file (car file-list)
3904 file-list (cdr file-list))
3905 (unless (setq buf (reftex-get-file-buffer-force file mark-to-kill))
3906 (error "No such file %s" file))
3907 (switch-to-buffer buf)
3908 (widen)
3909 (goto-char (point-min))
3910 (when (re-search-forward re nil t)
3911 (goto-char (match-beginning 0))
3912 (when return
3913 ;; Just return the relevant entry
3914 (if item (goto-char (match-end 0)))
3915 (setq return (buffer-substring
3916 (point) (reftex-end-of-bib-entry item)))
3917 (set-window-configuration window-conf)
3918 (throw 'exit return))
3919 (recenter 0)
3920 (if highlight
3921 (reftex-highlight 0 (match-beginning 0) (match-end 0)))
3922 (throw 'exit (selected-window))))
3923 (set-window-configuration window-conf)
3924 (if item
3925 (error "No \\bibitem with citation key %s" key)
3926 (error "No BibTeX entry with citation key %s" key)))))
3927
3928 (defun reftex-end-of-bib-entry (item)
3929 (save-excursion
3930 (condition-case nil
3931 (if item
3932 (progn (end-of-line)
3933 (re-search-forward
3934 "\\\\bibitem\\|\\end{thebibliography}")
3935 (1- (match-beginning 0)))
3936 (progn (forward-list 1) (point)))
3937 (error (min (point-max) (+ 300 (point)))))))
3938
3939 ;; Parse bibtex buffers
3940
3941 (defun reftex-extract-bib-entries (buffers)
3942 ;; Extract bib entries which match regexps from BUFFERS.
3943 ;; BUFFERS is a list of buffers or file names.
3944 ;; Return list with entries."
3945 (let* (re-list first-re rest-re
3946 (buffer-list (if (listp buffers) buffers (list buffers)))
3947 found-list entry buffer1 buffer alist
3948 key-point start-point end-point)
3949
3950 ;; Read a regexp, completing on known citation keys.
3951 (setq re-list
3952 (split-string
3953 (completing-read
3954 "RegExp [ && RegExp...]: "
3955 (if (fboundp 'LaTeX-bibitem-list)
3956 (LaTeX-bibitem-list)
3957 (cdr (assoc 'bibview-cache
3958 (symbol-value reftex-docstruct-symbol))))
3959 nil nil nil 'reftex-cite-regexp-hist)
3960 "[ \t]*&&[ \t]*"))
3961
3962 (setq first-re (car re-list) ; We'll use the first re to find things,
3963 rest-re (cdr re-list)) ; the others to narrow down.
3964 (if (string-match "\\`[ \t]*\\'" first-re)
3965 (error "Empty regular expression"))
3966
3967 (save-excursion
3968 (save-window-excursion
3969
3970 ;; Walk through all bibtex files
3971 (while buffer-list
3972 (setq buffer (car buffer-list)
3973 buffer-list (cdr buffer-list))
3974 (if (and (bufferp buffer)
3975 (buffer-live-p buffer))
3976 (setq buffer1 buffer)
3977 (setq buffer1 (reftex-get-file-buffer-force
3978 buffer (not reftex-keep-temporary-buffers))))
3979 (if (not buffer1)
3980 (error "Cannot find BibTeX file %s" buffer)
3981 (message "Scanning bibliography database %s" buffer1))
3982
3983 (set-buffer buffer1)
3984 (save-excursion
3985 (goto-char (point-min))
3986 (while (re-search-forward first-re nil t)
3987 (catch 'search-again
3988 (setq key-point (point))
3989 (unless (re-search-backward
3990 "\\(\\`\\|[\n\r]\\)[ \t]*@\\([a-zA-Z]+\\)[ \t\n\r]*[{(]" nil t)
3991 (throw 'search-again nil))
3992 (setq start-point (point))
3993 (goto-char (match-end 0))
3994 (condition-case nil
3995 (up-list 1)
3996 (error (goto-char key-point)
3997 (throw 'search-again nil)))
3998 (setq end-point (point))
3999
4000 ;; Ignore @string, @comment and @c entries or things
4001 ;; outside entries
4002 (when (or (string= (downcase (match-string 2)) "string")
4003 (string= (downcase (match-string 2)) "comment")
4004 (string= (downcase (match-string 2)) "c")
4005 (< (point) key-point)) ; this means match not in {}
4006 (goto-char key-point)
4007 (throw 'search-again nil))
4008
4009 ;; Well, we have got a match
4010 (setq entry (concat
4011 (buffer-substring start-point (point)) "\n"))
4012
4013 ;; Check if other regexp match as well
4014 (setq re-list rest-re)
4015 (while re-list
4016 (unless (string-match (car re-list) entry)
4017 ;; nope - move on
4018 (throw 'search-again nil))
4019 (pop re-list))
4020
4021 (setq alist (reftex-parse-bibtex-entry
4022 nil start-point end-point))
4023 (push (cons "&entry" entry) alist)
4024
4025 ;; check for crossref entries
4026 (if (assoc "crossref" alist)
4027 (setq alist
4028 (append
4029 alist (reftex-get-crossref-alist alist))))
4030
4031 ;; format the entry
4032 (push (cons "&formatted" (reftex-format-bib-entry alist))
4033 alist)
4034
4035 ;; make key the first element
4036 (push (reftex-get-bib-field "&key" alist) alist)
4037
4038 ;; add it to the list
4039 (push alist found-list))))
4040 (reftex-kill-temporary-buffers))))
4041 (setq found-list (nreverse found-list))
4042
4043 ;; Sorting
4044 (cond
4045 ((eq 'author reftex-sort-bibtex-matches)
4046 (sort found-list 'reftex-bib-sort-author))
4047 ((eq 'year reftex-sort-bibtex-matches)
4048 (sort found-list 'reftex-bib-sort-year))
4049 ((eq 'reverse-year reftex-sort-bibtex-matches)
4050 (sort found-list 'reftex-bib-sort-year-reverse))
4051 (t found-list))))
4052
4053 (defun reftex-bib-sort-author (e1 e2)
4054 (let ((al1 (reftex-get-bib-names "author" e1))
4055 (al2 (reftex-get-bib-names "author" e2)))
4056 (while (and al1 al2 (string= (car al1) (car al2)))
4057 (pop al1)
4058 (pop al2))
4059 (if (and (stringp (car al1))
4060 (stringp (car al2)))
4061 (string< (car al1) (car al2))
4062 (not (stringp (car al1))))))
4063
4064 (defun reftex-bib-sort-year (e1 e2)
4065 (< (string-to-int (cdr (assoc "year" e1)))
4066 (string-to-int (cdr (assoc "year" e2)))))
4067
4068 (defun reftex-bib-sort-year-reverse (e1 e2)
4069 (> (string-to-int (or (cdr (assoc "year" e1)) "0"))
4070 (string-to-int (or (cdr (assoc "year" e2)) "0"))))
4071
4072 (defun reftex-get-crossref-alist (entry)
4073 ;; return the alist from a crossref entry
4074 (let ((crkey (cdr (assoc "crossref" entry)))
4075 start)
4076 (save-excursion
4077 (save-restriction
4078 (widen)
4079 (if (re-search-forward
4080 (concat "@\\w+[{(][ \t\n\r]*" (regexp-quote crkey)
4081 "[ \t\n\r]*,") nil t)
4082 (progn
4083 (setq start (match-beginning 0))
4084 (condition-case nil
4085 (up-list 1)
4086 (error nil))
4087 (reftex-parse-bibtex-entry nil start (point)))
4088 nil)))))
4089
4090 ;; Parse the thebibliography environment
4091 (defun reftex-extract-bib-entries-from-thebibliography (file)
4092 ;; Extract bib-entries from the \begin{thebibliography} environment.
4093 ;; Parsing is not as good as for the BibTeX database stuff.
4094 ;; The environment should be located in file FILE.
4095
4096 (let* (start end buf entries re re-list)
4097 (unless file
4098 (error "Need file name to find thebibliography environment"))
4099 (setq buf (reftex-get-file-buffer-force
4100 file (not reftex-keep-temporary-buffers)))
4101 (unless buf
4102 (error "No such file %s" file))
4103 (message "Scanning thebibliography environment in %s" file)
4104
4105 (save-excursion
4106 (set-buffer buf)
4107 (save-restriction
4108 (widen)
4109 (goto-char (point-min))
4110 (if (re-search-forward
4111 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\begin{thebibliography}" nil t)
4112 (progn
4113 (beginning-of-line 2)
4114 (setq start (point))))
4115 (if (re-search-forward
4116 "\\(\\`\\|[\n\r]\\)[ \t]*\\\\end{thebibliography}" nil t)
4117 (progn
4118 (beginning-of-line 1)
4119 (setq end (point))))
4120 (when (and start end)
4121 (setq entries
4122 (mapcar 'reftex-parse-bibitem
4123 (delete ""
4124 (split-string
4125 (buffer-substring-no-properties start end)
4126 "[ \t\n\r]*\\\\bibitem\\(\\[[^]]*]\\)*")))))))
4127 (unless entries
4128 (error "No bibitems found"))
4129
4130 (setq re-list (split-string
4131 (read-string "RegExp [ && RegExp...]: "
4132 nil 'reftex-cite-regexp-hist)
4133 "[ \t]*&&[ \t]*"))
4134 (if (string-match "\\`[ \t]*\\'" (car re-list))
4135 (error "Empty regular expression"))
4136
4137 (while (and (setq re (pop re-list)) entries)
4138 (setq entries
4139 (delq nil (mapcar
4140 (function
4141 (lambda (x)
4142 (if (string-match re (cdr (assoc "&entry" x)))
4143 x nil)))
4144 entries))))
4145 (setq entries
4146 (mapcar
4147 (lambda (x)
4148 (push (cons "&formatted" (reftex-format-bibitem x)) x)
4149 (push (reftex-get-bib-field "&key" x) x)
4150 x)
4151 entries))
4152
4153 entries))
4154
4155 ;; Parse and format individual entries
4156
4157 (defun reftex-get-bib-names (field entry)
4158 ;; Return a list with the author or editor names in ENTRY
4159 (let ((names (reftex-get-bib-field field entry)))
4160 (if (equal "" names)
4161 (setq names (reftex-get-bib-field "editor" entry)))
4162 (while (string-match "\\band\\b[ \t]*" names)
4163 (setq names (replace-match "\n" nil t names)))
4164 (while (string-match "[\\.a-zA-Z\\-]+\\.[ \t]*\\|,.*\\|[{}]+" names)
4165 (setq names (replace-match "" nil t names)))
4166 (while (string-match "^[ \t]+\\|[ \t]+$" names)
4167 (setq names (replace-match "" nil t names)))
4168 (while (string-match "[ \t][ \t]+" names)
4169 (setq names (replace-match " " nil t names)))
4170 (split-string names "\n")))
4171
4172 (defun reftex-parse-bibtex-entry (entry &optional from to)
4173 (let (alist key start field)
4174 (save-excursion
4175 (save-restriction
4176 (if entry
4177 (progn
4178 (set-buffer (get-buffer-create " *RefTeX-scratch*"))
4179 (fundamental-mode)
4180 (erase-buffer)
4181 (insert entry))
4182 (widen)
4183 (narrow-to-region from to))
4184 (goto-char (point-min))
4185
4186 (if (re-search-forward
4187 "@\\(\\w+\\)[ \t\n\r]*[{(][ \t\n\r]*\\([^ \t\n\r,]+\\)" nil t)
4188 (setq alist
4189 (list
4190 (cons "&type" (downcase (reftex-match-string 1)))
4191 (cons "&key" (reftex-match-string 2)))))
4192 (while (re-search-forward "\\(\\w+\\)[ \t\n\r]*=[ \t\n\r]*" nil t)
4193 (setq key (downcase (reftex-match-string 1)))
4194 (cond
4195 ((= (following-char) ?{)
4196 (forward-char 1)
4197 (setq start (point))
4198 (condition-case nil
4199 (up-list 1)
4200 (error nil)))
4201 ((= (following-char) ?\")
4202 (forward-char 1)
4203 (setq start (point))
4204 (while (and (search-forward "\"" nil t)
4205 (= ?\\ (char-after (- (point) 2))))))
4206 (t
4207 (setq start (point))
4208 (re-search-forward "[ \t]*[\n\r,}]" nil 1)))
4209 (setq field (buffer-substring-no-properties start (1- (point))))
4210 ;; remove extra whitespace
4211 (while (string-match "[\n\t\r]\\|[ \t][ \t]+" field)
4212 (setq field (replace-match " " nil t field)))
4213 ;; remove leading garbage
4214 (if (string-match "^[ \t{]+" field)
4215 (setq field (replace-match "" nil t field)))
4216 ;; remove trailing garbage
4217 (if (string-match "[ \t}]+$" field)
4218 (setq field (replace-match "" nil t field)))
4219 (push (cons key field) alist))))
4220 alist))
4221
4222 (defun reftex-get-bib-field (fieldname entry &optional format)
4223 ;; Extract the field FIELDNAME from an ENTRY
4224 (let ((cell (assoc fieldname entry)))
4225 (if cell
4226 (if format
4227 (format format (cdr cell))
4228 (cdr cell))
4229 "")))
4230
4231 (defun reftex-format-bib-entry (entry)
4232 ;; Format a BibTeX ENTRY so that it is nice to look at
4233 (let*
4234 ((auth-list (reftex-get-bib-names "author" entry))
4235 (authors (mapconcat 'identity auth-list ", "))
4236 (year (reftex-get-bib-field "year" entry))
4237 (title (reftex-get-bib-field "title" entry))
4238 (type (reftex-get-bib-field "&type" entry))
4239 (key (reftex-get-bib-field "&key" entry))
4240 (extra
4241 (cond
4242 ((equal type "article")
4243 (concat (reftex-get-bib-field "journal" entry) " "
4244 (reftex-get-bib-field "volume" entry) ", "
4245 (reftex-get-bib-field "pages" entry)))
4246 ((equal type "book")
4247 (concat "book (" (reftex-get-bib-field "publisher" entry) ")"))
4248 ((equal type "phdthesis")
4249 (concat "PhD: " (reftex-get-bib-field "school" entry)))
4250 ((equal type "mastersthesis")
4251 (concat "Master: " (reftex-get-bib-field "school" entry)))
4252 ((equal type "inbook")
4253 (concat "Chap: " (reftex-get-bib-field "chapter" entry)
4254 ", pp. " (reftex-get-bib-field "pages" entry)))
4255 ((or (equal type "conference")
4256 (equal type "incollection")
4257 (equal type "inproceedings"))
4258 (reftex-get-bib-field "booktitle" entry "in: %s"))
4259 (t ""))))
4260 (setq authors (reftex-truncate authors 30 t t))
4261 (when (reftex-use-fonts)
4262 (put-text-property 0 (length key) 'face
4263 (reftex-verified-face reftex-label-face
4264 'font-lock-constant-face
4265 'font-lock-reference-face)
4266 key)
4267 (put-text-property 0 (length authors) 'face reftex-bib-author-face
4268 authors)
4269 (put-text-property 0 (length year) 'face reftex-bib-year-face
4270 year)
4271 (put-text-property 0 (length title) 'face reftex-bib-title-face
4272 title)
4273 (put-text-property 0 (length extra) 'face reftex-bib-extra-face
4274 extra))
4275 (concat key "\n " authors " " year " " extra "\n " title "\n\n")))
4276
4277 (defun reftex-parse-bibitem (item)
4278 ;; Parse a \bibitem entry
4279 (let ((key "") (text ""))
4280 (when (string-match "\\`{\\([^}]+\\)}\\([\001-\255]*\\)" item)
4281 (setq key (match-string 1 item)
4282 text (match-string 2 item)))
4283 ;; Clean up the text a little bit
4284 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
4285 (setq text (replace-match " " nil t text)))
4286 (if (string-match "\\`[ \t]+" text)
4287 (setq text (replace-match "" nil t text)))
4288 (list
4289 (cons "&key" key)
4290 (cons "&text" text)
4291 (cons "&entry" (concat key " " text)))))
4292
4293 (defun reftex-format-bibitem (item)
4294 ;; Format a \bibitem entry so that it is (relatively) nice to look at.
4295 (let ((text (reftex-get-bib-field "&text" item))
4296 (key (reftex-get-bib-field "&key" item))
4297 (lines nil))
4298
4299 ;; Wrap the text into several lines.
4300 (while (and (> (length text) 70)
4301 (string-match " " (substring text 60)))
4302 (push (substring text 0 (+ 60 (match-beginning 0))) lines)
4303 (setq text (substring text (+ 61 (match-beginning 0)))))
4304 (push text lines)
4305 (setq text (mapconcat 'identity (nreverse lines) "\n "))
4306
4307 (when (reftex-use-fonts)
4308 (put-text-property 0 (length text) 'face reftex-bib-author-face text))
4309 (concat key "\n " text "\n\n")))
4310
4311 ;; Make a citation
4312
4313 ;;;###autoload
4314 (defun reftex-citation (&optional no-insert)
4315 "Make a citation using BibTeX database files.
4316 After asking for a Regular Expression, it scans the buffers with
4317 bibtex entries (taken from the \\bibliography command) and offers the
4318 matching entries for selection. The selected entry is formated according
4319 to `reftex-cite-format' and inserted into the buffer.
4320 If NO-INSERT is non-nil, nothing is inserted, only the selected key returned.
4321 The regular expression uses an expanded syntax: && is interpreted as `and'.
4322 Thus, `aaaa&&bbb' matches entries which contain both `aaaa' and `bbb'.
4323 While entering the regexp, completion on knows citation keys is possible.
4324 When this function is called with point inside the braces of a \\cite
4325 command, it will add another key, ignoring the value of `reftex-cite-format'.
4326 When called with a numeric prefix, that many citations will be made and all
4327 put into the same \\cite command.
4328 When called with just or two C-u as prefix, enforces rescan of buffer for
4329 bibliography statement (e.g. if it was changed)."
4330
4331 (interactive)
4332
4333 ;; check for recursive edit
4334 (reftex-check-recursive-edit)
4335
4336 ;; This function may also be called outside reftex-mode.
4337 ;; Thus look for the scanning info only if in reftex-mode.
4338
4339 (when reftex-mode
4340 (reftex-access-scan-info current-prefix-arg))
4341
4342 ;; Call reftex-do-citation, but protected
4343 (unwind-protect
4344 (reftex-do-citation current-prefix-arg no-insert)
4345 (reftex-kill-temporary-buffers)))
4346
4347 (defun reftex-do-citation (&optional arg no-insert)
4348 ;; This really does the work of reftex-citation.
4349
4350 (let* ((format (reftex-figure-out-cite-format arg no-insert))
4351 (docstruct-symbol reftex-docstruct-symbol)
4352 (selected-entries (reftex-offer-bib-menu))
4353 (insert-entries selected-entries)
4354 entry string cite-view)
4355
4356 (unless selected-entries (error "Quit"))
4357
4358 (if (stringp selected-entries)
4359 ;; Nonexistent entry
4360 (setq selected-entries nil
4361 insert-entries (list (list selected-entries
4362 (cons "&key" selected-entries))))
4363 ;; It makes sense to compute the cite-view strings.
4364 (setq cite-view t))
4365
4366 (when (eq (car selected-entries) 'concat)
4367 ;; All keys go into a single command - we need to trick a little
4368 (pop selected-entries)
4369 (let ((concat-keys (mapconcat 'car selected-entries ",")))
4370 (setq insert-entries
4371 (list (list concat-keys (cons "&key" concat-keys))))))
4372
4373 (unless no-insert
4374
4375 ;; We shall insert this into the buffer...
4376 (message "Formatting...")
4377
4378 (while (setq entry (pop insert-entries))
4379 ;; Format the citation and insert it
4380 (setq string (if reftex-format-cite-function
4381 (funcall reftex-format-cite-function
4382 (reftex-get-bib-field "&key" entry)
4383 format)
4384 (reftex-format-citation entry format)))
4385 (insert string))
4386
4387 ;; Reposition cursor?
4388 (when (string-match "\\?" string)
4389 (search-backward "?")
4390 (delete-char 1))
4391
4392 ;; Tell AUCTeX
4393 (when (and reftex-mode
4394 (fboundp 'LaTeX-add-bibitems)
4395 reftex-plug-into-AUCTeX)
4396 (apply 'LaTeX-add-bibitems (mapcar 'car selected-entries)))
4397
4398 ;; Produce the cite-view strings
4399 (when (and reftex-mode reftex-cache-cite-echo cite-view)
4400 (mapcar (lambda (entry)
4401 (reftex-make-cite-echo-string entry docstruct-symbol))
4402 selected-entries))
4403
4404 (message ""))
4405
4406 (set-marker reftex-select-return-marker nil)
4407 (reftex-kill-buffer "*RefTeX Select*")
4408
4409 ;; Check if the prefix arg was numeric, and call recursively
4410 (when (integerp arg)
4411 (if (> arg 1)
4412 (progn
4413 (skip-chars-backward "}")
4414 (decf arg)
4415 (reftex-do-citation arg))
4416 (forward-char 1)))
4417
4418 ;; Return the citation key
4419 (car (car selected-entries))))
4420
4421 (defun reftex-figure-out-cite-format (arg no-insert)
4422 ;; Check if there is already a cite command at point and change cite format
4423 ;; in order to only add another reference in the same cite command.
4424 (let ((macro (car (reftex-what-macro 1)))
4425 (cite-format-value (reftex-get-cite-format))
4426 key format)
4427 (cond
4428 (no-insert
4429 ;; Format does not really matter because nothing will be inserted.
4430 (setq format "%l"))
4431
4432 ((and (stringp macro)
4433 (string-match "\\`\\\\cite\\|cite\\'" macro))
4434 ;; We are already inside a cite macro
4435 (if (or (not arg) (not (listp arg)))
4436 (setq format
4437 (concat
4438 (if (member (preceding-char) '(?\{ ?,)) "" ",")
4439 "%l"
4440 (if (member (following-char) '(?\} ?,)) "" ",")))
4441 (setq format "%l")))
4442 (t
4443 ;; Figure out the correct format
4444 (setq format
4445 (if (and (symbolp cite-format-value)
4446 (assq cite-format-value reftex-cite-format-builtin))
4447 (nth 2 (assq cite-format-value reftex-cite-format-builtin))
4448 cite-format-value))
4449 (when (listp format)
4450 (setq key
4451 (reftex-select-with-char
4452 "" (concat "SELECT A CITATION FORMAT\n\n"
4453 (mapconcat
4454 (lambda (x)
4455 (format "[%c] %s %s" (car x)
4456 (if (> (car x) 31) " " "")
4457 (cdr x)))
4458 format "\n"))))
4459 (if (assq key format)
4460 (setq format (cdr (assq key format)))
4461 (error "No citation format associated with key `%c'" key)))))
4462 format))
4463
4464 (defun reftex-get-cite-format ()
4465 ;; Return the current citation format. Either the document-local value in
4466 ;; reftex-cite-format-symbol, or the global value in reftex-cite-format.
4467 (if (and reftex-docstruct-symbol
4468 (symbolp reftex-docstruct-symbol)
4469 (get reftex-docstruct-symbol 'reftex-cite-format))
4470 (get reftex-docstruct-symbol 'reftex-cite-format)
4471 reftex-cite-format))
4472
4473 (defun reftex-offer-bib-menu ()
4474 ;; Offer bib menu and return list of selected items
4475
4476 (let (found-list rtn key data selected-entries)
4477
4478 (while
4479 (not
4480 (catch 'done
4481 ;; Scan bibtex files
4482 (setq found-list
4483 (cond
4484 ((assq 'bib (symbol-value reftex-docstruct-symbol))
4485 ;; using BibTeX database files.
4486 (reftex-extract-bib-entries (reftex-get-bibfile-list)))
4487 ((assq 'thebib (symbol-value reftex-docstruct-symbol))
4488 ;; using thebibliography environment.
4489 (reftex-extract-bib-entries-from-thebibliography
4490 (cdr (assq 'thebib (symbol-value reftex-docstruct-symbol)))))
4491 (reftex-default-bibliography
4492 (message "Using default bibliography")
4493 (reftex-extract-bib-entries reftex-default-bibliography))
4494 (t (error "No valid bibliography in this document, and no default available"))))
4495
4496 (unless found-list
4497 (error "Sorry, no matches found"))
4498
4499 ;; Remember where we came from
4500 (setq reftex-call-back-to-this-buffer (current-buffer))
4501 (set-marker reftex-select-return-marker (point))
4502
4503 ;; Offer selection
4504 (save-window-excursion
4505 (delete-other-windows)
4506 (let ((default-major-mode 'reftex-select-bib-mode))
4507 (reftex-kill-buffer "*RefTeX Select*")
4508 (switch-to-buffer-other-window "*RefTeX Select*")
4509 (unless (eq major-mode 'reftex-select-bib-mode)
4510 (reftex-select-bib-mode))
4511 (let ((buffer-read-only nil))
4512 (erase-buffer)
4513 (reftex-insert-bib-matches found-list)))
4514 (setq buffer-read-only t)
4515 (if (= 0 (buffer-size))
4516 (error "Sorry, no matches found"))
4517 (setq truncate-lines t)
4518 (goto-char 1)
4519 (while t
4520 (setq rtn
4521 (reftex-select-item
4522 reftex-citation-prompt
4523 reftex-citation-help
4524 reftex-select-bib-map
4525 nil
4526 'reftex-bibtex-selection-callback nil))
4527 (setq key (car rtn)
4528 data (nth 1 rtn))
4529 (unless key (throw 'done t))
4530 (cond
4531 ((eq key ?g)
4532 ;; Start over
4533 (throw 'done nil))
4534 ((eq key ?r)
4535 ;; Restrict with new regular expression
4536 (setq found-list (reftex-restrict-bib-matches found-list))
4537 (let ((buffer-read-only nil))
4538 (erase-buffer)
4539 (reftex-insert-bib-matches found-list))
4540 (goto-char 1))
4541 ((eq key ?A)
4542 ;; Take all
4543 (setq selected-entries found-list)
4544 (throw 'done t))
4545 ((eq key ?a)
4546 ;; Take all
4547 (setq selected-entries (cons 'concat found-list))
4548 (throw 'done t))
4549 ((or (eq key ?\C-m)
4550 (eq key 'return))
4551 ;; Take selected
4552 (setq selected-entries (if data (list data) nil))
4553 (throw 'done t))
4554 ((stringp key)
4555 ;; Got this one with completion
4556 (setq selected-entries key)
4557 (throw 'done t))
4558 (t
4559 (ding))))))))
4560 selected-entries))
4561
4562 (defun reftex-restrict-bib-matches (found-list)
4563 ;; Limit FOUND-LIST with more regular expressions
4564 (let ((re-list (split-string (read-string
4565 "RegExp [ && RegExp...]: "
4566 nil 'reftex-cite-regexp-hist)
4567 "[ \t]*&&[ \t]*"))
4568 (found-list-r found-list)
4569 re)
4570 (while (setq re (pop re-list))
4571 (setq found-list-r
4572 (delq nil
4573 (mapcar
4574 (lambda (x)
4575 (if (string-match
4576 re (cdr (assoc "&entry" x)))
4577 x
4578 nil))
4579 found-list-r))))
4580 (if found-list-r
4581 found-list-r
4582 (ding)
4583 found-list)))
4584
4585 (defun reftex-insert-bib-matches (list)
4586 ;; Insert the bib matches and number them correctly
4587 (let ((mouse-face
4588 (if (memq reftex-highlight-selection '(mouse both))
4589 reftex-mouse-selected-face
4590 nil))
4591 tmp len)
4592 (mapcar
4593 (function
4594 (lambda (x)
4595 (setq tmp (cdr (assoc "&formatted" x))
4596 len (length tmp))
4597 (put-text-property 0 len ':data x tmp)
4598 (put-text-property 0 (1- len) 'mouse-face mouse-face tmp)
4599 (insert tmp)))
4600 list))
4601 (run-hooks 'reftex-display-copied-context-hook))
4602
4603 (defun reftex-format-names (namelist n)
4604 (let (last (len (length namelist)))
4605 (cond
4606 ((< len 1) "")
4607 ((= 1 len) (car namelist))
4608 ((> len n) (concat (car namelist) (nth 2 reftex-cite-punctuation)))
4609 (t
4610 (setq n (min len n)
4611 last (nth (1- n) namelist))
4612 (setcdr (nthcdr (- n 2) namelist) nil)
4613 (concat
4614 (mapconcat 'identity namelist (nth 0 reftex-cite-punctuation))
4615 (nth 1 reftex-cite-punctuation)
4616 last)))))
4617
4618 (defun reftex-format-citation (entry format)
4619 ;; Format a citation from the info in the BibTeX ENTRY
4620
4621 (unless (stringp format) (setq format "\\cite{%l}"))
4622
4623 (if (and reftex-comment-citations
4624 (string-match "%l" reftex-cite-comment-format))
4625 (error "reftex-cite-comment-format contains illegal %%l"))
4626
4627 (while (string-match
4628 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
4629 format)
4630 (let ((n (string-to-int (match-string 4 format)))
4631 (l (string-to-char (match-string 5 format)))
4632 rpl b e)
4633 (save-match-data
4634 (setq rpl
4635 (cond
4636 ((= l ?l) (concat
4637 (reftex-get-bib-field "&key" entry)
4638 (if reftex-comment-citations
4639 reftex-cite-comment-format
4640 "")))
4641 ((= l ?a) (reftex-format-names
4642 (reftex-get-bib-names "author" entry)
4643 (or n 2)))
4644 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
4645 ((= l ?b) (reftex-get-bib-field "booktitle" entry "in: %s"))
4646 ((= l ?B) (reftex-abbreviate-title
4647 (reftex-get-bib-field "booktitle" entry "in: %s")))
4648 ((= l ?c) (reftex-get-bib-field "chapter" entry))
4649 ((= l ?d) (reftex-get-bib-field "edition" entry))
4650 ((= l ?e) (reftex-format-names
4651 (reftex-get-bib-names "editor" entry)
4652 (or n 2)))
4653 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
4654 ((= l ?h) (reftex-get-bib-field "howpublished" entry))
4655 ((= l ?i) (reftex-get-bib-field "institution" entry))
4656 ((= l ?j) (reftex-get-bib-field "journal" entry))
4657 ((= l ?k) (reftex-get-bib-field "key" entry))
4658 ((= l ?m) (reftex-get-bib-field "month" entry))
4659 ((= l ?n) (reftex-get-bib-field "number" entry))
4660 ((= l ?o) (reftex-get-bib-field "organization" entry))
4661 ((= l ?p) (reftex-get-bib-field "pages" entry))
4662 ((= l ?P) (car (split-string
4663 (reftex-get-bib-field "pages" entry)
4664 "[- .]+")))
4665 ((= l ?s) (reftex-get-bib-field "school" entry))
4666 ((= l ?u) (reftex-get-bib-field "publisher" entry))
4667 ((= l ?r) (reftex-get-bib-field "address" entry))
4668 ((= l ?t) (reftex-get-bib-field "title" entry))
4669 ((= l ?T) (reftex-abbreviate-title
4670 (reftex-get-bib-field "title" entry)))
4671 ((= l ?v) (reftex-get-bib-field "volume" entry))
4672 ((= l ?y) (reftex-get-bib-field "year" entry)))))
4673
4674 (if (string= rpl "")
4675 (setq b (match-beginning 2) e (match-end 2))
4676 (setq b (match-beginning 3) e (match-end 3)))
4677 (setq format (concat (substring format 0 b) rpl (substring format e)))))
4678 (while (string-match "%%" format)
4679 (setq format (replace-match "%" t t format)))
4680 (while (string-match "[ ,.;:]*%<" format)
4681 (setq format (replace-match "" t t format)))
4682 format)
4683
4684 (defun reftex-bibtex-selection-callback (data ignore no-revisit)
4685 ;; Callback function to be called from the BibTeX selection, in
4686 ;; order to display context. This function is relatively slow and not
4687 ;; recommended for follow mode. It works OK for individual lookups.
4688 (let ((win (selected-window))
4689 (key (reftex-get-bib-field "&key" data))
4690 bibfile-list item tmp)
4691
4692 (catch 'exit
4693 (save-excursion
4694 (set-buffer reftex-call-back-to-this-buffer)
4695 (cond
4696 ((assq 'bib (symbol-value reftex-docstruct-symbol))
4697 (setq bibfile-list (reftex-get-bibfile-list)))
4698 ((setq tmp (assq 'thebib (symbol-value reftex-docstruct-symbol)))
4699 (setq bibfile-list (list (cdr tmp))
4700 item t))
4701 (reftex-default-bibliography
4702 (setq bibfile-list reftex-default-bibliography))
4703 (t (ding) (throw 'exit))))
4704
4705 (when no-revisit
4706 (setq bibfile-list (reftex-visited-files bibfile-list)))
4707
4708 (condition-case nil
4709 (reftex-pop-to-bibtex-entry
4710 key bibfile-list (not reftex-keep-temporary-buffers) t item)
4711 (error (ding))))
4712
4713 (select-window win)))
4714
4715 ;;; =========================================================================
4716 ;;;
4717 ;;; Here is the routine used for selection
4718
4719 ;; Marker for return point from recursive edit
4720 (defvar reftex-recursive-edit-marker (make-marker))
4721
4722 (defvar reftex-last-data nil)
4723 (defvar reftex-last-line nil)
4724
4725 (defun reftex-check-recursive-edit ()
4726 ;; Check if we are already in a recursive edit. Abort with helpful
4727 ;; message if so.
4728 (if (marker-position reftex-recursive-edit-marker)
4729 (error
4730 (substitute-command-keys
4731 "In unfinished selection process. Finish, or abort with \\[abort-recursive-edit]."))))
4732
4733 (defun reftex-select-item (prompt help-string keymap
4734 &optional offset
4735 call-back cb-flag)
4736 ;; Select an item, using PROMPT. The function returns a key indicating
4737 ;; an exit status, along with a data structure indicating which item was
4738 ;; selected.
4739 ;; HELP-STRING contains help. KEYMAP is a keymap with the available
4740 ;; selection commands.
4741 ;; OFFSET can be a label list item which will be selected at start.
4742 ;; When it is t, point will start out at the beginning of the buffer.
4743 ;; Any other value will cause restart where last selection left off.
4744 ;; When CALL-BACK is given, it is a function which is called with the index
4745 ;; of the element.
4746 ;; CB-FLAG is the initial value of that flag.
4747
4748 (let* (ev data last-data callback-fwd (selection-buffer (current-buffer)))
4749
4750 (setq ev
4751 (catch 'myexit
4752 (save-window-excursion
4753 (setq truncate-lines t)
4754
4755 ;; Find a good starting point
4756 (cond
4757 (offset
4758 (goto-char
4759 (or (and (listp offset)
4760 (text-property-any (point-min) (point-max)
4761 ':data offset))
4762 (and (local-variable-p 'reftex-last-data (current-buffer))
4763 (boundp 'reftex-last-data)
4764 (listp reftex-last-data)
4765 (text-property-any (point-min) (point-max)
4766 ':data reftex-last-data))
4767 (and (local-variable-p 'reftex-last-line (current-buffer))
4768 (boundp 'reftex-last-line)
4769 (integerp reftex-last-line)
4770 (progn (goto-line reftex-last-line) (point)))
4771 (point-min))))
4772 (t (goto-char (point-min))))
4773 (beginning-of-line 1)
4774 (set (make-local-variable 'reftex-last-follow-point) (point))
4775
4776 (unwind-protect
4777 (progn
4778 (use-local-map keymap)
4779 (add-hook 'pre-command-hook 'reftex-select-pre-command-hook nil t)
4780 (add-hook 'post-command-hook 'reftex-select-post-command-hook nil t)
4781 (princ prompt)
4782 (set-marker reftex-recursive-edit-marker (point))
4783 ;; XEmacs does not run post-command-hook here
4784 (and (featurep 'xemacs) (run-hooks 'post-command-hook))
4785 (recursive-edit))
4786
4787 (set-marker reftex-recursive-edit-marker nil)
4788 (save-excursion
4789 (set-buffer selection-buffer)
4790 (use-local-map nil)
4791 (remove-hook 'pre-command-hook 'reftex-select-pre-command-hook t)
4792 (remove-hook 'post-command-hook
4793 'reftex-select-post-command-hook t))))))
4794
4795 (set (make-local-variable 'reftex-last-line)
4796 (+ (count-lines (point-min) (point)) (if (bolp) 1 0)))
4797 (set (make-local-variable 'reftex-last-data) last-data)
4798 (reftex-kill-buffer "*RefTeX Help*")
4799 (setq callback-fwd (not callback-fwd)) ;; ;-)))
4800 (message "")
4801 (list ev data last-data)))
4802
4803 ;; The following variables are all bound dynamically in `reftex-select-item'.
4804 ;; The defvars are here only to silence the byte compiler.
4805
4806 (defvar found-list)
4807 (defvar cb-flag)
4808 (defvar data)
4809 (defvar prompt)
4810 (defvar last-data)
4811 (defvar call-back)
4812 (defvar help-string)
4813 (defvar callback-fwd)
4814 (defvar varioref)
4815
4816 ;; The selection commands
4817
4818 (defun reftex-select-pre-command-hook ()
4819 (reftex-unhighlight 1)
4820 (reftex-unhighlight 0))
4821
4822 (defun reftex-select-post-command-hook ()
4823 (let (b e)
4824 (setq data (get-text-property (point) ':data))
4825 (setq last-data (or data last-data))
4826
4827 (when (and data cb-flag
4828 (not (equal reftex-last-follow-point (point))))
4829 (setq reftex-last-follow-point (point))
4830 (funcall call-back data callback-fwd
4831 (not reftex-revisit-to-follow)))
4832 (if data
4833 (setq b (or (previous-single-property-change
4834 (1+ (point)) ':data)
4835 (point-min))
4836 e (or (next-single-property-change
4837 (point) ':data)
4838 (point-max)))
4839 (setq b (point) e (point)))
4840 (and (memq reftex-highlight-selection '(cursor both))
4841 (reftex-highlight 1 b e))
4842 (if (or (not (pos-visible-in-window-p b))
4843 (not (pos-visible-in-window-p e)))
4844 (recenter '(4)))
4845 (unless (current-message)
4846 (princ prompt))))
4847
4848 (defun reftex-select-next (&optional arg)
4849 "Move to next selectable item."
4850 (interactive "p")
4851 (setq callback-fwd t)
4852 (or (eobp) (forward-char 1))
4853 (re-search-forward "^[^. \t\n\r]" nil t arg)
4854 (beginning-of-line 1))
4855 (defun reftex-select-previous (&optional arg)
4856 "Move to previous selectable item."
4857 (interactive "p")
4858 (setq callback-fwd nil)
4859 (re-search-backward "^[^. \t\n\r]" nil t arg))
4860 (defun reftex-select-next-heading (&optional arg)
4861 "Move to next table of contentes line."
4862 (interactive "p")
4863 (end-of-line)
4864 (re-search-forward "^ " nil t arg)
4865 (beginning-of-line))
4866 (defun reftex-select-previous-heading (&optional arg)
4867 "Move to previous table of contentes line."
4868 (interactive "p")
4869 (re-search-backward "^ " nil t arg))
4870 (defun reftex-select-quit ()
4871 "Abort selection process."
4872 (interactive)
4873 (throw 'myexit nil))
4874 (defun reftex-select-keyboard-quit ()
4875 "Abort selection process."
4876 (interactive)
4877 (throw 'exit t))
4878 (defun reftex-select-jump-to-previous ()
4879 "Jump back to where previous selection process left off."
4880 (interactive)
4881 (let (pos)
4882 (cond
4883 ((and (local-variable-p 'reftex-last-data (current-buffer))
4884 reftex-last-data
4885 (setq pos (text-property-any (point-min) (point-max)
4886 ':data reftex-last-data)))
4887 (goto-char pos))
4888 ((and (local-variable-p 'reftex-last-line (current-buffer))
4889 (integerp reftex-last-line))
4890 (goto-line reftex-last-line))
4891 (t (ding)))))
4892 (defun reftex-select-toggle-follow ()
4893 "Toggle follow mode: Other window follows with full context."
4894 (interactive)
4895 (setq reftex-last-follow-point -1)
4896 (setq cb-flag (not cb-flag)))
4897 (defun reftex-select-toggle-varioref ()
4898 "Toggle the macro used for referencing the label between \\ref and \\vref."
4899 (interactive)
4900 (if (string= varioref "\\ref")
4901 (setq varioref "\\vref")
4902 (setq varioref "\\ref"))
4903 (force-mode-line-update))
4904 (defun reftex-select-show-insertion-point ()
4905 "Show the point from where selection was started in another window."
4906 (interactive)
4907 (let ((this-window (selected-window)))
4908 (unwind-protect
4909 (progn
4910 (switch-to-buffer-other-window
4911 (marker-buffer reftex-select-return-marker))
4912 (goto-char (marker-position reftex-select-return-marker))
4913 (recenter '(4)))
4914 (select-window this-window))))
4915 (defun reftex-select-callback ()
4916 "Show full context in another window."
4917 (interactive)
4918 (if data (funcall call-back data callback-fwd nil) (ding)))
4919 (defun reftex-select-accept ()
4920 "Accept the currently selected item."
4921 (interactive)
4922 (throw 'myexit 'return))
4923 (defun reftex-select-mouse-accept (ev)
4924 "Accept the item at the mouse click."
4925 (interactive "e")
4926 (mouse-set-point ev)
4927 (setq data (get-text-property (point) ':data))
4928 (setq last-data (or data last-data))
4929 (throw 'myexit 'return))
4930 (defun reftex-select-read-label ()
4931 "Use minibuffer to read a label to reference, with completion."
4932 (interactive)
4933 (let ((label (completing-read
4934 "Label: " (symbol-value reftex-docstruct-symbol)
4935 nil nil reftex-prefix)))
4936 (unless (or (equal label "") (equal label reftex-prefix))
4937 (throw 'myexit label))))
4938 (defun reftex-select-read-cite ()
4939 "Use minibuffer to read a citation key with completion."
4940 (interactive)
4941 (let* ((key (completing-read "Citation key: " found-list))
4942 (entry (assoc key found-list)))
4943 (cond
4944 ((or (null key) (equal key "")))
4945 (entry
4946 (setq data entry)
4947 (setq last-data data)
4948 (throw 'myexit 'return))
4949 (t (throw 'myexit key)))))
4950 (defun reftex-select-help ()
4951 "Display a summary of the special key bindings."
4952 (interactive)
4953 (with-output-to-temp-buffer "*RefTeX Help*"
4954 (princ help-string))
4955 (reftex-enlarge-to-fit "*RefTeX Help*" t))
4956
4957 ;;; =========================================================================
4958 ;;;
4959 ;;; View cross references
4960
4961 (defun reftex-view-crossref (&optional arg how)
4962 "View cross reference of \\ref or \\cite macro at point.
4963 If the macro at point is a \\ref, show the corresponding label definition.
4964 If it is a \\cite, show the BibTeX database entry or the \\bibitem.
4965 To cope with the plethora of variations in packages, this
4966 function assumes any macro either starting with or ending in `ref' or
4967 `cite' to contain cross references.
4968 When the LaTeX package `xr' is being used, this command will also view
4969 crossreferences in external documents. However, this works correctly only
4970 when the \\externaldocument macros are used with the optional label prefix
4971 argument.
4972 With one or two C-u prefixes, enforce rescanning of the document.
4973 With argument 2, select the window showing the cross reference.
4974 When HOW is 'echo, call the corresponding echo function.
4975 When HOW is 'tmp-window, make the pop-up window as small as possible and
4976 arrange for its removal before the next command."
4977
4978 (interactive "P")
4979
4980 ;; See where we are.
4981 (let* ((macro (car (reftex-what-macro 1)))
4982 (key (reftex-this-word "^{}%\n\r,")))
4983
4984 (setq reftex-call-back-to-this-buffer (current-buffer))
4985
4986 (if (and macro
4987 (string-match "\\`\\\\cite\\|\\`\\\\ref\\|cite\\'\\|ref\\'"
4988 macro))
4989 (and (setq macro (match-string 0 macro))
4990 (string-match "\\`\\\\" macro)
4991 (setq macro (substring macro 1)))
4992 (setq macro nil))
4993
4994 (if (or (null macro) (reftex-in-comment))
4995 (error "No cross reference to display"))
4996
4997 (if (eq how 'tmp-window)
4998 ;; Remember the window configuration
4999 (put 'reftex-auto-view-crossref 'last-window-conf
5000 (current-window-configuration)))
5001 (cond
5002 ((string= macro "cite")
5003 (reftex-view-cr-cite arg key how))
5004 ((string= macro "ref")
5005 (reftex-view-cr-ref arg key how))
5006 (t
5007 (error "Cannot display crossref\n")))))
5008
5009 (defun reftex-view-cr-cite (arg key how)
5010 ;; View crossreference of a ref cite. HOW can have the values
5011 ;; nil: Show in another window.
5012 ;; echo: Show one-line info in echo area.
5013 ;; tmp-window: Show in small window and arrange for window to disappear.
5014
5015 ;; Ensure access to scanning info
5016 (reftex-access-scan-info (or arg current-prefix-arg))
5017
5018 (let (files size item (pos (point)) (win (selected-window)) pop-win)
5019 ;; Find the citation mode and the file list
5020 (cond
5021 ((assq 'bib (symbol-value reftex-docstruct-symbol))
5022 (setq item nil
5023 files (reftex-get-bibfile-list)))
5024 ((assq 'thebib (symbol-value reftex-docstruct-symbol))
5025 (setq item t
5026 files (list (cdr (assq 'thebib
5027 (symbol-value reftex-docstruct-symbol))))))
5028 (reftex-default-bibliography
5029 (setq item nil
5030 files reftex-default-bibliography))
5031 (how) ;; don't throw for special display
5032 (t (error "Cannot display crossref")))
5033
5034 (if (eq how 'echo)
5035 ;; Display in Echo area
5036 (reftex-echo-cite key files item)
5037 ;; Display in a window
5038 (if (not (eq how 'tmp-window))
5039 ;; Normal display
5040 (reftex-pop-to-bibtex-entry key files nil t item)
5041 ;; A temporary window
5042 (condition-case nil
5043 (reftex-pop-to-bibtex-entry key files nil t item)
5044 (error (goto-char pos)
5045 (message "cite: no such citation key %s" key)
5046 (error "")))
5047 ;; Resize the window
5048 (setq size (max 1 (count-lines (point)
5049 (reftex-end-of-bib-entry item))))
5050 (let ((window-min-height 2))
5051 (shrink-window (1- (- (window-height) size)))
5052 (recenter 0))
5053 ;; Arrange restoration
5054 (add-hook 'pre-command-hook 'reftex-restore-window-conf))
5055
5056 ;; Normal display in other window
5057 (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
5058 (setq pop-win (selected-window))
5059 (select-window win)
5060 (goto-char pos)
5061 (when (equal arg 2)
5062 (select-window pop-win)))))
5063
5064 (defun reftex-view-cr-ref (arg label how)
5065 ;; View crossreference of a ref macro. HOW can have the values
5066 ;; nil: Show in another window.
5067 ;; echo: Show one-line info in echo area.
5068 ;; tmp-window: Show in small window and arrange for window to disappear.
5069
5070 ;; Ensure access to scanning info
5071 (reftex-access-scan-info (or arg current-prefix-arg))
5072
5073 (let* ((xr-data (assoc 'xr (symbol-value reftex-docstruct-symbol)))
5074 (xr-re (nth 2 xr-data))
5075 (entry (assoc label (symbol-value reftex-docstruct-symbol)))
5076 (win (selected-window)) pop-win (pos (point)))
5077
5078 (if (and (not entry) (stringp label) xr-re (string-match xr-re label))
5079 ;; Label is defined in external document
5080 (save-excursion
5081 (save-match-data
5082 (set-buffer
5083 (or (reftex-get-file-buffer-force
5084 (cdr (assoc (match-string 1 label) (nth 1
5085 xr-data))))
5086 (error "Problem with external label %s" label))))
5087 (setq label (substring label (match-end 1)))
5088 (reftex-access-scan-info)
5089 (setq entry
5090 (assoc label (symbol-value reftex-docstruct-symbol)))))
5091 (if (eq how 'echo)
5092 (reftex-echo-ref label entry (symbol-value reftex-docstruct-symbol))
5093 (unless entry
5094 (message "Label %s not known - reparse document might help" label))
5095
5096 (reftex-pop-to-label label (list (nth 3 entry)) nil t)
5097 (add-hook 'pre-command-hook 'reftex-highlight-shall-die)
5098
5099 (when (eq how 'tmp-window)
5100 ;; Resize window and arrange restauration
5101 (shrink-window (1- (- (window-height) 9)))
5102 (recenter '(4))
5103 (add-hook 'pre-command-hook 'reftex-restore-window-conf))
5104 (setq pop-win (selected-window))
5105 (select-window win)
5106 (goto-char pos)
5107 (when (equal arg 2)
5108 (select-window pop-win)))))
5109
5110 (defun reftex-mouse-view-crossref (ev)
5111 "View cross reference of \\ref or \\cite macro where you click.
5112 If the macro at point is a \\ref, show the corresponding label definition.
5113 If it is a \\cite, show the BibTeX database entry.
5114 If there is no such macro at point, search forward to find one.
5115 With argument, actually select the window showing the cross reference."
5116 (interactive "e")
5117 (mouse-set-point ev)
5118 (reftex-view-crossref current-prefix-arg))
5119
5120 (defvar reftex-auto-view-crossref-timer nil
5121 "The timer used for auto-view-crossref.")
5122
5123 (defun reftex-view-crossref-when-idle ()
5124 ;; Display info about crossref at point in echo area or a window.
5125 ;; This function was desigend to work with an idle timer.
5126 ;; We try to get out of here as quickly as possible if the call is useless.
5127 (and reftex-mode
5128 ;; Quick precheck if this might be a relevant spot
5129 ;; FIXME: failes with backslash in comment
5130 (save-excursion
5131 (search-backward "\\" nil t)
5132 (looking-at "\\\\[a-zA-Z]*\\(cite\\|ref\\)"))
5133 ;; Make sure message area is free if we need it.
5134 (or (eq reftex-auto-view-crossref 'window) (not (current-message)))
5135 ;; Make sure we are not already displaying this one
5136 (not (memq last-command '(reftex-view-crossref
5137 reftex-mouse-view-crossref)))
5138 (condition-case nil
5139 (let ((current-prefix-arg nil))
5140 (cond
5141 ((eq reftex-auto-view-crossref t)
5142 (reftex-view-crossref -1 'echo))
5143 ((eq reftex-auto-view-crossref 'window)
5144 (reftex-view-crossref -1 'tmp-window))
5145 (t nil)))
5146 (error nil))))
5147
5148 (defun reftex-restore-window-conf ()
5149 (set-window-configuration (get 'reftex-auto-view-crossref 'last-window-conf))
5150 (put 'reftex-auto-view-crossref 'last-window-conf nil)
5151 (remove-hook 'pre-command-hook 'reftex-restore-window-conf))
5152
5153 (defun reftex-echo-ref (label entry docstruct)
5154 ;; Display crossref info in echo area.
5155 (cond
5156 ((null docstruct)
5157 (message (substitute-command-keys (format reftex-no-info-message "ref"))))
5158 ((null entry)
5159 (message "ref: unknown label: %s" label))
5160 (t
5161 (when (stringp (nth 2 entry))
5162 (message "ref(%s): %s" (nth 1 entry) (nth 2 entry)))
5163 (let ((buf (get-buffer " *Echo Area*")))
5164 (when buf
5165 (save-excursion
5166 (set-buffer buf)
5167 (run-hooks 'reftex-display-copied-context-hook)))))))
5168
5169 (defun reftex-echo-cite (key files item)
5170 ;; Display citation info in echo area.
5171 (let* ((cache (assq 'bibview-cache (symbol-value reftex-docstruct-symbol)))
5172 (cache-entry (assoc key (cdr cache)))
5173 entry string buf (all-files files))
5174
5175 (if (and reftex-cache-cite-echo cache-entry)
5176 ;; We can just use the cache
5177 (setq string (cdr cache-entry))
5178
5179 ;; Need to look in the database
5180 (unless reftex-revisit-to-echo
5181 (setq files (reftex-visited-files files)))
5182
5183 (setq entry
5184 (condition-case nil
5185 (save-excursion
5186 (reftex-pop-to-bibtex-entry key files nil nil item t))
5187 (error
5188 (if (and files (= (length all-files) (length files)))
5189 (message "cite: no such database entry: %s" key)
5190 (message (substitute-command-keys
5191 (format reftex-no-info-message "cite"))))
5192 nil)))
5193 (when entry
5194 (if item
5195 (setq string (reftex-nicify-text entry))
5196 (setq string (reftex-make-cite-echo-string
5197 (reftex-parse-bibtex-entry entry)
5198 reftex-docstruct-symbol)))))
5199 (unless (or (null string) (equal string ""))
5200 (message "cite: %s" string))
5201 (when (setq buf (get-buffer " *Echo Area*"))
5202 (save-excursion
5203 (set-buffer buf)
5204 (run-hooks 'reftex-display-copied-context-hook)))))
5205
5206 (defun reftex-make-cite-echo-string (entry docstruct-symbol)
5207 ;; Format a bibtex entry for the echo area and cache the result.
5208 (let* ((key (reftex-get-bib-field "&key" entry))
5209 (string
5210 (let* ((reftex-cite-punctuation '(" " " & " " etal.")))
5211 (reftex-format-citation entry reftex-cite-view-format)))
5212 (cache (assq 'bibview-cache (symbol-value docstruct-symbol)))
5213 (cache-entry (assoc key (cdr cache))))
5214 (unless cache
5215 ;; This docstruct has no cache - make one.
5216 (set docstruct-symbol (cons (cons 'bibview-cache nil)
5217 (symbol-value docstruct-symbol))))
5218 (when reftex-cache-cite-echo
5219 (setq key (copy-sequence key))
5220 (set-text-properties 0 (length key) nil key)
5221 (set-text-properties 0 (length string) nil string)
5222 (if cache-entry
5223 (unless (string= (cdr cache-entry) string)
5224 (setcdr cache-entry string)
5225 (put reftex-docstruct-symbol 'modified t))
5226 (push (cons key string) (cdr cache))
5227 (put reftex-docstruct-symbol 'modified t)))
5228 string))
5229
5230 (defvar reftex-use-itimer-in-xemacs nil
5231 "*Non-nil means use the idle timers in XEmacs for crossref display.
5232 Currently, idle timer restart is broken and we use the post-command-hook.")
5233
5234 (defun reftex-toggle-auto-view-crossref ()
5235 "Toggle the automatic display of crossref information in the echo area.
5236 When active, leaving point idle in the argument of a \\ref or \\cite macro
5237 will display info in the echo area."
5238 (interactive)
5239 (if reftex-auto-view-crossref-timer
5240 (progn
5241 (if (featurep 'xemacs)
5242 (if reftex-use-itimer-in-xemacs
5243 (delete-itimer reftex-auto-view-crossref-timer)
5244 (remove-hook 'post-command-hook 'reftex-start-itimer-once))
5245 (cancel-timer reftex-auto-view-crossref-timer))
5246 (setq reftex-auto-view-crossref-timer nil)
5247 (message "Automatic display of crossref information was turned off"))
5248 (setq reftex-auto-view-crossref-timer
5249 (if (featurep 'xemacs)
5250 (if reftex-use-itimer-in-xemacs
5251 (start-itimer "RefTeX Idle Timer"
5252 'reftex-view-crossref-when-idle
5253 reftex-idle-time reftex-idle-time t)
5254 (add-hook 'post-command-hook 'reftex-start-itimer-once)
5255 nil)
5256 (run-with-idle-timer
5257 reftex-idle-time t 'reftex-view-crossref-when-idle)))
5258 (unless reftex-auto-view-crossref
5259 (setq reftex-auto-view-crossref t))
5260 (message "Automatic display of crossref information was turned on")))
5261
5262 (defun reftex-start-itimer-once ()
5263 (and reftex-mode
5264 (not (itimer-live-p reftex-auto-view-crossref-timer))
5265 (setq reftex-auto-view-crossref-timer
5266 (start-itimer "RefTeX Idle Timer"
5267 'reftex-view-crossref-when-idle
5268 reftex-idle-time nil t))))
5269
5270 ;;; =========================================================================
5271 ;;;
5272 ;;; Functions that check out the surroundings
5273
5274 (defun reftex-what-macro (which &optional bound)
5275 ;; Find out if point is within the arguments of any TeX-macro.
5276 ;; The return value is either ("\\macro" . (point)) or a list of them.
5277
5278 ;; If WHICH is nil, immediately return nil.
5279 ;; If WHICH is 1, return innermost enclosing macro.
5280 ;; If WHICH is t, return list of all macros enclosing point.
5281 ;; If WHICH is a list of macros, look only for those macros and return the
5282 ;; name of the first macro in this list found to enclose point.
5283 ;; If the optional BOUND is an integer, bound backwards directed
5284 ;; searches to this point. If it is nil, limit to nearest \section -
5285 ;; like statement.
5286
5287 ;; This function is pretty stable, but can be fooled if the text contains
5288 ;; things like \macro{aa}{bb} where \macro is defined to take only one
5289 ;; argument. As RefTeX cannot know this, the string "bb" would still be
5290 ;; considered an argument of macro \macro.
5291
5292 (unless reftex-section-regexp (reftex-compile-variables))
5293 (catch 'exit
5294 (if (null which) (throw 'exit nil))
5295 (let ((bound (or bound (save-excursion (re-search-backward
5296 reftex-section-regexp nil 1)
5297 (point))))
5298 pos cmd-list cmd cnt cnt-opt entry)
5299 (save-restriction
5300 (save-excursion
5301 (narrow-to-region (max 1 bound) (point-max))
5302 ;; move back out of the current parenthesis
5303 (while (condition-case nil
5304 (progn (up-list -1) t)
5305 (error nil))
5306 (setq cnt 1 cnt-opt 0)
5307 ;; move back over any touching sexps
5308 (while (and (reftex-move-to-previous-arg bound)
5309 (condition-case nil
5310 (progn (backward-sexp) t)
5311 (error nil)))
5312 (if (eq (following-char) ?\[) (incf cnt-opt))
5313 (incf cnt))
5314 (setq pos (point))
5315 (when (and (or (= (following-char) ?\[)
5316 (= (following-char) ?\{))
5317 (re-search-backward "\\\\[*a-zA-Z]+\\=" nil t))
5318 (setq cmd (reftex-match-string 0))
5319 (when (looking-at "\\\\begin{[^}]*}")
5320 (setq cmd (reftex-match-string 0)
5321 cnt (1- cnt)))
5322 ;; This does ignore optional arguments. Very hard to fix.
5323 (when (setq entry (assoc cmd reftex-env-or-mac-alist))
5324 (if (> cnt (or (nth 4 entry) 100))
5325 (setq cmd nil)))
5326 (cond
5327 ((null cmd))
5328 ((eq t which)
5329 (push (cons cmd (point)) cmd-list))
5330 ((or (eq 1 which) (member cmd which))
5331 (throw 'exit (cons cmd (point))))))
5332 (goto-char pos)))
5333 (nreverse cmd-list)))))
5334
5335 (defun reftex-what-environment (which &optional bound)
5336 ;; Find out if point is inside a LaTeX environment.
5337 ;; The return value is (e.g.) either ("equation" . (point)) or a list of
5338 ;; them.
5339
5340 ;; If WHICH is nil, immediately return nil.
5341 ;; If WHICH is 1, return innermost enclosing environment.
5342 ;; If WHICH is t, return list of all environments enclosing point.
5343 ;; If WHICH is a list of environments, look only for those environments and
5344 ;; return the name of the first environment in this list found to enclose
5345 ;; point.
5346
5347 ;; If the optional BOUND is an integer, bound backwards directed searches to
5348 ;; this point. If it is nil, limit to nearest \section - like statement.
5349
5350 (unless reftex-section-regexp (reftex-compile-variables))
5351 (catch 'exit
5352 (save-excursion
5353 (if (null which) (throw 'exit nil))
5354 (let ((bound (or bound (save-excursion (re-search-backward
5355 reftex-section-regexp nil 1)
5356 (point))))
5357 env-list end-list env)
5358 (while (re-search-backward "\\\\\\(begin\\|end\\){\\([^}]+\\)}"
5359 bound t)
5360 (setq env (buffer-substring-no-properties
5361 (match-beginning 2) (match-end 2)))
5362 (cond
5363 ((string= (match-string 1) "end")
5364 (add-to-list 'end-list env))
5365 ((member env end-list)
5366 (setq end-list (delete env end-list)))
5367 ((eq t which)
5368 (push (cons env (point)) env-list))
5369 ((or (eq 1 which) (member env which))
5370 (throw 'exit (cons env (point))))))
5371 (nreverse env-list)))))
5372
5373 ;;; =========================================================================
5374 ;;;
5375 ;;; Finding files
5376
5377 (defun reftex-find-tex-file (file master-dir &optional die)
5378 ;; Find FILE in MASTER-DIR or on reftex-tex-path.
5379 ;; FILE may be given with or without the .tex extension.
5380 (let ((rec-values (if reftex-search-unrecursed-path-first '(nil t) '(t)))
5381 path file1 old-path)
5382 (cond
5383 ((file-name-absolute-p file)
5384 (if (file-regular-p (concat file ".tex"))
5385 (setq file1 (concat file ".tex"))
5386 (if (file-regular-p file) (setq file1 file))))
5387 ((and reftex-use-external-file-finders
5388 (assoc "tex" reftex-external-file-finders))
5389 (setq file1 (reftex-find-file-externally file "tex" master-dir)))
5390 (t
5391 (while (and (null file1) rec-values)
5392 (setq path (reftex-access-search-path
5393 "tex" (pop rec-values) master-dir file))
5394 (if (or (null old-path)
5395 (not (eq old-path path)))
5396 (setq old-path path
5397 path (cons master-dir path)
5398 file1 (or (reftex-find-file-on-path
5399 (concat file ".tex") path master-dir)
5400 (reftex-find-file-on-path file path master-dir)))))))
5401 (cond (file1 file1)
5402 (die (error "No such file: %s" file) nil)
5403 (t (message "No such file: %s (ignored)" file) nil))))
5404
5405 (defun reftex-find-bib-file (file master-dir &optional die)
5406 ;; Find FILE in MASTER-DIR or on reftex-bib-path.
5407 ;; File must be given already with the .bib extension.
5408 (let ((rec-values (if reftex-search-unrecursed-path-first '(nil t) '(t)))
5409 path file1 old-path)
5410 (cond
5411 ((file-name-absolute-p file)
5412 (if (file-regular-p file) (setq file1 file)))
5413 ((and reftex-use-external-file-finders
5414 (assoc "bib" reftex-external-file-finders))
5415 (setq file1 (reftex-find-file-externally file "bib" master-dir)))
5416 (t
5417 (while (and (null file1) rec-values)
5418 (setq path (reftex-access-search-path
5419 "bib" (pop rec-values) master-dir file))
5420 (if (or (null old-path)
5421 (not (eq old-path path)))
5422 (setq old-path path
5423 path (cons master-dir path)
5424 file1 (reftex-find-file-on-path file path master-dir))))))
5425 (cond (file1 file1)
5426 (die (error "No such file: %s" file) nil)
5427 (t (message "No such file: %s (ignored)" file) nil))))
5428
5429 (defun reftex-find-file-externally (file type &optional master-dir)
5430 ;; Use external program to find FILE.
5431 ;; The program is the association of TYPE in `reftex-external-file-finders'.
5432 ;; Interprete relative path definitions starting from MASTER-DIR.
5433 (let ((default-directory (or master-dir default-directory))
5434 (prg (cdr (assoc type reftex-external-file-finders)))
5435 out)
5436 (if (string-match "%f" prg)
5437 (setq prg (replace-match file t t prg)))
5438 (setq out (apply 'reftex-process-string (split-string prg)))
5439 (if (string-match "[ \t\n]+\\'" out)
5440 (setq out (replace-match "" nil nil out)))
5441 (cond ((equal out "") nil)
5442 ((file-regular-p out) out)
5443 (t nil))))
5444
5445 (defun reftex-process-string (program &rest args)
5446 "Execute PROGRAM with arguments ARGS and return its STDOUT as a string."
5447 (with-output-to-string
5448 (with-current-buffer
5449 standard-output
5450 (apply 'call-process program nil '(t nil) nil args))))
5451
5452 (defun reftex-access-search-path (which &optional recurse master-dir file)
5453 ;; Access path from environment variables. WHICH is either "tex" or "bib".
5454 ;; When RECURSE is t, expand path elements ending in `//' recursively.
5455 ;; Relative path elements are left as they are. However, relative recursive
5456 ;; elements are expanded with MASTER-DIR as default directory.
5457 ;; The expanded path is cached for the next search.
5458 ;; FILE is just for the progress message.
5459 ;; Returns the derived path.
5460 (let* ((pathvar (intern (concat "reftex-" which "-path"))))
5461 (when (null (get pathvar 'status))
5462 ;; Get basic path from environment
5463 (let ((env-vars (if (equal which "tex")
5464 reftex-texpath-environment-variables
5465 reftex-bibpath-environment-variables)))
5466 (set pathvar
5467 (reftex-parse-colon-path
5468 (mapconcat
5469 (lambda(x)
5470 (if (string-match "^!" x)
5471 (apply 'reftex-process-string
5472 (split-string (substring x 1)))
5473 (or (getenv x) x)))
5474 env-vars path-separator))))
5475 (put pathvar 'status 'split)
5476 ;; Check if we have recursive elements
5477 (let ((path (symbol-value pathvar)) dir rec)
5478 (while (setq dir (pop path))
5479 (when (string= (substring dir -2) "//")
5480 (if (file-name-absolute-p dir)
5481 (setq rec (or rec 'absolute))
5482 (setq rec 'relative))))
5483 (put pathvar 'rec-type rec)))
5484
5485 (if recurse
5486 ;; Return the recursive expansion of the path
5487 (cond
5488 ((not (get pathvar 'rec-type))
5489 ;; Path does not contain recursive elements - use simple path
5490 (symbol-value pathvar))
5491 ((or (not (get pathvar 'recursive-path))
5492 (and (eq (get pathvar 'rec-type) 'relative)
5493 (not (equal master-dir (get pathvar 'master-dir)))))
5494 ;; Either: We don't have a recursive expansion yet.
5495 ;; or: Relative recursive path elements need to be expanded
5496 ;; relative to new default directory
5497 (message "Expanding search path to find %s file: %s ..." which file)
5498 (put pathvar 'recursive-path
5499 (reftex-expand-path (symbol-value pathvar) master-dir))
5500 (put pathvar 'master-dir master-dir)
5501 (get pathvar 'recursive-path))
5502 (t
5503 ;; Recursive path computed earlier is still OK.
5504 (get pathvar 'recursive-path)))
5505 ;; The simple path was requested
5506 (symbol-value pathvar))))
5507
5508 (defun reftex-find-file-on-path (file path &optional def-dir)
5509 ;; Find FILE along the directory list PATH.
5510 ;; DEF-DIR is the default directory for expanding relative path elements.
5511 (catch 'exit
5512 (when (file-name-absolute-p file)
5513 (if (file-regular-p file)
5514 (throw 'exit file)
5515 (throw 'exit nil)))
5516 (let* ((thepath path) file1 dir )
5517 (while (setq dir (pop thepath))
5518 (when (string= (substring dir -2) "//")
5519 (setq dir (substring dir 0 -1)))
5520 (setq file1 (expand-file-name file (expand-file-name dir def-dir)))
5521 (if (file-regular-p file1)
5522 (throw 'exit file1)))
5523 ;; No such file
5524 nil)))
5525
5526 (defun reftex-parse-colon-path (path)
5527 ;; Like parse-colon-parse, but // or /~ are left alone.
5528 ;; Trailing ! or !! will be converted into `//' (emTeX convention)
5529 (mapcar
5530 (lambda (dir)
5531 (if (string-match "\\(//+\\|/*!+\\)\\'" dir)
5532 (setq dir (replace-match "//" t t dir)))
5533 (file-name-as-directory dir))
5534 (delete "" (split-string path (concat path-separator "+")))))
5535
5536 (defun reftex-expand-path (path &optional default-dir)
5537 ;; Expand parts of path ending in `//' recursively into directory list.
5538 ;; Relative recursive path elements are expanded relative to DEFAULT-DIR.
5539 (let (path1 dir recursive)
5540 (while (setq dir (pop path))
5541 (if (setq recursive (string= (substring dir -2) "//"))
5542 (setq dir (substring dir 0 -1)))
5543 (if (and recursive
5544 (not (file-name-absolute-p dir)))
5545 (setq dir (expand-file-name dir default-dir)))
5546 (if recursive
5547 ;; Expand recursively
5548 (setq path1 (append (reftex-recursive-directory-list dir) path1))
5549 ;; Keep unchanged
5550 (push dir path1)))
5551 (nreverse path1)))
5552
5553 (defun reftex-recursive-directory-list (dir)
5554 ;; Return a list of all directories below DIR, including DIR itself
5555 (let ((path (list dir)) path1 file files)
5556 (while (setq dir (pop path))
5557 (when (file-directory-p dir)
5558 (setq files (nreverse (directory-files dir t "[^.]")))
5559 (while (setq file (pop files))
5560 (if (file-directory-p file)
5561 (push (file-name-as-directory file) path)))
5562 (push dir path1)))
5563 path1))
5564
5565 ;;; =========================================================================
5566 ;;;
5567 ;;; Some generally useful functions
5568
5569 (defun reftex-no-props (string)
5570 ;; Return STRING with all text properties removed
5571 (and (stringp string)
5572 (set-text-properties 0 (length string) nil string))
5573 string)
5574
5575 (defun reftex-match-string (n)
5576 ;; Match string without properties
5577 (when (match-beginning n)
5578 (buffer-substring-no-properties (match-beginning n) (match-end n))))
5579
5580 (defun reftex-kill-buffer (buffer)
5581 ;; Kill buffer if it exists.
5582 (and (setq buffer (get-buffer buffer))
5583 (kill-buffer buffer)))
5584
5585 (defun reftex-erase-buffer (&optional buffer)
5586 ;; Erase BUFFER if it exists. BUFFER defaults to current buffer.
5587 ;; This even erases read-only buffers.
5588 (cond
5589 ((null buffer)
5590 ;; erase current buffer
5591 (let ((buffer-read-only nil)) (erase-buffer)))
5592 ((setq buffer (get-buffer buffer))
5593 ;; buffer exists
5594 (save-excursion
5595 (set-buffer buffer)
5596 (let ((buffer-read-only nil)) (erase-buffer))))))
5597
5598 (defun reftex-this-word (&optional class)
5599 ;; Grab the word around point.
5600 (setq class (or class "-a-zA-Z0-9:_/.*;|"))
5601 (save-excursion
5602 (buffer-substring-no-properties
5603 (progn (skip-chars-backward class) (point))
5604 (progn (skip-chars-forward class) (point)))))
5605
5606 (defun reftex-all-assq (key list)
5607 ;; Return a list of all associations of KEY in LIST. Comparison with eq.
5608 (let (rtn)
5609 (while (setq list (memq (assq key list) list))
5610 (push (car list) rtn)
5611 (pop list))
5612 (nreverse rtn)))
5613
5614 (defun reftex-all-assoc-string (key list)
5615 ;; Return a list of all associations of KEY in LIST. Comparison with string=.
5616 (let (rtn)
5617 (while list
5618 (if (string= (car (car list)) key)
5619 (push (car list) rtn))
5620 (pop list))
5621 (nreverse rtn)))
5622
5623 (defun reftex-last-assoc-before-elt (key elt list)
5624 ;; Find the last association of KEY in LIST before or at ELT
5625 ;; ELT is found in LIST with equal, not eq.
5626 ;; Returns nil when either KEY or elt are not found in LIST.
5627 ;; On success, returns the association.
5628 (let* ((elt (car (member elt list))) ass last-ass)
5629
5630 (while (and (setq ass (assoc key list))
5631 (setq list (memq ass list))
5632 (memq elt list))
5633 (setq last-ass ass
5634 list (cdr list)))
5635 last-ass))
5636
5637 (defvar enable-multibyte-characters)
5638 (defun reftex-truncate (string ncols &optional ellipses padding)
5639 ;; Truncate a string to NCHAR characters.
5640 ;; Works fast with ASCII and correctly with Mule characters.
5641 ;; When ELLIPSES is non-nil, put three dots at the end of the string.
5642 ;; When padding is non-nil, fills with white space to NCOLS characters.
5643 (setq string
5644 (cond
5645 ((and (boundp 'enable-multibyte-characters)
5646 enable-multibyte-characters
5647 (fboundp 'string-width)
5648 (fboundp 'truncate-string-to-width))
5649 (if (<= (string-width string) ncols)
5650 string
5651 (if ellipses
5652 (concat (truncate-string-to-width string (- ncols 3)) "...")
5653 (truncate-string-to-width string ncols))))
5654 (t
5655 (if (<= (length string) ncols)
5656 string
5657 (if ellipses
5658 (concat (substring string 0 (- ncols 3)) "...")
5659 (substring string 0 ncols))))))
5660 (if padding
5661 (format (format "%%-%ds" ncols) string)
5662 string))
5663
5664 (defun reftex-nearest-match (regexp &optional pos)
5665 ;; Find the nearest match of REGEXP. Set the match data.
5666 ;; If POS is given, calculate distances relative to it.
5667 ;; Return nil if there is no match.
5668 (let ((start (point)) (pos (or pos (point))) match1 match2 match)
5669 (goto-char start)
5670 (when (re-search-backward regexp nil t)
5671 (setq match1 (match-data)))
5672 (goto-char start)
5673 (when (re-search-forward regexp nil t)
5674 (setq match2 (match-data)))
5675 (goto-char start)
5676 (setq match
5677 (cond
5678 ((not match1) match2)
5679 ((not match2) match1)
5680 ((< (abs (- pos (car match1))) (abs (- pos (car match2)))) match1)
5681 (t match2)))
5682 (if match (progn (set-match-data match) t) nil)))
5683
5684 (defun reftex-auto-mode-alist ()
5685 ;; Return an `auto-mode-alist' with only the .gz (etc) thingies.
5686 ;; Stolen from gnus nnheader.
5687 (let ((alist auto-mode-alist)
5688 out)
5689 (while alist
5690 (when (listp (cdr (car alist)))
5691 (push (car alist) out))
5692 (pop alist))
5693 (nreverse out)))
5694
5695 (defun reftex-enlarge-to-fit (buf2 &optional keep-current)
5696 ;; Enlarge other window displaying buffer to show whole buffer if possible.
5697 ;; If KEEP-CURRENT in non-nil, current buffer must remain visible.
5698 (let* ((win1 (selected-window))
5699 (buf1 (current-buffer))
5700 (win2 (get-buffer-window buf2)))
5701 (when win2
5702 (select-window win2)
5703 (unless (and (pos-visible-in-window-p 1)
5704 (pos-visible-in-window-p (point-max)))
5705 (enlarge-window (1+ (- (count-lines 1 (point-max))
5706 (window-height))))))
5707 (cond
5708 ((window-live-p win1) (select-window win1))
5709 (keep-current
5710 ;; we must have the old buffer!
5711 (switch-to-buffer-other-window buf1)
5712 (shrink-window (- (window-height) window-min-height))))))
5713
5714 (defun reftex-select-with-char (prompt help-string &optional delay-time scroll)
5715 ;; Offer to select something with PROMPT and, after DELAY-TIME seconds,
5716 ;; also with HELP-STRING.
5717 ;; When SCROLL is non-nil, use SPC and DEL to scroll help window.
5718 (let ((char ?\?))
5719 (save-window-excursion
5720 (catch 'exit
5721 (message (concat prompt " (?=Help)"))
5722 (when (or (sit-for (or delay-time 0))
5723 (= ?\? (setq char (read-char-exclusive))))
5724 (with-output-to-temp-buffer " *RefTeX Help*"
5725 (princ help-string))
5726 (reftex-enlarge-to-fit " *RefTeX Help*")
5727 (select-window (get-buffer-window " *RefTeX Help*"))
5728 (setq truncate-lines t))
5729 (setq prompt (concat prompt (if scroll " (SPC/DEL=Scroll)" "")))
5730 (message prompt)
5731 (and (equal char ?\?) (setq char (read-char-exclusive)))
5732 (while t
5733 (cond ((equal char ?\C-g) (keyboard-quit))
5734 ((equal char ?\?))
5735 ((and scroll (equal char ?\ ))
5736 (condition-case nil (scroll-up) (error nil))
5737 (message prompt))
5738 ((and scroll (equal char ?\C-? ))
5739 (condition-case nil (scroll-down) (error nil))
5740 (message prompt))
5741 (t (throw 'exit char)))
5742 (setq char (read-char-exclusive)))))))
5743
5744 (defun reftex-make-regexp-allow-for-ctrl-m (string)
5745 ;; convert STRING into a regexp, allowing ^M for \n and vice versa
5746 (let ((start -2))
5747 (setq string (regexp-quote string))
5748 (while (setq start (string-match "[\n\r]" string (+ 3 start)))
5749 (setq string (replace-match "[\n\r]" nil t string)))
5750 string))
5751
5752 (defun reftex-get-buffer-visiting (file)
5753 ;; return a buffer visiting FILE
5754 (cond
5755 ((boundp 'find-file-compare-truenames) ; XEmacs
5756 (let ((find-file-compare-truenames t))
5757 (get-file-buffer file)))
5758 ((fboundp 'find-buffer-visiting) ; Emacs
5759 (find-buffer-visiting file))
5760 (t (error "This should not happen (reftex-get-buffer-visiting)"))))
5761
5762 ;; Define `current-message' for compatibility with XEmacs prior to 20.4
5763 (defvar message-stack)
5764 (if (and (featurep 'xemacs)
5765 (not (fboundp 'current-message)))
5766 (defun current-message (&optional frame)
5767 (cdr (car message-stack))))
5768
5769 (defun reftex-visited-files (list)
5770 ;; Takes a list of filenames and returns the buffers of those already visited
5771 (delq nil (mapcar (lambda (x) (if (reftex-get-buffer-visiting x) x nil))
5772 list)))
5773
5774 (defun reftex-get-file-buffer-force (file &optional mark-to-kill)
5775 ;; Return a buffer visiting file. Make one, if necessary.
5776 ;; If neither such a buffer nor the file exist, return nil.
5777 ;; If MARK-TO-KILL is t and there is no live buffer, visit the file with
5778 ;; initializations according to `reftex-initialize-temporary-buffers',
5779 ;; and mark the buffer to be killed after use.
5780
5781 (let ((buf (reftex-get-buffer-visiting file)))
5782
5783 (cond (buf
5784 ;; We have it already as a buffer - just return it
5785 buf)
5786
5787 ((file-readable-p file)
5788 ;; At least there is such a file and we can read it.
5789
5790 (if (or (not mark-to-kill)
5791 (eq t reftex-initialize-temporary-buffers))
5792
5793 ;; Visit the file with full magic
5794 (setq buf (find-file-noselect file))
5795
5796 ;; Else: Visit the file just briefly, without or
5797 ;; with limited Magic
5798
5799 ;; The magic goes away
5800 (let ((format-alist nil)
5801 (auto-mode-alist (reftex-auto-mode-alist))
5802 (default-major-mode 'fundamental-mode)
5803 (enable-local-variables nil)
5804 (after-insert-file-functions nil))
5805 (setq buf (find-file-noselect file)))
5806
5807 ;; Is there a hook to run?
5808 (when (listp reftex-initialize-temporary-buffers)
5809 (save-excursion
5810 (set-buffer buf)
5811 (run-hooks 'reftex-initialize-temporary-buffers))))
5812
5813 ;; Lets see if we got a license to kill :-|
5814 (and mark-to-kill
5815 (add-to-list 'reftex-buffers-to-kill buf))
5816
5817 ;; Return the new buffer
5818 buf)
5819
5820 ;; If no such file exists, return nil
5821 (t nil))))
5822
5823 (defun reftex-kill-temporary-buffers (&optional buffer)
5824 ;; Kill all buffers in the list reftex-kill-temporary-buffers.
5825 (cond
5826 (buffer
5827 (when (member buffer reftex-buffers-to-kill)
5828 (kill-buffer buffer)
5829 (setq reftex-buffers-to-kill
5830 (delete buffer reftex-buffers-to-kill))))
5831 (t
5832 (while (setq buffer (pop reftex-buffers-to-kill))
5833 (when (bufferp buffer)
5834 (and (buffer-modified-p buffer)
5835 (y-or-n-p (format "Save file %s? "
5836 (buffer-file-name buffer)))
5837 (save-excursion
5838 (set-buffer buffer)
5839 (save-buffer)))
5840 (kill-buffer buffer))
5841 (pop reftex-buffers-to-kill)))))
5842
5843 (defun reftex-splice-symbols-into-list (list alist)
5844 ;; Splice the association in ALIST of any symbols in LIST into the list.
5845 ;; Return new list.
5846 (let (rtn tmp)
5847 (while list
5848 (while (and (not (null (car list))) ;; keep list elements nil
5849 (symbolp (car list)))
5850 (setq tmp (car list))
5851 (cond
5852 ((assoc tmp alist)
5853 (setq list (append (nth 2 (assoc tmp alist)) (cdr list))))
5854 (t
5855 (error "Cannot treat symbol %s in reftex-label-alist"
5856 (symbol-name tmp)))))
5857 (push (pop list) rtn))
5858 (nreverse rtn)))
5859
5860 (defun reftex-uniquify-by-car (alist &optional keep-list)
5861 ;; Return a list of all elements in ALIST, but each car only once.
5862 ;; Elements of KEEP-LIST are not removed even if duplicate.
5863 (let (new elm)
5864 (while alist
5865 (setq elm (pop alist))
5866 (if (or (member (car elm) keep-list)
5867 (not (assoc (car elm) new)))
5868 (push elm new)))
5869 (nreverse new)))
5870
5871 ;;; =========================================================================
5872 ;;;
5873 ;;; Fontification and Highlighting
5874
5875 (defun reftex-use-fonts ()
5876 ;; Return t if we can and want to use fonts.
5877 (and window-system
5878 reftex-use-fonts
5879 (featurep 'font-lock)))
5880
5881 (defun reftex-refontify ()
5882 ;; Return t if we need to refontify context
5883 (and (reftex-use-fonts)
5884 (or (eq t reftex-refontify-context)
5885 (and (eq 1 reftex-refontify-context)
5886 ;; Test of we use the font-lock version of x-symbol
5887 (and (featurep 'x-symbol-tex) (not (boundp 'x-symbol-mode)))))))
5888
5889 (defun reftex-fontify-select-label-buffer (parent-buffer)
5890 ;; Fontify the `*RefTeX Select*' buffer. Buffer is temporarily renamed to
5891 ;; start with none-SPC char, beacuse Font-Lock otherwise refuses operation.
5892 (run-hook-with-args 'reftex-pre-refontification-functions
5893 parent-buffer 'reftex-ref)
5894 (let* ((oldname (buffer-name))
5895 (newname (concat "Fontify-me-" oldname)))
5896 (unwind-protect
5897 (progn
5898 ;; Rename buffer temporarily to start w/o space (because of font-lock)
5899 (rename-buffer newname t)
5900 (cond
5901 ((fboundp 'font-lock-default-fontify-region)
5902 ;; Good: we have the indirection functions
5903 (set (make-local-variable 'font-lock-fontify-region-function)
5904 'reftex-select-font-lock-fontify-region)
5905 (let ((major-mode 'latex-mode))
5906 (font-lock-mode 1)))
5907 ((fboundp 'font-lock-set-defaults-1)
5908 ;; Looks like the XEmacs font-lock stuff.
5909 ;; FIXME: this is still kind of a hack.
5910 (set (make-local-variable 'font-lock-keywords) nil)
5911 (let ((major-mode 'latex-mode)
5912 (font-lock-defaults-computed nil))
5913 (font-lock-set-defaults-1)
5914 (reftex-select-font-lock-fontify-region (point-min) (point-max))))
5915 (t
5916 ;; Oops?
5917 (message "Sorry: cannot refontify RefTeX Select buffer."))))
5918 (rename-buffer oldname))))
5919
5920 (defun reftex-select-font-lock-fontify-region (beg end &optional loudly)
5921 ;; Fontify a region, but only lines starting with a dot.
5922 (let ((func (if (fboundp 'font-lock-default-fontify-region)
5923 'font-lock-default-fontify-region
5924 'font-lock-fontify-region))
5925 beg1 end1)
5926 (goto-char beg)
5927 (while (re-search-forward "^\\." end t)
5928 (setq beg1 (point) end1 (progn (skip-chars-forward "^\n") (point)))
5929 (funcall func beg1 end1 nil)
5930 (goto-char end1))))
5931
5932 (defun reftex-select-font-lock-unfontify (&rest ignore) t)
5933
5934 (defun reftex-verified-face (&rest faces)
5935 ;; Return the first valid face in FACES, or nil if none is valid.
5936 ;; Also, when finding a nil element in FACES, return nil. This
5937 ;; function is just a safety net to catch name changes of builtin
5938 ;; fonts. Currently it is only used for reftex-label-face, which has
5939 ;; as default font-lock-reference-face, which was recently renamed
5940 ;; to font-lock-constant-face.
5941 (let (face)
5942 (catch 'exit
5943 (while (setq face (pop faces))
5944 (if (featurep 'xemacs)
5945 (if (find-face face) (throw 'exit face))
5946 (if (facep face) (throw 'exit face)))))))
5947
5948 ;; Highlighting uses overlays. For XEmacs, we need the emulation.
5949 (if (featurep 'xemacs) (require 'overlay))
5950
5951 ;; We keep a vector with several different overlays to do our highlighting.
5952 (defvar reftex-highlight-overlays [nil nil])
5953
5954 ;; Initialize the overlays
5955 (aset reftex-highlight-overlays 0 (make-overlay 1 1))
5956 (overlay-put (aref reftex-highlight-overlays 0)
5957 'face 'highlight)
5958 (aset reftex-highlight-overlays 1 (make-overlay 1 1))
5959 (overlay-put (aref reftex-highlight-overlays 1)
5960 'face reftex-cursor-selected-face)
5961
5962 ;; Two functions for activating and deactivation highlight overlays
5963 (defun reftex-highlight (index begin end &optional buffer)
5964 "Highlight a region with overlay INDEX."
5965 (move-overlay (aref reftex-highlight-overlays index)
5966 begin end (or buffer (current-buffer))))
5967 (defun reftex-unhighlight (index)
5968 "Detach overlay INDEX."
5969 (delete-overlay (aref reftex-highlight-overlays index)))
5970
5971 (defun reftex-highlight-shall-die ()
5972 ;; Function used in pre-command-hook to remove highlights.
5973 (remove-hook 'pre-command-hook 'reftex-highlight-shall-die)
5974 (reftex-unhighlight 0))
5975
5976 ;;; =========================================================================
5977 ;;;
5978 ;;; Functions to compile the tables, reset the mode etc.
5979
5980 ;; A list of all variables in the cache.
5981 ;; The cache is used to save the compiled versions of some variables.
5982 (defconst reftex-cache-variables
5983 '(reftex-memory ;; This MUST ALWAYS be the first!
5984 reftex-env-or-mac-alist reftex-everything-regexp
5985 reftex-find-label-regexp-format reftex-find-label-regexp-format2
5986 reftex-label-env-list reftex-label-mac-list
5987 reftex-section-or-include-regexp reftex-section-levels-all
5988 reftex-section-regexp reftex-type-query-help
5989 reftex-type-query-prompt reftex-typekey-list
5990 reftex-typekey-to-format-alist reftex-typekey-to-prefix-alist
5991 reftex-words-to-typekey-alist))
5992
5993 (defun reftex-ensure-compiled-variables ()
5994 ;; Recompile the label alist when necessary
5995 (let* ((mem reftex-memory)
5996 (cache (get reftex-docstruct-symbol 'reftex-cache))
5997 (cmem (car cache))
5998 (alist reftex-label-alist)
5999 (levels (get reftex-docstruct-symbol 'reftex-section-levels))
6000 (style (get reftex-docstruct-symbol 'reftex-label-alist-style))
6001 (default reftex-default-label-alist-entries))
6002 (cond
6003 (reftex-tables-dirty (reftex-compile-variables))
6004 ((and (eq alist (nth 0 mem))
6005 (eq levels (nth 1 mem))
6006 (eq style (nth 2 mem))
6007 (eq default (nth 3 mem)))) ;; everything is OK
6008 ((and (eq alist (nth 0 cmem))
6009 (eq levels (nth 1 cmem))
6010 (eq style (nth 2 cmem))
6011 (eq default (nth 2 cmem)))
6012 ;; restore the cache
6013 (message "Restoring cache")
6014 (mapcar (lambda (sym) (set sym (pop cache))) reftex-cache-variables))
6015 (t (reftex-compile-variables)))))
6016
6017 (defun reftex-reset-mode ()
6018 "Reset RefTeX Mode.
6019 This will re-compile the configuration information and remove all
6020 current scanning information and the parse file to enforce a rescan
6021 on next use."
6022 (interactive)
6023
6024 ;; Reset the file search path variables
6025 (loop for prop in '(status master-dir recursive-path rec-type) do
6026 (put 'reftex-tex-path prop nil)
6027 (put 'reftex-bib-path prop nil))
6028
6029 ;; Kill temporary buffers associated with RefTeX - just in case they
6030 ;; were not cleaned up properly
6031 (save-excursion
6032 (let ((buffer-list '("*RefTeX Help*" "*RefTeX Select*"
6033 "*Duplicate Labels*" "*toc*" " *RefTeX-scratch*"))
6034 buf)
6035 (while (setq buf (pop buffer-list))
6036 (if (get-buffer buf)
6037 (kill-buffer buf))))
6038 (reftex-erase-all-selection-buffers))
6039
6040 ;; Make sure the current document will be rescanned soon.
6041 (reftex-reset-scanning-information)
6042
6043 ;; Remove any parse info file
6044 (reftex-access-parse-file 'kill)
6045
6046 ;; Plug functions into AUCTeX if the user option says so.
6047 (and reftex-plug-into-AUCTeX
6048 (reftex-plug-into-AUCTeX))
6049
6050 (reftex-compile-variables))
6051
6052 (defun reftex-reset-scanning-information ()
6053 "Reset the symbols containing information from buffer scanning.
6054 This enforces rescanning the buffer on next use."
6055 (if (string= reftex-last-toc-master (reftex-TeX-master-file))
6056 (reftex-erase-buffer "*toc*"))
6057 (let ((symlist reftex-multifile-symbols)
6058 symbol)
6059 (while symlist
6060 (setq symbol (car symlist)
6061 symlist (cdr symlist))
6062 (if (and (symbolp (symbol-value symbol))
6063 (not (null (symbol-value symbol))))
6064 (set (symbol-value symbol) nil)))))
6065
6066 (defun reftex-erase-all-selection-buffers ()
6067 ;; Remove all selection buffers associated with current document.
6068 (mapcar
6069 (lambda (type)
6070 (reftex-erase-buffer (reftex-make-selection-buffer-name type)))
6071 reftex-typekey-list))
6072
6073 (defun reftex-compile-variables ()
6074 ;; Compile the information in reftex-label-alist & Co.
6075
6076 (message "Compiling label environment definitions...")
6077
6078 ;; Update AUCTeX style information
6079 (when (and (featurep 'tex-site) (fboundp 'TeX-update-style))
6080 (condition-case nil (TeX-update-style) (error nil)))
6081
6082 ;; Record that we have done this, and what we have used.
6083 (setq reftex-tables-dirty nil)
6084 (setq reftex-memory
6085 (list reftex-label-alist
6086 (get reftex-docstruct-symbol 'reftex-section-levels)
6087 (get reftex-docstruct-symbol 'reftex-label-alist-style)
6088 reftex-default-label-alist-entries))
6089
6090 ;; Compile information in reftex-label-alist
6091 (let ((all (reftex-uniquify-by-car
6092 (reftex-splice-symbols-into-list
6093 (append reftex-label-alist
6094 (get reftex-docstruct-symbol 'reftex-label-alist-style)
6095 reftex-default-label-alist-entries)
6096 reftex-label-alist-builtin)
6097 '(nil)))
6098 entry env-or-mac typekeychar typekey prefix context word
6099 fmt reffmt labelfmt wordlist qh-list macros-with-labels
6100 nargs nlabel opt-args cell sum i)
6101
6102 (setq reftex-words-to-typekey-alist nil
6103 reftex-typekey-list nil
6104 reftex-typekey-to-format-alist nil
6105 reftex-typekey-to-prefix-alist nil
6106 reftex-env-or-mac-alist nil
6107 reftex-label-env-list nil
6108 reftex-label-mac-list nil)
6109 (while all
6110 (catch 'next-entry
6111 (setq entry (car all)
6112 env-or-mac (car entry)
6113 entry (cdr entry)
6114 all (cdr all))
6115 (if (null env-or-mac)
6116 (setq env-or-mac ""))
6117 (if (stringp (car entry))
6118 ;; This is before version 2.00 - convert entry to new format
6119 ;; This is just to keep old users happy
6120 (setq entry (cons (string-to-char (car entry))
6121 (cons (concat (car entry) ":")
6122 (cdr entry)))))
6123 (setq typekeychar (nth 0 entry)
6124 typekey (if typekeychar (char-to-string typekeychar) nil)
6125 prefix (nth 1 entry)
6126 fmt (nth 2 entry)
6127 context (nth 3 entry)
6128 wordlist (nth 4 entry))
6129 (if (stringp wordlist)
6130 ;; This is before version 2.04 - convert to new format
6131 (setq wordlist (nthcdr 4 entry)))
6132
6133 (if (and (stringp fmt)
6134 (string-match "@" fmt))
6135 ;; Special syntax for specifying a label format
6136 (setq fmt (split-string fmt "@+"))
6137 (setq fmt (list "\\label{%s}" fmt)))
6138 (setq labelfmt (car fmt)
6139 reffmt (nth 1 fmt))
6140 ;; Note a new typekey
6141 (if typekey
6142 (add-to-list 'reftex-typekey-list typekey))
6143 (if (and typekey prefix
6144 (not (assoc typekey reftex-typekey-to-prefix-alist)))
6145 (add-to-list 'reftex-typekey-to-prefix-alist
6146 (cons typekey prefix)))
6147 ;; Check if this is a macro or environment
6148 (cond
6149 ((string-match "\\`\\\\" env-or-mac)
6150 ;; It's a macro
6151 (let ((result (reftex-parse-args env-or-mac)))
6152 (setq env-or-mac (or (first result) env-or-mac)
6153 nargs (second result)
6154 nlabel (third result)
6155 opt-args (fourth result))
6156 (if nlabel (add-to-list 'macros-with-labels env-or-mac)))
6157 (if typekey (add-to-list 'reftex-label-mac-list env-or-mac)))
6158 (t
6159 ;; It's an environment
6160 (setq nargs nil nlabel nil opt-args nil)
6161 (cond ((string= env-or-mac "any"))
6162 ((string= env-or-mac ""))
6163 ((string= env-or-mac "section"))
6164 (t
6165 (add-to-list 'reftex-label-env-list env-or-mac)))))
6166 ;; Translate some special context cases
6167 (when (assq context reftex-default-context-regexps)
6168 (setq context
6169 (format
6170 (cdr (assq context reftex-default-context-regexps))
6171 (regexp-quote env-or-mac))))
6172 ;; See if this is the first format for this typekey
6173 (and reffmt
6174 (not (assoc typekey reftex-typekey-to-format-alist))
6175 (push (cons typekey reffmt) reftex-typekey-to-format-alist))
6176 ;; See if this is the first definition for this env-or-mac
6177 (and (not (string= env-or-mac "any"))
6178 (not (string= env-or-mac ""))
6179 (not (assoc env-or-mac reftex-env-or-mac-alist))
6180 (push (list env-or-mac typekey context labelfmt
6181 nargs nlabel opt-args)
6182 reftex-env-or-mac-alist))
6183 ;; Are the magic words regular expressions? Quote normal words.
6184 (if (eq (car wordlist) 'regexp)
6185 (setq wordlist (cdr wordlist))
6186 (setq wordlist (mapcar 'regexp-quote wordlist)))
6187 ;; Remember the first association of each word.
6188 (while (stringp (setq word (pop wordlist)))
6189 (or (assoc word reftex-words-to-typekey-alist)
6190 (push (cons word typekey) reftex-words-to-typekey-alist)))
6191 (cond
6192 ((string= "" env-or-mac) nil)
6193 ((setq cell (assoc typekey qh-list))
6194 (push env-or-mac (cdr cell)))
6195 (typekey
6196 (push (list typekey env-or-mac) qh-list)))))
6197
6198 (setq reftex-typekey-to-prefix-alist
6199 (nreverse reftex-typekey-to-prefix-alist))
6200
6201 ;; Prepare the typekey query prompt and help string.
6202 (setq qh-list
6203 (sort qh-list (function
6204 (lambda (x1 x2) (string< (car x1) (car x2))))))
6205 (setq reftex-type-query-prompt
6206 (concat "Label type: ["
6207 (mapconcat (function (lambda(x) (format "%s" (car x))))
6208 qh-list "")
6209 "]"))
6210 ;; In the help string, we need to wrap lines...
6211 (setq reftex-type-query-help
6212 (concat
6213 "SELECT A LABEL TYPE:\n--------------------\n"
6214 (mapconcat
6215 (lambda(x)
6216 (setq sum 0)
6217 (format " [%s] %s"
6218 (car x)
6219 (mapconcat (lambda(env)
6220 (setq sum (+ sum (length env)))
6221 (if (< sum 60)
6222 env
6223 (setq sum 0)
6224 (concat "\n " env)))
6225 (cdr x) " ")))
6226 qh-list "\n")))
6227
6228 ;; Convert magic words to regular expressions. We make regular expressions
6229 ;; which allow for some chars from the ref format to be in the buffer.
6230 ;; These characters will be seen and removed.
6231 (setq reftex-words-to-typekey-alist
6232 (mapcar
6233 (lambda (x)
6234 (setq word (car x)
6235 typekey (cdr x)
6236 fmt (cdr (assoc typekey reftex-typekey-to-format-alist)))
6237 (setq word (concat "\\W\\(" word "[ \t\n\r]*\\)\\("))
6238 (setq i 0)
6239 (while (and (< i 10) ; maximum number of format chars allowed
6240 (< i (length fmt))
6241 (not (member (aref fmt i) '(?%))))
6242 (setq word (concat word "\\|" (regexp-quote
6243 (substring fmt 0 (1+ i)))))
6244 (incf i))
6245 (cons (concat word "\\)\\=") typekey))
6246 (nreverse reftex-words-to-typekey-alist)))
6247
6248 ;; Make the full list of section levels
6249 (setq reftex-section-levels-all
6250 (append (get reftex-docstruct-symbol 'reftex-section-levels)
6251 reftex-section-levels))
6252
6253 ;; Calculate the regular expressions
6254 (let* ((wbol "\\(\\`\\|[\n\r]\\)[ \t]*")
6255 (label-re "\\\\label{\\([^}]*\\)}")
6256 (include-re (concat wbol "\\\\\\(include\\|input\\)[{ \t]+\\([^} \t\n\r]+\\)"))
6257 (section-re
6258 (concat wbol "\\\\\\("
6259 (mapconcat 'car reftex-section-levels-all "\\|")
6260 "\\)\\*?\\(\\[[^]]*\\]\\)?{"))
6261 (appendix-re (concat wbol "\\(\\\\appendix\\)"))
6262 (macro-re
6263 (if macros-with-labels
6264 (concat "\\("
6265 (mapconcat 'regexp-quote macros-with-labels "\\|")
6266 "\\)[[{]")
6267 ""))
6268 (find-label-re-format
6269 (concat "\\("
6270 (mapconcat 'regexp-quote (append '("\\label")
6271 macros-with-labels) "\\|")
6272 "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]")))
6273 (setq reftex-section-regexp section-re
6274 reftex-section-or-include-regexp
6275 (concat section-re "\\|" include-re)
6276 reftex-everything-regexp
6277 (concat label-re "\\|" section-re "\\|" include-re
6278 "\\|" appendix-re
6279 (if macros-with-labels "\\|" "") macro-re)
6280 reftex-find-label-regexp-format find-label-re-format
6281 reftex-find-label-regexp-format2
6282 "\\([]} \t\n\r]\\)\\([[{]\\)\\(%s\\)[]}]")
6283 (message "Compiling label environment definitions...done")))
6284 (put reftex-docstruct-symbol 'reftex-cache
6285 (mapcar 'symbol-value reftex-cache-variables)))
6286
6287 ;;; =========================================================================
6288 ;;;
6289 ;;; Operations on entire Multifile documents
6290
6291 (defun reftex-create-tags-file ()
6292 "Create TAGS file by running `etags' on the current document.
6293 The TAGS file is also immediately visited with `visit-tags-table'."
6294 (interactive)
6295 (reftex-access-scan-info current-prefix-arg)
6296 (let* ((master (reftex-TeX-master-file))
6297 (files (reftex-all-document-files))
6298 (cmd (format "etags %s" (mapconcat 'identity files " "))))
6299 (save-excursion
6300 (set-buffer (reftex-get-buffer-visiting master))
6301 (message "Running etags to create TAGS file...")
6302 (shell-command cmd)
6303 (visit-tags-table "TAGS"))))
6304
6305 ;; History of grep commands.
6306 (defvar reftex-grep-history nil)
6307 (defvar reftex-grep-command "grep -n "
6308 "Last grep command used in \\[reftex-grep-document]; default for next grep.")
6309
6310 (defun reftex-grep-document (grep-cmd)
6311 "Run grep query through all files related to this document.
6312 With prefix arg, force to rescan document.
6313 No active TAGS table is required."
6314
6315 (interactive
6316 (list (read-from-minibuffer "Run grep on document (like this): "
6317 reftex-grep-command nil nil
6318 'reftex-grep-history)))
6319 (reftex-access-scan-info current-prefix-arg)
6320 (let* ((files (reftex-all-document-files t))
6321 (cmd (format
6322 "%s %s" grep-cmd
6323 (mapconcat 'identity files " "))))
6324 (grep cmd)))
6325
6326 (defun reftex-search-document (&optional regexp)
6327 "Regexp search through all files of the current TeX document.
6328 Starts always in the master file. Stops when a match is found.
6329 To continue searching for next match, use command \\[tags-loop-continue].
6330 No active TAGS table is required."
6331 (interactive)
6332 (let ((default (reftex-this-word)))
6333 (unless regexp
6334 (setq regexp (read-string (format "Search regexp in document [%s]: "
6335 default))))
6336 (if (string= regexp "") (setq regexp (regexp-quote default)))
6337
6338 (reftex-access-scan-info current-prefix-arg)
6339 (tags-search regexp (list 'reftex-all-document-files))))
6340
6341 (defun reftex-query-replace-document (&optional from to delimited)
6342 "Run a query-replace-regexp of FROM with TO over the entire TeX document.
6343 Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
6344 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
6345 with the command \\[tags-loop-continue].
6346 No active TAGS table is required."
6347 (interactive)
6348 (let ((default (reftex-this-word)))
6349 (unless from
6350 (setq from (read-string (format "Replace regexp in document [%s]: "
6351 default)))
6352 (if (string= from "") (setq from (regexp-quote default))))
6353 (unless to
6354 (setq to (read-string (format "Replace regexp %s with: " from))))
6355 (reftex-access-scan-info current-prefix-arg)
6356 (tags-query-replace from to (or delimited current-prefix-arg)
6357 (list 'reftex-all-document-files))))
6358
6359 (defun reftex-find-duplicate-labels ()
6360 "Produce a list of all duplicate labels in the document."
6361
6362 (interactive)
6363
6364 ;; Rescan the document to make sure
6365 (reftex-access-scan-info t)
6366
6367 (let ((master (reftex-TeX-master-file))
6368 (cnt 0)
6369 (dlist
6370 (mapcar
6371 (function
6372 (lambda (x)
6373 (let (x1)
6374 (cond
6375 ((memq (car x)
6376 '(toc bof eof bib thebib label-numbers xr xr-doc
6377 master-dir file-error bibview-cache appendix
6378 is-multi))
6379 nil)
6380 (t
6381 (setq x1 (reftex-all-assoc-string
6382 (car x) (symbol-value reftex-docstruct-symbol)))
6383 (if (< 1 (length x1))
6384 (append (list (car x))
6385 (mapcar (function
6386 (lambda(x)
6387 (abbreviate-file-name (nth 3 x))))
6388 x1))
6389 (list nil)))))))
6390 (reftex-uniquify-by-car (symbol-value reftex-docstruct-symbol)))))
6391
6392 (setq dlist (reftex-uniquify-by-car dlist))
6393 (if (null dlist) (error "No duplicate labels in document"))
6394 (switch-to-buffer-other-window "*Duplicate Labels*")
6395 (make-local-variable 'TeX-master)
6396 (setq TeX-master master)
6397 (erase-buffer)
6398 (insert " MULTIPLE LABELS IN CURRENT DOCUMENT:\n")
6399 (insert
6400 " Move point to label and type `r' to run a query-replace on the label\n"
6401 " and its references. Type `q' to exit this buffer.\n\n")
6402 (insert " LABEL FILE\n")
6403 (insert " -------------------------------------------------------------\n")
6404 (use-local-map (make-sparse-keymap))
6405 (local-set-key [?q] (function
6406 (lambda () "Kill this buffer." (interactive)
6407 (kill-buffer (current-buffer)) (delete-window))))
6408 (local-set-key [?r] 'reftex-change-label)
6409 (while dlist
6410 (when (and (car (car dlist))
6411 (cdr (car dlist)))
6412 (incf cnt)
6413 (insert (mapconcat 'identity (car dlist) "\n ") "\n"))
6414 (pop dlist))
6415 (goto-char (point-min))
6416 (when (= cnt 0)
6417 (kill-buffer (current-buffer))
6418 (delete-window)
6419 (message "Document does not contain duplicate labels."))))
6420
6421 (defun reftex-change-label (&optional from to)
6422 "Query replace FROM with TO in all \\label and \\ref commands.
6423 Works on the entire multifile document.
6424 If you exit (\\[keyboard-quit] or ESC), you can resume the query replace
6425 with the command \\[tags-loop-continue].
6426 No active TAGS table is required."
6427 (interactive)
6428 (let ((default (reftex-this-word "-a-zA-Z0-9_*.:")))
6429 (unless from
6430 (setq from (read-string (format "Replace label globally [%s]: "
6431 default))))
6432 (if (string= from "") (setq from default))
6433 (unless to
6434 (setq to (read-string (format "Replace label %s with: "
6435 from))))
6436 (reftex-query-replace-document
6437 (concat "\\\\\\(label\\|[a-z]*ref\\){" (regexp-quote from) "}")
6438 (format "\\\\\\1{%s}" to))))
6439
6440 (defun reftex-renumber-simple-labels ()
6441 "Renumber all simple labels in the document to make them sequentially.
6442 Simple labels are the ones created by RefTeX, consisting only of the
6443 prefix and a number. After the command completes, all these labels will
6444 have sequential numbers throughout the document. Any references to
6445 the labels will be changed as well. For this, RefTeX looks at the
6446 arguments of any macros which either start or end in the string `ref'.
6447 This command should be used with care, in particular in multifile
6448 documents. You should not use it if another document refers to this
6449 one with the `xr' package."
6450 (interactive)
6451 ;; Resan the entire document
6452 (reftex-access-scan-info 1)
6453 ;; Get some insurance
6454 (if (and (reftex-is-multi)
6455 (not (yes-or-no-p "Replacing all simple labels in multiple files is risky. Continue? ")))
6456 (error "Abort"))
6457 ;; Make the translation list
6458 (let* ((re-core (concat "\\("
6459 (mapconcat 'cdr reftex-typekey-to-prefix-alist "\\|")
6460 "\\)"))
6461 (label-re (concat "\\`" re-core "\\([0-9]+\\)\\'"))
6462 (search-re (concat "{\\(" re-core "\\([0-9]+\\)\\)}"))
6463 (error-fmt "Undefined label or reference %s. Ignore and continue? ")
6464 (label-numbers-alist (mapcar (lambda (x) (cons (cdr x) 0))
6465 reftex-typekey-to-prefix-alist))
6466 (files (reftex-all-document-files))
6467 (list (symbol-value reftex-docstruct-symbol))
6468 translate-alist n entry label new-label nr-cell changed-sequence)
6469
6470 (while (setq entry (pop list))
6471 (when (and (stringp (car entry))
6472 (string-match label-re (car entry)))
6473 (setq label (car entry)
6474 nr-cell (assoc (match-string 1 (car entry))
6475 label-numbers-alist))
6476 (if (assoc label translate-alist)
6477 (error "Duplicate label %s" label))
6478 (setq new-label (concat (match-string 1 (car entry))
6479 (incf (cdr nr-cell))))
6480 (push (cons label new-label) translate-alist)
6481 (or (string= label new-label) (setq changed-sequence t))))
6482
6483 (unless changed-sequence
6484 (error "Simple labels are already in correct sequence"))
6485
6486 ;; Save all document buffers before this operation
6487 (reftex-save-all-document-buffers)
6488
6489 ;; First test to check for erros
6490 (setq n (reftex-translate
6491 files search-re translate-alist error-fmt 'test))
6492
6493 ;; Now the real thing.
6494 (if (yes-or-no-p
6495 (format "Replace %d items at %d places in %d files? "
6496 (length translate-alist) n (length files)))
6497 (progn
6498 (let ((inhibit-quit t)) ;; Do not disturb...
6499 (reftex-translate
6500 files search-re translate-alist error-fmt nil)
6501 (setq quit-flag nil))
6502 (if (and (reftex-is-multi)
6503 (yes-or-no-p "Save entire document? "))
6504 (reftex-save-all-document-buffers))
6505 ;; Rescan again...
6506 (reftex-access-scan-info 1)
6507 (message "Done replacing simple labels."))
6508 (message "No replacements done"))))
6509
6510 (defun reftex-translate (files search-re translate-alist error-fmt test)
6511 ;; In FILES, look for SEARCH-RE and replace match 1 of it with
6512 ;; its association in TRANSLATE-ALSIT.
6513 ;; If we do not find an association and TEST is non-nil, query
6514 ;; to ignore the problematic string.
6515 ;; If TEST is nil, it is ignored without query.
6516 ;; Return the number of replacements.
6517 (let ((n 0) file label match-data buf macro pos cell)
6518 (while (setq file (pop files))
6519 (setq buf (reftex-get-file-buffer-force file))
6520 (unless buf
6521 (error "No such file %s" file))
6522 (set-buffer buf)
6523 (save-excursion
6524 (save-restriction
6525 (widen)
6526 (goto-char (point-min))
6527 (while (re-search-forward search-re nil t)
6528 (save-excursion
6529 (backward-char)
6530 (setq label (reftex-match-string 1)
6531 cell (assoc label translate-alist)
6532 match-data (match-data)
6533 macro (reftex-what-macro 1)
6534 pos (cdr macro))
6535 (goto-char (or pos (point)))
6536 (when (and macro
6537 (or (looking-at "\\\\ref")
6538 (looking-at "\\\\[a-zA-Z]*ref[^a-zA-Z]")
6539 (looking-at "\\\\ref[a-zA-Z]*[^a-zA-Z]")
6540 (looking-at (format
6541 reftex-find-label-regexp-format
6542 (regexp-quote label)))))
6543 ;; OK, we should replace it.
6544 (set-match-data match-data)
6545 (cond
6546 ((and test (not cell))
6547 ;; We've got a problem
6548 (unwind-protect
6549 (progn
6550 (reftex-highlight 1 (match-beginning 0) (match-end 0))
6551 (ding)
6552 (or (y-or-n-p (format error-fmt label))
6553 (error "Abort")))
6554 (reftex-unhighlight 1)))
6555 ((and test cell)
6556 (incf n))
6557 ((and (not test) cell)
6558 ;; Replace
6559 (goto-char (match-beginning 1))
6560 (delete-region (match-beginning 1) (match-end 1))
6561 (insert (cdr cell)))
6562 (t nil))))))))
6563 n))
6564
6565 (defun reftex-save-all-document-buffers ()
6566 "Save all documents associated with the current document.
6567 The function is useful after a global action like replacing or renumbering
6568 labels."
6569 (interactive)
6570 (let ((files (reftex-all-document-files))
6571 file buffer)
6572 (save-excursion
6573 (while (setq file (pop files))
6574 (setq buffer (reftex-get-buffer-visiting file))
6575 (when buffer
6576 (set-buffer buffer)
6577 (save-buffer))))))
6578
6579 ;;; =========================================================================
6580 ;;;
6581 ;;; AUCTeX Interface
6582
6583 (defun reftex-plug-flag (which)
6584 ;; Tell if a certain flag is set in reftex-plug-into-AUCTeX
6585 (or (eq t reftex-plug-into-AUCTeX)
6586 (and (listp reftex-plug-into-AUCTeX)
6587 (nth which reftex-plug-into-AUCTeX))))
6588
6589 (defun reftex-arg-label (optional &optional prompt definition)
6590 "Use `reftex-label', `reftex-reference' or AUCTeX's code to insert label arg.
6591 What is being used depends upon `reftex-plug-into-AUCTeX'."
6592 (let (label)
6593 (cond
6594 ((and definition (reftex-plug-flag 1))
6595 ;; Create a new label, with a temporary brace for `reftex-what-macro'
6596 (unwind-protect
6597 (progn (insert "{") (setq label (or (reftex-label nil t) "")))
6598 (delete-backward-char 1)))
6599 ((and (not definition) (reftex-plug-flag 2))
6600 ;; Reference a label with RefTeX
6601 (setq label (reftex-reference nil t)))
6602 (t
6603 ;; AUCTeX's default mechanism
6604 (setq label (completing-read (TeX-argument-prompt optional prompt "Key")
6605 (LaTeX-label-list)))))
6606 (if (and definition (not (string-equal "" label)))
6607 (LaTeX-add-labels label))
6608 (TeX-argument-insert label optional optional)))
6609
6610 (defun reftex-arg-cite (optional &optional prompt definition)
6611 "Use `reftex-citation' or AUCTeX's code to insert a cite-key macro argument.
6612 What is being used depends upon `reftex-plug-into-AUCTeX'."
6613 (let (items)
6614 (cond
6615 ((and (not definition) (reftex-plug-flag 3))
6616 (setq items (list (or (reftex-citation t) ""))))
6617 (t
6618 (setq prompt (concat (if optional "(Optional) " "")
6619 (if prompt prompt "Add key")
6620 ": (default none) "))
6621 (setq items (multi-prompt "," t prompt (LaTeX-bibitem-list)))))
6622 (apply 'LaTeX-add-bibitems items)
6623 (TeX-argument-insert (mapconcat 'identity items ",") optional optional)))
6624
6625 (defun reftex-plug-into-AUCTeX ()
6626 ;; Replace AUCTeX functions with RefTeX functions.
6627 ;; Which functions are replaced is controlled by the variable
6628 ;; `reftex-plug-into-AUCTeX'.
6629
6630 (if (reftex-plug-flag 0)
6631 (setq LaTeX-label-function 'reftex-label)
6632 (setq LaTeX-label-function nil))
6633
6634 (if (and (or (reftex-plug-flag 1) (reftex-plug-flag 2))
6635 (fboundp 'TeX-arg-label))
6636 (fset 'TeX-arg-label 'reftex-arg-label))
6637
6638 (if (and (reftex-plug-flag 3)
6639 (fboundp 'TeX-arg-cite))
6640 (fset 'TeX-arg-cite 'reftex-arg-cite)))
6641
6642 (defun reftex-toggle-plug-into-AUCTeX ()
6643 "Toggle Interface between AUCTeX and RefTeX on and off."
6644 (interactive)
6645 (unless (and (featurep 'tex-site) (featurep 'latex))
6646 (error "AUCTeX's LaTeX mode does not seem to be loaded."))
6647 (setq reftex-plug-into-AUCTeX (not reftex-plug-into-AUCTeX))
6648 (reftex-plug-into-AUCTeX)
6649 (if reftex-plug-into-AUCTeX
6650 (message "RefTeX has been plugged into AUCTeX.")
6651 (message "RefTeX no longer interacts with AUCTeX.")))
6652
6653 (defun reftex-add-label-environments (entry-list)
6654 "Add label environment descriptions to `reftex-label-alist-style'.
6655 The format of ENTRY-LIST is exactly like `reftex-label-alist'. See there
6656 for details.
6657 This function makes it possible to support RefTeX from AUCTeX style files.
6658 The entries in ENTRY-LIST will be processed after the user settings in
6659 `reftex-label-alist', and before the defaults (specified in
6660 `reftex-default-label-alist-entries'). Any changes made to
6661 `reftex-label-alist-style' will raise a flag to the effect that
6662 the label information is recompiled on next use."
6663 (unless reftex-docstruct-symbol
6664 (reftex-tie-multifile-symbols))
6665 (when (and reftex-docstruct-symbol
6666 (symbolp reftex-docstruct-symbol))
6667 (let ((list (get reftex-docstruct-symbol 'reftex-label-alist-style))
6668 entry changed)
6669 (while entry-list
6670 (setq entry (pop entry-list))
6671 (unless (member entry list)
6672 (setq reftex-tables-dirty t
6673 changed t)
6674 (push entry list)))
6675 (when changed
6676 (put reftex-docstruct-symbol 'reftex-label-alist-style list)))))
6677 (defalias 'reftex-add-to-label-alist 'reftex-add-label-environments)
6678
6679 (defun reftex-add-section-levels (entry-list)
6680 "Add entries to the value of `reftex-section-levels'.
6681 The added values are kept local to the current document. The format
6682 of ENTRY-LIST is a list of cons cells (\"MACRONAME\" . LEVEL). See
6683 `reftex-section-levels' for an example."
6684 (unless reftex-docstruct-symbol
6685 (reftex-tie-multifile-symbols))
6686 (when (and reftex-docstruct-symbol
6687 (symbolp reftex-docstruct-symbol))
6688 (let ((list (get reftex-docstruct-symbol 'reftex-section-levels))
6689 entry changed)
6690 (while entry-list
6691 (setq entry (pop entry-list))
6692 (unless (member entry list)
6693 (setq reftex-tables-dirty t
6694 changed t)
6695 (push entry list)))
6696 (when changed
6697 (put reftex-docstruct-symbol 'reftex-section-levels list)))))
6698
6699 (defun reftex-set-cite-format (value)
6700 "Set the document-local value of `reftex-cite-format'.
6701 When such a value exists, it overwrites the setting given with
6702 `reftex-cite-format'. See the documentation of `reftex-cite-format'
6703 for possible values. This function should be used from AUCTeX style files."
6704 (unless reftex-docstruct-symbol
6705 (reftex-tie-multifile-symbols))
6706 (when (and reftex-docstruct-symbol
6707 (symbolp reftex-docstruct-symbol))
6708 (put reftex-docstruct-symbol 'reftex-cite-format value)))
6709
6710 (defun reftex-notice-new-section ()
6711 "Hook to handshake with RefTeX after a new section has been inserted."
6712 ;; Add a new section to the docstruct list and renumber the
6713 ;; following sections. This hook has to be called immediately after
6714 ;; the new section was inserted into the buffer, and before the
6715 ;; section label is created.
6716
6717 (condition-case nil
6718 (catch 'exit
6719 (unless reftex-mode (throw 'exit nil))
6720 (reftex-access-scan-info)
6721 (let* ((docstruct (symbol-value reftex-docstruct-symbol))
6722 here-am-I appendix tail toc-entry star level
6723 section-number context)
6724
6725 (save-excursion
6726 (when (re-search-backward reftex-section-regexp nil t)
6727
6728 ;; Find where we are
6729 (setq here-am-I (reftex-where-am-I))
6730 (unless (cdr here-am-I) (throw 'exit nil))
6731 (setq reftex-active-toc (reftex-last-assoc-before-elt
6732 'toc (car here-am-I) docstruct)
6733 appendix (reftex-last-assoc-before-elt
6734 'appendix (car here-am-I) docstruct))
6735
6736 ;; Initialize section numbers
6737 (if (eq (car (car here-am-I)) 'appendix)
6738 (reftex-init-section-numbers nil t)
6739 (reftex-init-section-numbers reftex-active-toc appendix))
6740
6741 ;; Match the section command
6742 (when (and (re-search-forward reftex-everything-regexp nil t)
6743 (match-end 3))
6744 (setq star (= ?* (char-after (match-end 3)))
6745 toc-entry (reftex-section-info (buffer-file-name))
6746 level (nth 5 toc-entry)
6747 tail (memq (car here-am-I)
6748 (symbol-value reftex-docstruct-symbol)))
6749 (if tail
6750 ;; Insert the section info
6751 (push toc-entry (cdr tail))
6752 (throw 'exit nil))
6753
6754 ;; We are done unless we use section numbers
6755 (unless (nth 1 reftex-label-menu-flags) (throw 'exit nil))
6756
6757 ;; Update the remaining toc items
6758 (setq tail (cdr tail))
6759 (while (and (setq tail (memq (assq 'toc (cdr tail)) tail))
6760 (setq toc-entry (car tail))
6761 (>= (nth 5 toc-entry) level))
6762 (setq section-number
6763 (reftex-section-number (nth 5 toc-entry) star)
6764 context (nth 2 toc-entry))
6765 (when (string-match "\\`\\([ \t]*\\)\\([.0-9A-Z]+\\)\\(.*\\)"
6766 context)
6767 (when (and (not appendix)
6768 (>= (string-to-char (match-string 2)) ?A))
6769 ;; Just entered the appendex. Get out.
6770 (throw 'exit nil))
6771
6772 ;; Change the section number.
6773 (setf (nth 2 toc-entry)
6774 (concat (match-string 1 context)
6775 section-number
6776 (match-string 3 context))))))))))
6777 (error nil))
6778 )
6779
6780 ;;; =========================================================================
6781 ;;;
6782 ;;; Keybindings
6783
6784 ;; The default bindings in the mode map.
6785 (loop for x in
6786 '(("\C-c=" . reftex-toc)
6787 ("\C-c(" . reftex-label)
6788 ("\C-c)" . reftex-reference)
6789 ("\C-c[" . reftex-citation)
6790 ("\C-c&" . reftex-view-crossref))
6791 do (define-key reftex-mode-map (car x) (cdr x)))
6792
6793 ;; Bind `reftex-mouse-view-crossref' only when the key is still free
6794 (if (featurep 'xemacs)
6795 (unless (key-binding [(shift button2)])
6796 (define-key reftex-mode-map [(shift button2)]
6797 'reftex-mouse-view-crossref))
6798 (unless (key-binding [(shift mouse-2)])
6799 (define-key reftex-mode-map [(shift mouse-2)]
6800 'reftex-mouse-view-crossref)))
6801
6802 ;; If the user requests so, she can have a few more bindings:
6803 (when reftex-extra-bindings
6804 (loop for x in
6805 '(("\C-ct" . reftex-toc)
6806 ("\C-cl" . reftex-label)
6807 ("\C-cr" . reftex-reference)
6808 ("\C-cc" . reftex-citation)
6809 ("\C-cv" . reftex-view-crossref)
6810 ("\C-cg" . reftex-grep-document)
6811 ("\C-cs" . reftex-search-document))
6812 do (define-key reftex-mode-map (car x) (cdr x))))
6813
6814 ;; Common bindings in reftex-select-label-map and reftex-select-bib-map
6815 (let ((map (make-sparse-keymap)))
6816 (substitute-key-definition
6817 'next-line 'reftex-select-next map global-map)
6818 (substitute-key-definition
6819 'previous-line 'reftex-select-previous map global-map)
6820 (substitute-key-definition
6821 'keyboard-quit 'reftex-select-keyboard-quit map global-map)
6822 (substitute-key-definition
6823 'newline 'reftex-select-accept map global-map)
6824
6825 (loop for x in
6826 '((" " . reftex-select-callback)
6827 ("n" . reftex-select-next)
6828 ([(down)] . reftex-select-next)
6829 ("p" . reftex-select-previous)
6830 ([(up)] . reftex-select-previous)
6831 ("f" . reftex-select-toggle-follow)
6832 ("\C-m" . reftex-select-accept)
6833 ([(return)] . reftex-select-accept)
6834 ("q" . reftex-select-quit)
6835 ("." . reftex-select-show-insertion-point)
6836 ("?" . reftex-select-help))
6837 do (define-key map (car x) (cdr x)))
6838
6839 ;; The mouse-2 binding
6840 (if (featurep 'xemacs)
6841 (define-key map [(button2)] 'reftex-select-mouse-accept)
6842 (define-key map [(mouse-2)] 'reftex-select-mouse-accept))
6843
6844 ;; Digit arguments
6845 (loop for key across "0123456789" do
6846 (define-key map (vector (list key)) 'digit-argument))
6847 (define-key map "-" 'negative-argument)
6848
6849 ;; Make two maps
6850 (setq reftex-select-label-map map)
6851 (setq reftex-select-bib-map (copy-keymap map)))
6852
6853 ;; Specific bindings in reftex-select-label-map
6854 (loop for key across "cgilrRstx#%" do
6855 (define-key reftex-select-label-map (vector (list key))
6856 (list 'lambda '()
6857 "Press `?' during selection to find out about this key."
6858 '(interactive) (list 'throw '(quote myexit) key))))
6859
6860 (loop for x in
6861 '(("b" . reftex-select-jump-to-previous)
6862 ("v" . reftex-select-toggle-varioref)
6863 ([(tab)] . reftex-select-read-label)
6864 ("\C-i" . reftex-select-read-label)
6865 ("\C-c\C-n" . reftex-select-next-heading)
6866 ("\C-c\C-p" . reftex-select-previous-heading))
6867 do
6868 (define-key reftex-select-label-map (car x) (cdr x)))
6869
6870 ;; Specific bindings in reftex-select-bib-map
6871 (loop for key across "grRaA" do
6872 (define-key reftex-select-bib-map (vector (list key))
6873 (list 'lambda '()
6874 "Press `?' during selection to find out about this key."
6875 '(interactive) (list 'throw '(quote myexit) key))))
6876
6877 (loop for x in
6878 '(("\C-i" . reftex-select-read-cite)
6879 ([(tab)] . reftex-select-read-cite))
6880 do (define-key reftex-select-bib-map (car x) (cdr x)))
6881
6882 ;; Table of Contents map
6883 (if (featurep 'xemacs)
6884 (define-key reftex-toc-map [(button2)] 'reftex-toc-mouse-goto-line-and-hide)
6885 (define-key reftex-toc-map [(mouse-2)] 'reftex-toc-mouse-goto-line-and-hide))
6886
6887 (loop for x in
6888 '(("n" . next-line)
6889 ("p" . previous-line)
6890 ("?" . reftex-toc-show-help)
6891 (" " . reftex-toc-view-line)
6892 ("\C-m" . reftex-toc-goto-line-and-hide)
6893 ("\C-i" . reftex-toc-goto-line)
6894 ("r" . reftex-toc-rescan)
6895 ("R" . reftex-toc-Rescan)
6896 ("g" . revert-buffer)
6897 ("q" . reftex-toc-quit)
6898 ("Q" . reftex-toc-quit-and-kill)
6899 ("f" . reftex-toc-toggle-follow)
6900 ("x" . reftex-toc-external)
6901 ("." . reftex-toc-show-insertion-point))
6902 do (define-key reftex-toc-map (car x) (cdr x)))
6903
6904 (loop for key across "0123456789" do
6905 (define-key reftex-toc-map (vector (list key)) 'digit-argument))
6906 (define-key reftex-toc-map "-" 'negative-argument)
6907
6908 ;;; =========================================================================
6909 ;;;
6910 ;;; Menu
6911
6912 ;; Define a menu for the menu bar if Emacs is running under X
6913
6914 (require 'easymenu)
6915
6916 (easy-menu-define
6917 reftex-mode-menu reftex-mode-map
6918 "Menu used in RefTeX mode"
6919 `("Ref"
6920 ["Table of Contents" reftex-toc t]
6921 "---"
6922 ["\\label" reftex-label t]
6923 ["\\ref" reftex-reference t]
6924 ["\\cite" reftex-citation t]
6925 ["View Crossref" reftex-view-crossref t]
6926 "---"
6927 ("Parse Document"
6928 ["Only this File" reftex-parse-one t]
6929 ["Entire Document" reftex-parse-all (reftex-is-multi)]
6930 ["Save to File" (reftex-access-parse-file 'write)
6931 (> (length (symbol-value reftex-docstruct-symbol)) 0)]
6932 ["Restore from File" (reftex-access-parse-file 'restore) t]
6933 "---"
6934 ["Reset RefTeX Mode" reftex-reset-mode t])
6935 ("Global Actions"
6936 ["Search Whole Document" reftex-search-document t]
6937 ["Replace in Document" reftex-query-replace-document t]
6938 ["Grep on Document" reftex-grep-document t]
6939 "---"
6940 ["Create TAGS File" reftex-create-tags-file t]
6941 "---"
6942 ["Find Duplicate Labels" reftex-find-duplicate-labels t]
6943 ["Change Label and Refs" reftex-change-label t]
6944 ["Renumber Simple Labels" reftex-renumber-simple-labels t]
6945 "---"
6946 ["Save document" reftex-save-all-document-buffers t])
6947 "---"
6948 ("Options"
6949 ("Table of Contents"
6950 ["Follow Mode" (setq reftex-toc-follow-mode (not reftex-toc-follow-mode))
6951 :style toggle :selected reftex-toc-follow-mode]
6952 ["Follow Mode may visit files"
6953 (setq reftex-revisit-to-follow (not reftex-revisit-to-follow))
6954 :style toggle :selected reftex-revisit-to-follow])
6955 ("References"
6956 ["Guess Label Type"
6957 (setq reftex-guess-label-type (not reftex-guess-label-type))
6958 :style toggle :selected reftex-guess-label-type]
6959 ["Use `\\vref' by Default"
6960 (setq reftex-vref-is-default (not reftex-vref-is-default))
6961 :style toggle :selected reftex-vref-is-default]
6962 "---"
6963 "Selection Buffers"
6964 ["Use Multiple Buffers"
6965 (setq reftex-use-multiple-selection-buffers
6966 (not reftex-use-multiple-selection-buffers))
6967 :style toggle :selected reftex-use-multiple-selection-buffers]
6968 ["Auto Update Buffers"
6969 (setq reftex-auto-update-selection-buffers
6970 (not reftex-auto-update-selection-buffers))
6971 :style toggle :selected reftex-auto-update-selection-buffers])
6972 ("Citations"
6973 "Citation Style"
6974 ,@(mapcar
6975 (function
6976 (lambda (x)
6977 (vector
6978 (capitalize (symbol-name (car x)))
6979 (list 'reftex-set-cite-format (list 'quote (car x)))
6980 ':style 'radio ':selected
6981 (list 'eq (list 'reftex-get-cite-format) (list 'quote (car x))))))
6982 reftex-cite-format-builtin)
6983 "---"
6984 "Bibinfo in Comments"
6985 ["Attach Comments"
6986 (setq reftex-comment-citations (not reftex-comment-citations))
6987 :style toggle :selected reftex-comment-citations]
6988 "---"
6989 "Sort Database Matches"
6990 ["by Author" (setq reftex-sort-bibtex-matches 'author)
6991 :style radio :selected (eq reftex-sort-bibtex-matches 'author)]
6992 ["by Year" (setq reftex-sort-bibtex-matches 'year)
6993 :style radio :selected (eq reftex-sort-bibtex-matches 'year)]
6994 ["by Year, reversed" (setq reftex-sort-bibtex-matches 'reverse-year)
6995 :style radio :selected (eq reftex-sort-bibtex-matches 'reverse-year)]
6996 ["Not" (setq reftex-sort-bibtex-matches nil)
6997 :style radio :selected (eq reftex-sort-bibtex-matches nil)])
6998 ("Crossref Viewing"
6999 ["Automatic Info" reftex-toggle-auto-view-crossref
7000 :style toggle :selected reftex-auto-view-crossref-timer]
7001 ["...in Echo Area" (setq reftex-auto-view-crossref t)
7002 :style radio :selected (eq reftex-auto-view-crossref t)]
7003 ["...in Other Window" (setq reftex-auto-view-crossref 'window)
7004 :style radio :selected (eq reftex-auto-view-crossref 'window)]
7005 "---"
7006 ["Crossref Echo may visit files"
7007 (setq reftex-revisit-to-echo (not reftex-revisit-to-echo))
7008 :style toggle :selected reftex-revisit-to-echo]
7009 ["Cache Echo strings for \cite"
7010 (setq reftex-cache-cite-echo (not reftex-cache-cite-echo))
7011 :style toggle :selected reftex-cache-cite-echo])
7012 ("Parser"
7013 "Document Scans"
7014 ["Partial Scans"
7015 (setq reftex-enable-partial-scans (not reftex-enable-partial-scans))
7016 :style toggle :selected reftex-enable-partial-scans]
7017 ["Auto-Save Parse Info"
7018 (setq reftex-save-parse-info (not reftex-save-parse-info))
7019 :style toggle :selected reftex-save-parse-info]
7020 ["Automatic Rescans"
7021 (setq reftex-allow-automatic-rescan (not reftex-allow-automatic-rescan))
7022 :style toggle :selected reftex-allow-automatic-rescan]
7023 "---"
7024 "Temporary Buffers"
7025 ["Keep Buffers"
7026 (setq reftex-keep-temporary-buffers (not reftex-keep-temporary-buffers))
7027 :style toggle :selected reftex-keep-temporary-buffers]
7028 ["Initialize when Visiting"
7029 (setq reftex-initialize-temporary-buffers
7030 (not reftex-initialize-temporary-buffers))
7031 :style toggle :selected reftex-initialize-temporary-buffers])
7032 ("AUC TeX"
7033 ["Plug into AUC TeX" reftex-toggle-plug-into-AUCTeX
7034 :style toggle :selected reftex-plug-into-AUCTeX])
7035 ("Fontification"
7036 ["Use Fontification" (setq reftex-use-fonts (not reftex-use-fonts))
7037 :style toggle :selected reftex-use-fonts]
7038 ["Fontify Context Display" (setq reftex-refontify-context
7039 (not (reftex-refontify)))
7040 :style toggle :selected (reftex-refontify)]))
7041 ;;"---"
7042 ("Customize"
7043 ["Browse RefTeX group" reftex-customize t]
7044 "---"
7045 ["Build Full Customize Menu" reftex-create-customize-menu
7046 (fboundp 'customize-menu-create)])
7047 "---"
7048 ("Documentation"
7049 ["Info" reftex-info t]
7050 ["Commentary" reftex-show-commentary t])))
7051
7052 (defun reftex-customize ()
7053 "Call the customize function with reftex as argument."
7054 (interactive)
7055 (customize-browse 'reftex))
7056
7057 (defun reftex-create-customize-menu ()
7058 "Create a full customization menu for RefTeX, insert it into the menu."
7059 (interactive)
7060 (if (fboundp 'customize-menu-create)
7061 (progn
7062 (easy-menu-change
7063 '("Ref") "Customize"
7064 `(["Browse RefTeX group" reftex-customize t]
7065 "---"
7066 ,(customize-menu-create 'reftex)
7067 ["Set" Custom-set t]
7068 ["Save" Custom-save t]
7069 ["Reset to Current" Custom-reset-current t]
7070 ["Reset to Saved" Custom-reset-saved t]
7071 ["Reset to Standard Settings" Custom-reset-standard t]))
7072 (message "\"Ref\"-menu now contains full customization menu"))
7073 (error "Cannot expand menu (outdated version of cus-edit.el)")))
7074
7075 (defun reftex-show-commentary ()
7076 "Use the finder to view the file documentation from `reftex.el'."
7077 (interactive)
7078 (require 'finder)
7079 (finder-commentary "reftex.el"))
7080
7081 (defun reftex-info ()
7082 "Read documentation for RefTeX in the info system."
7083 (interactive)
7084 (require 'info)
7085 (Info-goto-node "(reftex)"))
7086
7087 ;; Support for \label and \ref --------------------------------------
7088
7089 ;;; Install the kill-buffer and kill-emacs hooks ------------------------------
7090
7091 (add-hook 'kill-buffer-hook 'reftex-kill-buffer-hook)
7092 (add-hook 'kill-emacs-hook 'reftex-kill-emacs-hook)
7093
7094 ;;; Install the idle timer if requested ---------------------------------------
7095
7096 (and reftex-auto-view-crossref
7097 (not reftex-auto-view-crossref-timer)
7098 (reftex-toggle-auto-view-crossref))
7099
7100 ;;; Run Hook ------------------------------------------------------------------
7101
7102 (run-hooks 'reftex-load-hook)
7103
7104 ;;; That's it! ----------------------------------------------------------------
7105
7106 (setq reftex-tables-dirty t) ; in case this file is evaluated by hand
7107 (provide 'reftex)
7108
7109 ;;;============================================================================
7110
7111 ;;; reftex.el ends here
7112