Fix up comment convention on the arch-tag lines.
[bpt/emacs.git] / lisp / textmodes / reftex.el
1 ;;; reftex.el --- minor mode for doing \label, \ref, \cite, \index in LaTeX
2 ;; Copyright (C) 1997, 1998, 1999, 2000, 2003, 2004, 2005,
3 ;; 2006, 2007, 2008 Free Software Foundation, Inc.
4
5 ;; Author: Carsten Dominik <dominik@science.uva.nl>
6 ;; Maintainer: auctex-devel@gnu.org
7 ;; Version: 4.31
8 ;; Keywords: tex
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26
27 ;;---------------------------------------------------------------------------
28 ;;
29 ;;; Commentary:
30 ;;
31 ;; RefTeX is a minor mode with distinct support for \ref, \label, \cite,
32 ;; and \index commands in (multi-file) LaTeX documents.
33 ;; - A table of contents provides easy access to any part of a document.
34 ;; - Labels are created semi-automatically.
35 ;; - Definition context of labels is provided when creating a reference.
36 ;; - Citations are simplified with efficient database lookup.
37 ;; - Text phrases can be collected in a file, for later global indexing.
38 ;; - The index preview buffer helps to check and edit index entries.
39 ;;
40 ;;
41 ;; INSTALLATION
42 ;; ------------
43 ;;
44 ;; - If this file is part of an X/Emacs distribution, it is installed.
45 ;; - For XEmacs 21.x, you need to install the RefTeX plug-in package
46 ;; available from the XEmacs distribution sites.
47 ;; - If you have downloaded this file from the maintainers webpage, follow
48 ;; the instructions in the INSTALL file of the distrubution.
49 ;;
50 ;; To turn RefTeX Mode on and off in a buffer, use `M-x reftex-mode'.
51 ;;
52 ;; To turn on RefTeX Mode for all LaTeX files, add the following lines
53 ;; to your .emacs file:
54 ;;
55 ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; AUCTeX LaTeX mode
56 ;; (add-hook 'latex-mode-hook 'turn-on-reftex) ; Emacs latex mode
57 ;;
58 ;;
59 ;; DOCUMENTATION
60 ;; -------------
61 ;;
62 ;; See below for a short summary of how to use RefTeX.
63 ;;
64 ;; There is an extensive texinfo document describing RefTeX in detail.
65 ;; One way to view this documentation is `M-x reftex-info RET'.
66 ;;
67 ;; The documentation in various formats is also available at
68 ;;
69 ;; http://zon.astro.uva.nl/~dominik/Tools/
70 ;;
71 ;;---------------------------------------------------------------------------
72 ;;
73 ;; Introduction
74 ;; ************
75 ;;
76 ;; RefTeX is a specialized package for support of labels, references,
77 ;; citations, and the index in LaTeX. RefTeX wraps itself round 4 LaTeX
78 ;; macros: `\label', `\ref', `\cite', and `\index'. Using these macros
79 ;; usually requires looking up different parts of the document and
80 ;; searching through BibTeX database files. RefTeX automates these
81 ;; time-consuming tasks almost entirely. It also provides functions to
82 ;; display the structure of a document and to move around in this
83 ;; structure quickly.
84 ;;
85 ;; *Note Imprint::, for information about who to contact for help, bug
86 ;; reports or suggestions.
87 ;;
88 ;; Environment
89 ;; ===========
90 ;;
91 ;; RefTeX needs to access all files which are part of a multifile
92 ;; document, and the BibTeX database files requested by the
93 ;; `\bibliography' command. To find these files, RefTeX will require a
94 ;; search path, i.e. a list of directories to check. Normally this list
95 ;; is stored in the environment variables `TEXINPUTS' and `BIBINPUTS'
96 ;; which are also used by RefTeX. However, on some systems these
97 ;; variables do not contain the full search path. If RefTeX does not work
98 ;; for you because it cannot find some files, read *Note Finding Files::.
99 ;;
100 ;; Entering RefTeX Mode
101 ;; ====================
102 ;;
103 ;; To turn RefTeX Mode on and off in a particular buffer, use `M-x
104 ;; reftex-mode'. To turn on RefTeX Mode for all LaTeX files, add the
105 ;; following lines to your `.emacs' file:
106 ;;
107 ;; (add-hook 'LaTeX-mode-hook 'turn-on-reftex) ; with AUCTeX LaTeX mode
108 ;; (add-hook 'latex-mode-hook 'turn-on-reftex) ; with Emacs latex mode
109 ;;
110 ;; RefTeX in a Nutshell
111 ;; ====================
112 ;;
113 ;; 1. Table of Contents
114 ;; Typing `C-c =' (`reftex-toc') will show a table of contents of the
115 ;; document. This buffer can display sections, labels and index
116 ;; entries defined in the document. From the buffer, you can jump
117 ;; quickly to every part of your document. Press `?' to get help.
118 ;;
119 ;; 2. Labels and References
120 ;; RefTeX helps to create unique labels and to find the correct key
121 ;; for references quickly. It distinguishes labels for different
122 ;; environments, knows about all standard environments (and many
123 ;; others), and can be configured to recognize any additional labeled
124 ;; environments you have defined yourself (variable
125 ;; `reftex-label-alist').
126 ;;
127 ;; * Creating Labels
128 ;; Type `C-c (' (`reftex-label') to insert a label at point.
129 ;; RefTeX will either
130 ;; - derive a label from context (default for section labels)
131 ;; - prompt for a label string (default for figures and
132 ;; tables) or
133 ;; - insert a simple label made of a prefix and a number (all
134 ;; other environments)
135 ;;
136 ;; Which labels are created how is configurable with the variable
137 ;; `reftex-insert-label-flags'.
138 ;;
139 ;; * Referencing Labels
140 ;; To make a reference, type `C-c )' (`reftex-reference'). This
141 ;; shows an outline of the document with all labels of a certain
142 ;; type (figure, equation,...) and some label context.
143 ;; Selecting a label inserts a `\ref{LABEL}' macro into the
144 ;; original buffer.
145 ;;
146 ;; 3. Citations
147 ;; Typing `C-c [' (`reftex-citation') will let you specify a regular
148 ;; expression to search in current BibTeX database files (as
149 ;; specified in the `\bibliography' command) and pull out a list of
150 ;; matches for you to choose from. The list is _formatted_ and
151 ;; sorted. The selected article is referenced as `\cite{KEY}' (see
152 ;; the variable `reftex-cite-format' if you want to insert different
153 ;; macros).
154 ;;
155 ;; 4. Index Support
156 ;; RefTeX helps to enter index entries. It also compiles all entries
157 ;; into an alphabetically sorted `*Index*' buffer which you can use
158 ;; to check and edit the entries. RefTeX knows about the standard
159 ;; index macros and can be configured to recognize any additional
160 ;; macros you have defined (`reftex-index-macros'). Multiple indices
161 ;; are supported.
162 ;;
163 ;; * Creating Index Entries
164 ;; To index the current selection or the word at point, type
165 ;; `C-c /' (`reftex-index-selection-or-word'). The default macro
166 ;; `reftex-index-default-macro' will be used. For a more
167 ;; complex entry type `C-c <' (`reftex-index'), select any of
168 ;; the index macros and enter the arguments with completion.
169 ;;
170 ;; * The Index Phrases File (Delayed Indexing)
171 ;; Type `C-c \' (`reftex-index-phrase-selection-or-word') to add
172 ;; the current word or selection to a special _index phrase
173 ;; file_. RefTeX can later search the document for occurrences
174 ;; of these phrases and let you interactively index the matches.
175 ;;
176 ;; * Displaying and Editing the Index
177 ;; To display the compiled index in a special buffer, type `C-c
178 ;; >' (`reftex-display-index'). From that buffer you can check
179 ;; and edit all entries.
180 ;;
181 ;; 5. Viewing Cross-References
182 ;; When point is on the KEY argument of a cross-referencing macro
183 ;; (`\label', `\ref', `\cite', `\bibitem', `\index', and variations)
184 ;; or inside a BibTeX database entry, you can press `C-c &'
185 ;; (`reftex-view-crossref') to display corresponding locations in the
186 ;; document and associated BibTeX database files.
187 ;; When the enclosing macro is `\cite' or `\ref' and no other message
188 ;; occupies the echo area, information about the citation or label
189 ;; will automatically be displayed in the echo area.
190 ;;
191 ;; 6. Multifile Documents
192 ;; Multifile Documents are fully supported. The included files must
193 ;; have a file variable `TeX-master' or `tex-main-file' pointing to
194 ;; the master file. RefTeX provides cross-referencing information
195 ;; from all parts of the document, and across document borders
196 ;; (`xr.sty').
197 ;;
198 ;; 7. Document Parsing
199 ;; RefTeX needs to parse the document in order to find labels and
200 ;; other information. It does it automatically once and updates its
201 ;; list internally when `reftex-label' and `reftex-index' are used.
202 ;; To enforce reparsing, call any of the commands described above
203 ;; with a raw `C-u' prefix, or press the `r' key in the label
204 ;; selection buffer, the table of contents buffer, or the index
205 ;; buffer.
206 ;;
207 ;; 8. AUCTeX
208 ;; If your major LaTeX mode is AUCTeX, RefTeX can cooperate with it
209 ;; (see variable `reftex-plug-into-AUCTeX'). AUCTeX contains style
210 ;; files which trigger appropriate settings in RefTeX, so that for
211 ;; many of the popular LaTeX packages no additional customizations
212 ;; will be necessary.
213 ;;
214 ;; 9. Useful Settings
215 ;; To make RefTeX faster for large documents, try these:
216 ;; (setq reftex-enable-partial-scans t)
217 ;; (setq reftex-save-parse-info t)
218 ;; (setq reftex-use-multiple-selection-buffers t)
219 ;;
220 ;; To integrate with AUCTeX, use
221 ;; (setq reftex-plug-into-AUCTeX t)
222 ;;
223 ;; To make your own LaTeX macro definitions known to RefTeX,
224 ;; customize the variables
225 ;; `reftex-label-alist' (for label macros/environments)
226 ;; `reftex-section-levels' (for sectioning commands)
227 ;; `reftex-cite-format' (for `\cite'-like macros)
228 ;; `reftex-index-macros' (for `\index'-like macros)
229 ;; `reftex-index-default-macro' (to set the default macro)
230 ;; If you have a large number of macros defined, you may want to write
231 ;; an AUCTeX style file to support them with both AUCTeX and RefTeX.
232 ;;
233 ;; 10. Where Next?
234 ;; Go ahead and use RefTeX. Use its menus until you have picked up
235 ;; the key bindings. For an overview of what you can do in each of
236 ;; the different special buffers, press `?'. Read the manual if you
237 ;; get stuck, of if you are curious what else might be available.
238 ;; The first part of the manual explains in a tutorial way how to use
239 ;; and customize RefTeX. The second part is a command and variable
240 ;; reference.
241 ;;
242 ;;---------------------------------------------------------------------------
243 ;;
244 ;; AUTHOR
245 ;; ======
246 ;;
247 ;; Carsten Dominik <dominik@science.uva.nl>
248 ;;
249 ;; with contributions from Stephen Eglen
250 ;;
251 ;; RefTeX is bundled with Emacs and available as a plug-in package for
252 ;; XEmacs 21.x. If you need to install it yourself, you can find a
253 ;; distribution at
254 ;;
255 ;; http://zon.astro.uva.nl/~dominik/Tools/
256 ;;
257 ;; THANKS TO:
258 ;; ---------
259 ;; Thanks to the people on the Net who have used RefTeX and helped
260 ;; developing it with their reports. In particular thanks to
261 ;;
262 ;; Fran Burstall, Alastair Burt, Soren Dayton, Stephen Eglen,
263 ;; Karl Eichwalder, Peter Galbraith, Dieter Kraft, Kai Grossjohann,
264 ;; Frank Harrell, Adrian Lanz, Rory Molinari, Stefan Monnier,
265 ;; Laurent Mugnier, Sudeep Kumar Palat, Daniel Polani, Robin Socha,
266 ;; Richard Stanton, Allan Strand, Jan Vroonhof, Christoph Wedler,
267 ;; Alan Williams.
268 ;;
269 ;; Finally thanks to Uwe Bolick who first got me (some years ago) into
270 ;; supporting LaTeX labels and references with an editor (which was
271 ;; MicroEmacs at the time).
272 ;;
273 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
274 ;;
275 ;;;;;;
276 \f
277 ;;; Code:
278
279 (eval-when-compile (require 'cl))
280
281 ;; Stuff that needs to be there when we use defcustom
282 (require 'custom)
283
284 (require 'easymenu)
285
286 (defvar reftex-tables-dirty t
287 "Flag showing if tables need to be re-computed.")
288
289 (eval-and-compile
290 (defun reftex-set-dirty (symbol value)
291 (setq reftex-tables-dirty t)
292 (set symbol value)))
293
294
295 ;;; =========================================================================
296 ;;;
297 ;;; Configuration variables
298
299 (require 'reftex-vars)
300
301
302 ;;; =========================================================================
303 ;;;
304 ;;; Define the formal stuff for a minor mode named RefTeX.
305 ;;;
306
307 (defconst reftex-version "RefTeX version 4.31"
308 "Version string for RefTeX.")
309
310 (defvar reftex-mode nil
311 "Determines if RefTeX mode is active.")
312 (make-variable-buffer-local 'reftex-mode)
313
314 (defvar reftex-mode-map (make-sparse-keymap)
315 "Keymap for RefTeX mode.")
316
317 (defvar reftex-mode-menu nil)
318 (defvar reftex-syntax-table nil)
319 (defvar reftex-syntax-table-for-bib nil)
320
321 (unless reftex-syntax-table
322 (setq reftex-syntax-table (copy-syntax-table))
323 (modify-syntax-entry ?\( "." reftex-syntax-table)
324 (modify-syntax-entry ?\) "." reftex-syntax-table))
325
326 (unless reftex-syntax-table-for-bib
327 (setq reftex-syntax-table-for-bib
328 (copy-syntax-table reftex-syntax-table))
329 (modify-syntax-entry ?\' "." reftex-syntax-table-for-bib)
330 (modify-syntax-entry ?\" "." reftex-syntax-table-for-bib)
331 (modify-syntax-entry ?\[ "." reftex-syntax-table-for-bib)
332 (modify-syntax-entry ?\] "." reftex-syntax-table-for-bib))
333
334 ;; The following definitions are out of place, but I need them here
335 ;; to make the compilation of reftex-mode not complain.
336 (defvar reftex-auto-view-crossref-timer nil
337 "The timer used for auto-view-crossref.")
338 (defvar reftex-toc-auto-recenter-timer nil
339 "The idle timer used to recenter the toc window.")
340
341 ;;; =========================================================================
342 ;;;
343 ;;; Parser functions
344
345 (autoload 'reftex-parse-one "reftex-parse"
346 "Re-parse this file." t)
347 (autoload 'reftex-parse-all "reftex-parse"
348 "Re-parse entire document." t)
349 (autoload 'reftex-do-parse "reftex-parse")
350 (autoload 'reftex-where-am-I "reftex-parse")
351 (autoload 'reftex-init-section-numbers "reftex-parse")
352 (autoload 'reftex-section-info "reftex-parse")
353 (autoload 'reftex-section-number "reftex-parse")
354 (autoload 'reftex-what-macro "reftex-parse")
355 (autoload 'reftex-what-macro-safe "reftex-parse")
356 (autoload 'reftex-index-info "reftex-parse")
357 (autoload 'reftex-index-info-safe "reftex-parse")
358 (autoload 'reftex-short-context "reftex-parse")
359 (autoload 'reftex-what-environment "reftex-parse")
360 (autoload 'reftex-what-special-env "reftex-parse")
361 (autoload 'reftex-move-over-touching-args "reftex-parse")
362 (autoload 'reftex-notice-new "reftex-parse")
363 (autoload 'reftex-nth-arg "reftex-parse")
364 (autoload 'reftex-locate-bibliography-files "reftex-parse")
365 (autoload 'reftex-ensure-index-support "reftex-parse")
366 (autoload 'reftex-everything-regexp "reftex-parse")
367
368
369 ;;; =========================================================================
370 ;;;
371 ;;; Labels and References
372
373 (autoload 'reftex-label-location "reftex-ref")
374 (autoload 'reftex-label-info-update "reftex-ref")
375 (autoload 'reftex-label-info "reftex-ref")
376 (autoload 'reftex-label "reftex-ref"
377 "Insert a unique label." t)
378 (autoload 'reftex-reference "reftex-ref"
379 "Make a LaTeX reference." t)
380 (autoload 'reftex-varioref-vref "reftex-ref"
381 "Make a varioref reference." t)
382 (autoload 'reftex-fancyref-fref "reftex-ref"
383 "Make a fancyref \\fref reference." t)
384 (autoload 'reftex-fancyref-Fref "reftex-ref"
385 "Make a fancyref \\Fref reference." t)
386 (autoload 'reftex-show-label-location "reftex-ref")
387 (autoload 'reftex-query-label-type "reftex-ref")
388 (autoload 'reftex-goto-label "reftex-ref"
389 "Prompt for label name and go to that location." t)
390
391 ;;; =========================================================================
392 ;;;
393 ;;; Table of contents
394
395 (autoload 'reftex-toc "reftex-toc"
396 "Show the table of contents for the current document." t)
397 (autoload 'reftex-toc-recenter "reftex-toc"
398 "Display the TOC window and highlight line corresponding to current position." t)
399 (autoload 'reftex-toggle-auto-toc-recenter "reftex-toc"
400 "Toggle automatic recentering of TOC window." t)
401
402 ;;; =========================================================================
403 ;;;
404 ;;; BibTeX citations.
405
406 (autoload 'reftex-citep "reftex-cite")
407 (autoload 'reftex-citet "reftex-cite")
408 (autoload 'reftex-make-cite-echo-string "reftex-cite")
409 (autoload 'reftex-get-bibfile-list "reftex-cite")
410 (autoload 'reftex-pop-to-bibtex-entry "reftex-cite")
411 (autoload 'reftex-end-of-bib-entry "reftex-cite")
412 (autoload 'reftex-parse-bibtex-entry "reftex-cite")
413 (autoload 'reftex-citation "reftex-cite"
414 "Make a citation using BibTeX database files." t)
415 (autoload 'reftex-default-bibliography "reftex-cite")
416 (autoload 'reftex-bib-or-thebib "reftex-cite")
417 (autoload 'reftex-create-bibtex-file "reftex-cite")
418
419 ;;; =========================================================================
420 ;;;
421 ;;; Selection
422
423 (autoload 'reftex-select-label-mode "reftex-sel")
424 (autoload 'reftex-select-bib-mode "reftex-sel")
425 (autoload 'reftex-find-start-point "reftex-sel")
426 (autoload 'reftex-insert-docstruct "reftex-sel")
427 (autoload 'reftex-get-offset "reftex-sel")
428 (autoload 'reftex-select-item "reftex-sel")
429
430
431 ;;; =========================================================================
432 ;;;
433 ;;; Index support
434
435 (autoload 'reftex-index "reftex-index"
436 "Query for an index macro and insert it along with its argments." t)
437 (autoload 'reftex-index-selection-or-word "reftex-index"
438 "Put selection or the word near point into the default index macro." t)
439 (autoload 'reftex-index-phrase-selection-or-word "reftex-index"
440 "Put selection or the word near point into Index Phrases File." t)
441 (autoload 'reftex-display-index "reftex-index"
442 "Display a buffer with an index compiled from the current document." t)
443 (autoload 'reftex-index-visit-phrases-buffer "reftex-index"
444 "Visit the Index Phrases File." t)
445 (autoload 'reftex-index-phrases-mode "reftex-index"
446 "Major mode for managing the Index phrases of a LaTeX document." t)
447 (autoload 'reftex-index-complete-tag "reftex-index")
448 (autoload 'reftex-index-complete-key "reftex-index")
449 (autoload 'reftex-index-show-entry "reftex-index")
450 (autoload 'reftex-index-select-tag "reftex-index")
451
452
453 ;;; =========================================================================
454 ;;;
455 ;;; View cross references
456
457 (autoload 'reftex-view-crossref "reftex-dcr"
458 "View cross reference of \\ref or \\cite macro at point." t)
459 (autoload 'reftex-mouse-view-crossref "reftex-dcr"
460 "View cross reference of \\ref or \\cite macro where you click." t)
461 (autoload 'reftex-toggle-auto-view-crossref "reftex-dcr")
462 (autoload 'reftex-view-crossref-from-bibtex "reftex-dcr"
463 "View location in a LaTeX document which cites the BibTeX entry at point." t)
464
465
466 ;;; =========================================================================
467 ;;;
468 ;;; Operations on entire Multifile documents
469
470 (autoload 'reftex-create-tags-file "reftex-global"
471 "Create TAGS file by running `etags' on the current document." t)
472 (autoload 'reftex-grep-document "reftex-global"
473 "Run grep query through all files related to this document." t)
474 (autoload 'reftex-search-document "reftex-global"
475 "Regexp search through all files of the current TeX document." t)
476 (autoload 'reftex-query-replace-document "reftex-global"
477 "Run a query-replace-regexp of FROM with TO over the entire TeX document." t)
478 (autoload 'reftex-find-duplicate-labels "reftex-global"
479 "Produce a list of all duplicate labels in the document." t)
480 (autoload 'reftex-change-label "reftex-global"
481 "Query replace FROM with TO in all \\label and \\ref commands." t)
482 (autoload 'reftex-renumber-simple-labels "reftex-global"
483 "Renumber all simple labels in the document to make them sequentially." t)
484 (autoload 'reftex-save-all-document-buffers "reftex-global"
485 "Save all documents associated with the current document." t)
486
487
488 ;;; =========================================================================
489 ;;;
490 ;;; AUCTeX Interface
491
492 (autoload 'reftex-arg-label "reftex-auc")
493 (autoload 'reftex-arg-cite "reftex-auc")
494 (autoload 'reftex-arg-index-tag "reftex-auc")
495 (autoload 'reftex-arg-index "reftex-auc")
496 (autoload 'reftex-plug-into-AUCTeX "reftex-auc")
497 (autoload 'reftex-toggle-plug-into-AUCTeX "reftex-auc"
498 "Toggle Interface between AUCTeX and RefTeX on and off." t)
499 (autoload 'reftex-add-label-environments "reftex-auc")
500 (autoload 'reftex-add-to-label-alist "reftex-auc")
501 (autoload 'reftex-add-section-levels "reftex-auc")
502 (autoload 'reftex-notice-new-section "reftex-auc")
503
504 ;;;###autoload
505 (defun turn-on-reftex ()
506 "Turn on RefTeX mode."
507 (reftex-mode t))
508
509 ;;;###autoload
510 (defun reftex-mode (&optional arg)
511 "Minor mode with distinct support for \\label, \\ref and \\cite in LaTeX.
512
513 \\<reftex-mode-map>A Table of Contents of the entire (multifile) document with browsing
514 capabilities is available with `\\[reftex-toc]'.
515
516 Labels can be created with `\\[reftex-label]' and referenced with `\\[reftex-reference]'.
517 When referencing, you get a menu with all labels of a given type and
518 context of the label definition. The selected label is inserted as a
519 \\ref macro.
520
521 Citations can be made with `\\[reftex-citation]' which will use a regular expression
522 to pull out a *formatted* list of articles from your BibTeX
523 database. The selected citation is inserted as a \\cite macro.
524
525 Index entries can be made with `\\[reftex-index-selection-or-word]' which indexes the word at point
526 or the current selection. More general index entries are created with
527 `\\[reftex-index]'. `\\[reftex-display-index]' displays the compiled index.
528
529 Most command have help available on the fly. This help is accessed by
530 pressing `?' to any prompt mentioning this feature.
531
532 Extensive documentation about RefTeX is available in Info format.
533 You can view this information with `\\[reftex-info]'.
534
535 \\{reftex-mode-map}
536 Under X, these and other functions will also be available as `Ref' menu
537 on the menu bar.
538
539 ------------------------------------------------------------------------------"
540
541 (interactive "P")
542 (setq reftex-mode (not (or (and (null arg) reftex-mode)
543 (<= (prefix-numeric-value arg) 0))))
544
545 (if reftex-mode
546 (progn
547 ;; Mode was turned on
548 (easy-menu-add reftex-mode-menu)
549 (and reftex-plug-into-AUCTeX
550 (reftex-plug-into-AUCTeX))
551 (unless (get 'reftex-auto-view-crossref 'initialized)
552 (and reftex-auto-view-crossref
553 (reftex-toggle-auto-view-crossref))
554 (put 'reftex-auto-view-crossref 'initialized t))
555 (unless (get 'reftex-auto-recenter-toc 'initialized)
556 (and (eq reftex-auto-recenter-toc t)
557 (reftex-toggle-auto-toc-recenter))
558 (put 'reftex-auto-recenter-toc 'initialized t))
559
560 ;; Prepare the special syntax tables.
561 (setq reftex-syntax-table (copy-syntax-table (syntax-table)))
562 (modify-syntax-entry ?\( "." reftex-syntax-table)
563 (modify-syntax-entry ?\) "." reftex-syntax-table)
564
565 (setq reftex-syntax-table-for-bib
566 (copy-syntax-table reftex-syntax-table))
567 (modify-syntax-entry ?\' "." reftex-syntax-table-for-bib)
568 (modify-syntax-entry ?\" "." reftex-syntax-table-for-bib)
569 (modify-syntax-entry ?\[ "." reftex-syntax-table-for-bib)
570 (modify-syntax-entry ?\] "." reftex-syntax-table-for-bib)
571
572 (run-hooks 'reftex-mode-hook))
573 ;; Mode was turned off
574 (easy-menu-remove reftex-mode-menu)))
575
576 (if (fboundp 'add-minor-mode)
577 ;; Use it so that we get the extras
578 (progn
579 (put 'reftex-mode :included '(memq major-mode '(latex-mode tex-mode)))
580 (put 'reftex-mode :menu-tag "RefTeX Mode")
581 (add-minor-mode 'reftex-mode " Ref" reftex-mode-map))
582 ;; The standard way
583 (unless (assoc 'reftex-mode minor-mode-alist)
584 (push '(reftex-mode " Ref") minor-mode-alist))
585 (unless (assoc 'reftex-mode minor-mode-map-alist)
586 (push (cons 'reftex-mode reftex-mode-map) minor-mode-map-alist)))
587
588 (defvar reftex-docstruct-symbol)
589 (defun reftex-kill-buffer-hook ()
590 "Save RefTeX's parse file for this buffer if the information has changed."
591 ;; Save the parsing information if it was modified.
592 ;; This function should be installed in `kill-buffer-hook'.
593 ;; We are careful to make sure nothing goes wring in this function.
594 (when (and (boundp 'reftex-mode) reftex-mode
595 (boundp 'reftex-save-parse-info) reftex-save-parse-info
596 (boundp 'reftex-docstruct-symbol) reftex-docstruct-symbol
597 (symbol-value reftex-docstruct-symbol)
598 (get reftex-docstruct-symbol 'modified))
599 ;; Write the file.
600 (condition-case nil
601 (reftex-access-parse-file 'write)
602 (error nil))))
603
604 (defun reftex-kill-emacs-hook ()
605 "Call `reftex-kill-buffer-hook' on all buffers."
606 ;; This function should be installed in `kill-emacs-hook'.
607 (save-excursion
608 (mapcar (lambda (buf)
609 (set-buffer buf)
610 (reftex-kill-buffer-hook))
611 (buffer-list))))
612
613 ;;; =========================================================================
614 ;;;
615 ;;; Silence warnings about variables in other packages.
616 (defvar TeX-master)
617 (defvar LaTeX-section-hook)
618 (defvar LaTeX-label-function)
619 (defvar tex-main-file)
620 (defvar outline-minor-mode)
621 (defvar font-lock-mode)
622 (defvar font-lock-keywords)
623 (defvar font-lock-fontify-region-function)
624 (defvar font-lock-syntactic-keywords)
625
626 ;;; =========================================================================
627 ;;;
628 ;;; Multibuffer Variables
629 ;;;
630 ;;; Technical notes: These work as follows: We keep just one list
631 ;;; of labels for each master file - this can save a lot of memory.
632 ;;; `reftex-master-index-list' is an alist which connects the true file name
633 ;;; of each master file with the symbols holding the information on that
634 ;;; document. Each buffer has local variables which point to these symbols.
635
636 ;; List of variables which handle the multifile stuff.
637 ;; This list is used to tie, untie, and reset these symbols.
638 (defconst reftex-multifile-symbols
639 '(reftex-docstruct-symbol))
640
641 ;; Alist connecting master file names with the corresponding lisp symbols.
642 (defvar reftex-master-index-list nil)
643
644 ;; Last index used for a master file.
645 (defvar reftex-multifile-index 0)
646
647 ;; Variable holding the symbol with the label list of the document.
648 (defvar reftex-docstruct-symbol nil)
649 (make-variable-buffer-local 'reftex-docstruct-symbol)
650
651 (defun reftex-next-multifile-index ()
652 ;; Return the next free index for multifile symbols.
653 (incf reftex-multifile-index))
654
655 (defun reftex-tie-multifile-symbols ()
656 ;; Tie the buffer-local symbols to globals connected with the master file.
657 ;; If the symbols for the current master file do not exist, they are created.
658
659 (let* ((master (file-truename (reftex-TeX-master-file)))
660 (index (assoc master reftex-master-index-list))
661 (symlist reftex-multifile-symbols)
662 symbol symname newflag)
663 ;; Find the correct index.
664 (if index
665 ;; symbols do exist
666 (setq index (cdr index))
667 ;; Get a new index and add info to the alist.
668 (setq index (reftex-next-multifile-index)
669 newflag t)
670 (push (cons master index) reftex-master-index-list))
671
672 ;; Get/create symbols and tie them.
673 (while symlist
674 (setq symbol (car symlist)
675 symlist (cdr symlist)
676 symname (symbol-name symbol))
677 (set symbol (intern (concat symname "-" (int-to-string index))))
678 (put (symbol-value symbol) :master-index index)
679 ;; Initialize if new symbols.
680 (when newflag
681 (set (symbol-value symbol) nil)
682 (put (symbol-value symbol) 'reftex-index-macros-style '(default))))
683
684 ;; Return t if the symbols did already exist, nil when we've made them.
685 (not newflag)))
686
687 (defun reftex-untie-multifile-symbols ()
688 ;; Remove ties from multifile symbols, so that next use makes new ones.
689 (let ((symlist reftex-multifile-symbols)
690 (symbol nil))
691 (while symlist
692 (setq symbol (car symlist)
693 symlist (cdr symlist))
694 (set symbol nil))))
695
696 (defun reftex-TeX-master-file ()
697 ;; Return the name of the master file associated with the current buffer.
698 ;; When AUCTeX is loaded, we will use it's more sophisticated method.
699 ;; We also support the default TeX and LaTeX modes by checking for a
700 ;; variable tex-main-file.
701 (let
702 ((master
703 (cond
704 ((fboundp 'TeX-master-file) ; AUCTeX is loaded. Use its mechanism.
705 (condition-case nil
706 (TeX-master-file t)
707 (error (buffer-file-name))))
708 ((fboundp 'tex-main-file) (tex-main-file)) ; Emacs LaTeX mode
709 ((boundp 'TeX-master) ; The variable is defined - lets use it.
710 (cond
711 ((eq TeX-master t)
712 (buffer-file-name))
713 ((eq TeX-master 'shared)
714 (setq TeX-master (read-file-name "Master file: "
715 nil nil t nil)))
716 (TeX-master)
717 (t
718 (setq TeX-master (read-file-name "Master file: "
719 nil nil t nil)))))
720 ((boundp 'tex-main-file)
721 ;; This is the variable from the default TeX modes.
722 (cond
723 ((stringp tex-main-file)
724 ;; ok, this must be it
725 tex-main-file)
726 (t
727 ;; In this case, the buffer is its own master.
728 (buffer-file-name))))
729 (t
730 ;; Know nothing about master file. Assume this is a master file.
731 (buffer-file-name)))))
732 (cond
733 ((null master)
734 (error "Need a filename for this buffer, please save it first"))
735 ((or (file-exists-p (concat master ".tex"))
736 (reftex-get-buffer-visiting (concat master ".tex")))
737 ;; Ahh, an extra .tex was missing...
738 (setq master (concat master ".tex")))
739 ((or (file-exists-p master)
740 (reftex-get-buffer-visiting master))
741 ;; We either see the file, or have a buffer on it. OK.
742 )
743 (t
744 ;; Use buffer file name.
745 (setq master (buffer-file-name))))
746 (expand-file-name master)))
747
748 (defun reftex-is-multi ()
749 ;; Tell if this is a multifile document. When not sure, say yes.
750 (let ((entry (assq 'is-multi (symbol-value reftex-docstruct-symbol))))
751 (if entry
752 (nth 1 entry)
753 t)))
754
755 (defun reftex-set-cite-format (value)
756 "Set the document-local value of `reftex-cite-format'.
757 When such a value exists, it overwrites the setting given with
758 `reftex-cite-format'. See the documentation of `reftex-cite-format'
759 for possible values. This function should be used from AUCTeX style files."
760 (unless reftex-docstruct-symbol
761 (reftex-tie-multifile-symbols))
762 (when (and reftex-docstruct-symbol
763 (symbolp reftex-docstruct-symbol))
764 (put reftex-docstruct-symbol 'reftex-cite-format value)))
765
766 (defun reftex-get-cite-format ()
767 ;; Return the current citation format. Either the document-local value in
768 ;; reftex-cite-format-symbol, or the global value in reftex-cite-format.
769 (if (and reftex-docstruct-symbol
770 (symbolp reftex-docstruct-symbol)
771 (get reftex-docstruct-symbol 'reftex-cite-format))
772 (get reftex-docstruct-symbol 'reftex-cite-format)
773 reftex-cite-format))
774
775 (defun reftex-add-index-macros (entry-list)
776 "Add index macro descriptions to `reftex-index-macros-style'.
777 The format of ENTRY-LIST is exactly like `reftex-index-macros'. See there
778 for details.
779 This function makes it possible to support RefTeX from AUCTeX style files.
780 The entries in ENTRY-LIST will be processed after the user settings in
781 `reftex-index-entries', and before the defaults. Any changes made to
782 `reftex-label-alist-style' will raise a flag to the effect that
783 the label information is recompiled on next use."
784 (unless reftex-docstruct-symbol
785 (reftex-tie-multifile-symbols))
786 (when (and reftex-docstruct-symbol
787 (symbolp reftex-docstruct-symbol))
788 (let ((list (get reftex-docstruct-symbol 'reftex-index-macros-style))
789 entry changed)
790 (while entry-list
791 (setq entry (pop entry-list))
792 ;; When it is a symbol, remove all other symbols
793 (and (symbolp entry)
794 (not (memq entry list))
795 (setq list (reftex-remove-symbols-from-list list)))
796 ;; Add to list unless already member
797 (unless (member entry list)
798 (setq reftex-tables-dirty t
799 changed t)
800 (push entry list)))
801 (when changed
802 (put reftex-docstruct-symbol 'reftex-index-macros-style list)))))
803
804 ;;; =========================================================================
805 ;;;
806 ;;; Functions to compile the tables, reset the mode etc.
807
808 ;; The following constants are derived from `reftex-label-alist'.
809
810 ;; Prompt used for label type queries directed to the user.
811 (defvar reftex-type-query-prompt nil)
812
813 ;; Help string for label type queries.
814 (defvar reftex-type-query-help nil)
815
816 ;; Alist relating label type to reference format.
817 (defvar reftex-typekey-to-format-alist nil)
818
819 ;; Alist relating label type to label prefix.
820 (defvar reftex-typekey-to-prefix-alist nil)
821
822 ;; Alist relating environments or macros to label type and context regexp.
823 (defvar reftex-env-or-mac-alist nil)
824
825 ;; List of special environment parser functions
826 (defvar reftex-special-env-parsers nil)
827
828 ;; List of macros carrying a label.
829 (defvar reftex-label-mac-list nil)
830
831 ;; List of environments carrying a label.
832 (defvar reftex-label-env-list nil)
833
834 ;; List of all typekey letters in use.
835 (defvar reftex-typekey-list nil)
836
837 ;; Alist relating magic words to a label type.
838 (defvar reftex-words-to-typekey-alist nil)
839 ;; Alist relating label prefixes to a label type.
840 (defvar reftex-prefix-to-typekey-alist nil)
841
842 ;; The last list-of-labels entry used in a reference.
843 (defvar reftex-last-used-reference (list nil nil nil nil))
844
845 ;; Alist relating index macros to other info.
846 (defvar reftex-key-to-index-macro-alist nil)
847 ;; Prompt for index macro queries
848 (defvar reftex-query-index-macro-prompt nil)
849 ;; Help string for index macro queries
850 (defvar reftex-query-index-macro-help nil)
851
852 ;; The message when follow-mode is suspended
853 (defvar reftex-no-follow-message
854 "No follow-mode into unvisited file. Press SPC to visit it.")
855 (defvar reftex-no-info-message
856 "%s: info not available, use `\\[reftex-view-crossref]' to get it.")
857
858 ;; Global variables used for communication between functions.
859 (defvar reftex-default-context-position nil)
860 (defvar reftex-location-start nil)
861 (defvar reftex-call-back-to-this-buffer nil)
862 (defvar reftex-select-return-marker (make-marker))
863 (defvar reftex-active-toc nil)
864 (defvar reftex-tex-path nil)
865 (defvar reftex-bib-path nil)
866 (defvar reftex-select-marked nil)
867 (defvar reftex-last-follow-point nil)
868 (defvar reftex-latex-syntax-table nil)
869 (defvar reftex-prefix nil)
870 (defvar reftex-section-levels-all nil)
871 (defvar reftex-buffers-with-changed-invisibility nil)
872 (defvar reftex-callback-fwd t)
873 (defvar reftex-last-toc-master nil
874 "Stores the name of the tex file that `reftex-toc' was last run on.")
875 ;; Marker for return point from recursive edit
876 (defvar reftex-recursive-edit-marker (make-marker))
877
878 ;; List of buffers created temporarily for lookup, which should be killed.
879 (defvar reftex-buffers-to-kill nil)
880
881 ;; Regexp to find anything.
882 (defvar reftex-section-regexp nil)
883 (defvar reftex-section-or-include-regexp nil)
884 (defvar reftex-index-macro-regexp nil)
885 (defvar reftex-index-level-re nil)
886 (defvar reftex-index-key-end-re nil)
887 (defvar reftex-find-index-entry-regexp-format nil)
888 (defvar reftex-everything-regexp nil)
889 (defvar reftex-everything-regexp-no-index nil)
890 (defvar reftex-index-re nil)
891 (defvar reftex-find-citation-regexp-format
892 "\\\\\\([a-zA-Z]*cite[*a-zA-Z]*\\*?\\|bibentry\\)\\(\\[[^]]*\\]\\|{[^}]*}\\)*{\\([^}]*,\\)?\\(%s\\)[},]")
893 (defvar reftex-find-reference-format
894 "\\\\\\(ref[a-zA-Z]*\\|[a-zA-Z]*ref\\(range\\)?\\)\\*?\\(\\[[^]]*\\]\\|{[^}]*}\\)*{\\(%s\\)}")
895 (defvar reftex-macros-with-labels nil)
896 (defvar reftex-macros-with-index nil)
897 (defvar reftex-index-macro-alist nil)
898 (defvar reftex-find-label-regexp-format nil)
899 (defvar reftex-find-label-regexp-format2 nil)
900
901 (defvar reftex-memory nil
902 "Memorizes old variable values to indicate changes in these variables.")
903
904 ;; A list of all variables in the cache.
905 ;; The cache is used to save the compiled versions of some variables.
906 (defconst reftex-cache-variables
907 '(reftex-memory ;; This MUST ALWAYS be the first!
908
909 ;; Outline
910 reftex-section-levels-all
911
912 ;; Labels
913 reftex-env-or-mac-alist
914 reftex-special-env-parsers
915 reftex-macros-with-labels
916 reftex-label-mac-list
917 reftex-label-env-list
918 reftex-typekey-list
919 reftex-typekey-to-format-alist
920 reftex-typekey-to-prefix-alist
921 reftex-words-to-typekey-alist
922 reftex-prefix-to-typekey-alist
923 reftex-type-query-prompt
924 reftex-type-query-help
925
926 ;; Index
927 reftex-index-macro-alist
928 reftex-macros-with-index
929 reftex-query-index-macro-prompt
930 reftex-query-index-macro-help
931 reftex-key-to-index-macro-alist
932
933 ;; Regular expressions
934 reftex-section-regexp
935 reftex-section-or-include-regexp
936 reftex-index-re
937 reftex-everything-regexp
938 reftex-everything-regexp-no-index
939 reftex-find-label-regexp-format
940 reftex-find-label-regexp-format2
941 reftex-find-index-entry-regexp-format
942 ))
943
944 (defun reftex-ensure-compiled-variables ()
945 ;; Recompile the label alist when necessary
946 (let* ((mem reftex-memory)
947 (cache (get reftex-docstruct-symbol 'reftex-cache))
948 (cmem (car cache))
949 (alist reftex-label-alist)
950 (levels (get reftex-docstruct-symbol 'reftex-section-levels))
951 (style (get reftex-docstruct-symbol 'reftex-label-alist-style))
952 (default reftex-default-label-alist-entries)
953 (index reftex-index-macros)
954 (istyle (get reftex-docstruct-symbol 'reftex-index-macros-style)))
955 (cond
956 (reftex-tables-dirty (reftex-compile-variables))
957 ((and (eq alist (nth 0 mem))
958 (eq levels (nth 1 mem))
959 (eq style (nth 2 mem))
960 (eq default (nth 3 mem))
961 (eq index (nth 4 mem))
962 (eq istyle (nth 5 mem)))) ;; everything is OK
963 ((and (eq alist (nth 0 cmem))
964 (eq levels (nth 1 cmem))
965 (eq style (nth 2 cmem))
966 (eq default (nth 2 cmem))
967 (eq index (nth 4 cmem))
968 (eq istyle (nth 5 cmem)))
969 ;; restore the cache
970 (message "Restoring cache")
971 (mapcar (lambda (sym) (set sym (pop cache))) reftex-cache-variables))
972 (t (reftex-compile-variables)))))
973
974 (defun reftex-reset-mode ()
975 "Reset RefTeX Mode.
976 This will re-compile the configuration information and remove all
977 current scanning information and the parse file to enforce a rescan
978 on next use."
979 (interactive)
980
981 ;; Reset the file search path variables
982 (loop for prop in '(status master-dir recursive-path rec-type) do
983 (put 'reftex-tex-path prop nil)
984 (put 'reftex-bib-path prop nil))
985
986 ;; Kill temporary buffers associated with RefTeX - just in case they
987 ;; were not cleaned up properly
988 (save-excursion
989 (let ((buffer-list '("*RefTeX Help*" "*RefTeX Select*"
990 "*Duplicate Labels*" "*toc*" " *RefTeX-scratch*"))
991 buf)
992 (while (setq buf (pop buffer-list))
993 (if (get-buffer buf)
994 (kill-buffer buf))))
995 (reftex-erase-all-selection-and-index-buffers))
996
997 ;; Make sure the current document will be rescanned soon.
998 (reftex-reset-scanning-information)
999
1000 ;; Remove any parse info file
1001 (reftex-access-parse-file 'kill)
1002
1003 ;; Plug functions into AUCTeX if the user option says so.
1004 (and reftex-plug-into-AUCTeX
1005 (reftex-plug-into-AUCTeX))
1006
1007 (reftex-compile-variables))
1008
1009 ;;;###autoload
1010 (defun reftex-reset-scanning-information ()
1011 "Reset the symbols containing information from buffer scanning.
1012 This enforces rescanning the buffer on next use."
1013 (if (string= reftex-last-toc-master (reftex-TeX-master-file))
1014 (reftex-erase-buffer "*toc*"))
1015 (let ((symlist reftex-multifile-symbols)
1016 symbol)
1017 (while symlist
1018 (setq symbol (car symlist)
1019 symlist (cdr symlist))
1020 (if (and (symbolp (symbol-value symbol))
1021 (not (null (symbol-value symbol))))
1022 (set (symbol-value symbol) nil)))))
1023
1024 (defun reftex-erase-all-selection-and-index-buffers ()
1025 ;; Remove all selection buffers associated with current document.
1026 (mapc
1027 (lambda (type)
1028 (reftex-erase-buffer (reftex-make-selection-buffer-name type)))
1029 reftex-typekey-list)
1030 ;; Kill all index buffers
1031 (mapc
1032 (lambda (tag)
1033 (reftex-kill-buffer (reftex-make-index-buffer-name tag)))
1034 (cdr (assoc 'index-tags (symbol-value reftex-docstruct-symbol)))))
1035
1036 (defun reftex-compile-variables ()
1037 ;; Compile the information in reftex-label-alist & Co.
1038
1039 (message "Compiling label environment definitions...")
1040
1041 ;; Update AUCTeX style information
1042 (when (and (featurep 'tex-site) (fboundp 'TeX-update-style))
1043 (condition-case nil (TeX-update-style) (error nil)))
1044
1045 ;; Record that we have done this, and what we have used.
1046 (setq reftex-tables-dirty nil)
1047 (setq reftex-memory
1048 (list reftex-label-alist
1049 (get reftex-docstruct-symbol 'reftex-section-levels)
1050 (get reftex-docstruct-symbol 'reftex-label-alist-style)
1051 reftex-default-label-alist-entries
1052 reftex-index-macros
1053 (get reftex-docstruct-symbol 'reftex-index-macros-style)))
1054
1055 ;; Compile information in reftex-label-alist
1056 (let ((all (reftex-uniquify-by-car
1057 (reftex-splice-symbols-into-list
1058 (append reftex-label-alist
1059 (get reftex-docstruct-symbol
1060 'reftex-label-alist-style)
1061 reftex-default-label-alist-entries)
1062 reftex-label-alist-builtin)
1063 '(nil)))
1064 (all-index (reftex-uniquify-by-car
1065 (reftex-splice-symbols-into-list
1066 (append reftex-index-macros
1067 (get reftex-docstruct-symbol
1068 'reftex-index-macros-style)
1069 '(default))
1070 reftex-index-macros-builtin)))
1071 entry env-or-mac typekeychar typekey prefix context word
1072 fmt reffmt labelfmt wordlist qh-list macros-with-labels
1073 nargs nlabel opt-args cell sum i
1074 macro verify repeat nindex tag key toc-level toc-levels)
1075
1076 (setq reftex-words-to-typekey-alist nil
1077 reftex-prefix-to-typekey-alist
1078 '(("sec:" . "s") ("cha:" . "s") ("chap:" . "s"))
1079 reftex-typekey-list nil
1080 reftex-typekey-to-format-alist nil
1081 reftex-typekey-to-prefix-alist nil
1082 reftex-env-or-mac-alist nil
1083 reftex-label-env-list nil
1084 reftex-label-mac-list nil)
1085 (while all
1086 (catch 'next-entry
1087 (setq entry (car all)
1088 env-or-mac (car entry)
1089 entry (cdr entry)
1090 all (cdr all))
1091 (if (null env-or-mac)
1092 (setq env-or-mac ""))
1093 (if (stringp (car entry))
1094 ;; This is before version 2.00 - convert entry to new format
1095 ;; This is just to keep old users happy
1096 (setq entry (cons (string-to-char (car entry))
1097 (cons (concat (car entry) ":")
1098 (cdr entry)))))
1099 (setq typekeychar (nth 0 entry)
1100 typekey (if typekeychar (char-to-string typekeychar) nil)
1101 prefix (nth 1 entry)
1102 fmt (nth 2 entry)
1103 context (nth 3 entry)
1104 wordlist (nth 4 entry)
1105 toc-level (nth 5 entry))
1106 (if (stringp wordlist)
1107 ;; This is before version 2.04 - convert to new format
1108 (setq wordlist (nthcdr 4 entry)))
1109
1110 (if (and (stringp fmt)
1111 (string-match "@" fmt))
1112 ;; Special syntax for specifying a label format
1113 (setq fmt (split-string fmt "@+"))
1114 (setq fmt (list "\\label{%s}" fmt)))
1115 (setq labelfmt (car fmt)
1116 reffmt (nth 1 fmt))
1117 ;; Note a new typekey
1118 (if typekey
1119 (add-to-list 'reftex-typekey-list typekey))
1120 (if (and typekey prefix
1121 (not (assoc prefix reftex-prefix-to-typekey-alist)))
1122 (add-to-list 'reftex-prefix-to-typekey-alist
1123 (cons prefix typekey)))
1124 (if (and typekey prefix
1125 (not (assoc typekey reftex-typekey-to-prefix-alist)))
1126 (add-to-list 'reftex-typekey-to-prefix-alist
1127 (cons typekey prefix)))
1128 ;; Check if this is a macro or environment
1129 (cond
1130 ((symbolp env-or-mac)
1131 ;; A special parser function
1132 (unless (fboundp env-or-mac)
1133 (message "Warning: %s does not seem to be a valid function"
1134 env-or-mac))
1135 (setq nargs nil nlabel nil opt-args nil)
1136 (add-to-list 'reftex-special-env-parsers env-or-mac)
1137 (setq env-or-mac (symbol-name env-or-mac)))
1138 ((string-match "\\`\\\\" env-or-mac)
1139 ;; It's a macro
1140 (let ((result (reftex-parse-args env-or-mac)))
1141 (setq env-or-mac (or (first result) env-or-mac)
1142 nargs (second result)
1143 nlabel (third result)
1144 opt-args (fourth result))
1145 (if nlabel (add-to-list 'macros-with-labels env-or-mac)))
1146 (if typekey (add-to-list 'reftex-label-mac-list env-or-mac)))
1147 (t
1148 ;; It's an environment
1149 (setq nargs nil nlabel nil opt-args nil)
1150 (cond ((string= env-or-mac "any"))
1151 ((string= env-or-mac ""))
1152 ((string= env-or-mac "section"))
1153 (t
1154 (add-to-list 'reftex-label-env-list env-or-mac)
1155 (if toc-level
1156 (let ((string (format "begin{%s}" env-or-mac)))
1157 (or (assoc string toc-levels)
1158 (push (cons string toc-level) toc-levels))))))))
1159 ;; Translate some special context cases
1160 (when (assq context reftex-default-context-regexps)
1161 (setq context
1162 (format
1163 (cdr (assq context reftex-default-context-regexps))
1164 (regexp-quote env-or-mac))))
1165 ;; See if this is the first format for this typekey
1166 (and reffmt
1167 (not (assoc typekey reftex-typekey-to-format-alist))
1168 (push (cons typekey reffmt) reftex-typekey-to-format-alist))
1169 ;; See if this is the first definition for this env-or-mac
1170 (and (not (string= env-or-mac "any"))
1171 (not (string= env-or-mac ""))
1172 (not (assoc env-or-mac reftex-env-or-mac-alist))
1173 (push (list env-or-mac typekey context labelfmt
1174 nargs nlabel opt-args)
1175 reftex-env-or-mac-alist))
1176 ;; Are the magic words regular expressions? Quote normal words.
1177 (if (eq (car wordlist) 'regexp)
1178 (setq wordlist (cdr wordlist))
1179 (setq wordlist (mapcar 'regexp-quote wordlist)))
1180 ;; Remember the first association of each word.
1181 (while (stringp (setq word (pop wordlist)))
1182 (or (assoc word reftex-words-to-typekey-alist)
1183 (push (cons word typekey) reftex-words-to-typekey-alist)))
1184 (cond
1185 ((string= "" env-or-mac) nil)
1186 ((setq cell (assoc typekey qh-list))
1187 (push env-or-mac (cdr cell)))
1188 (typekey
1189 (push (list typekey env-or-mac) qh-list)))))
1190
1191 (setq reftex-typekey-to-prefix-alist
1192 (nreverse reftex-typekey-to-prefix-alist))
1193
1194 ;; Prepare the typekey query prompt and help string.
1195 (setq qh-list
1196 (sort qh-list
1197 (lambda (x1 x2)
1198 (string< (downcase (car x1)) (downcase (car x2))))))
1199 (setq reftex-type-query-prompt
1200 (concat "Label type: ["
1201 (mapconcat (lambda(x) (format "%s" (car x)))
1202 qh-list "")
1203 "]"))
1204 ;; In the help string, we need to wrap lines...
1205 (setq reftex-type-query-help
1206 (concat
1207 "SELECT A LABEL TYPE:\n--------------------\n"
1208 (mapconcat
1209 (lambda(x)
1210 (setq sum 0)
1211 (format " [%s] %s"
1212 (car x)
1213 (mapconcat (lambda(env)
1214 (setq sum (+ sum (length env)))
1215 (if (< sum 60)
1216 env
1217 (setq sum 0)
1218 (concat "\n " env)))
1219 (cdr x) " ")))
1220 qh-list "\n")))
1221
1222 ;; Convert magic words to regular expressions. We make regular expressions
1223 ;; which allow for some chars from the ref format to be in the buffer.
1224 ;; These characters will be seen and removed.
1225 (setq reftex-words-to-typekey-alist
1226 (mapcar
1227 (lambda (x)
1228 (setq word (car x)
1229 typekey (cdr x)
1230 fmt (cdr (assoc typekey reftex-typekey-to-format-alist)))
1231 (setq word (concat "\\W\\(" word "[ \t\n\r]*\\)\\("))
1232 (setq i 0)
1233 (while (and (< i 10) ; maximum number of format chars allowed
1234 (< i (length fmt))
1235 (not (member (aref fmt i) '(?%))))
1236 (setq word (concat word "\\|" (regexp-quote
1237 (substring fmt 0 (1+ i)))))
1238 (incf i))
1239 (cons (concat word "\\)\\=") typekey))
1240 (nreverse reftex-words-to-typekey-alist)))
1241
1242 ;; Parse the index macros
1243 (setq reftex-index-macro-alist nil
1244 reftex-key-to-index-macro-alist nil
1245 reftex-macros-with-index nil)
1246 (while all-index
1247 (setq entry (car all-index)
1248 macro (car entry)
1249 tag (nth 1 entry)
1250 key (nth 2 entry)
1251 prefix (or (nth 3 entry) "")
1252 verify (nth 4 entry)
1253 ;; For repeat, we need to be compatible with older code
1254 ;; This information used to be given only for the default macro,
1255 ;; but later we required to have it for *every* index macro
1256 repeat (cond ((> (length entry) 5) (nth 5 entry))
1257 ((and (eq key (car reftex-index-default-macro))
1258 (> (length reftex-index-default-macro) 2))
1259 ;; User has old setting - respect it
1260 (nth 2 reftex-index-default-macro))
1261 (t t))
1262 all-index (cdr all-index))
1263 (let ((result (reftex-parse-args macro)))
1264 (setq macro (or (first result) macro)
1265 nargs (second result)
1266 nindex (third result)
1267 opt-args (fourth result))
1268 (unless (member macro reftex-macros-with-index)
1269 ;; 0 1 2 3 4 5 6 7
1270 (push (list macro tag prefix verify nargs nindex opt-args repeat)
1271 reftex-index-macro-alist)
1272 (or (assoc key reftex-key-to-index-macro-alist)
1273 (push (list key macro) reftex-key-to-index-macro-alist))
1274 (push macro reftex-macros-with-index))))
1275 ;; Make the prompt and help string for index macros query
1276 (setq reftex-key-to-index-macro-alist
1277 (sort reftex-key-to-index-macro-alist
1278 (lambda (a b) (< (downcase (car a)) (downcase (car b))))))
1279 (setq reftex-query-index-macro-prompt
1280 (concat "Index macro: ["
1281 (mapconcat (lambda (x) (char-to-string (car x)))
1282 reftex-key-to-index-macro-alist "")
1283 "]"))
1284 (setq i 0
1285 reftex-query-index-macro-help
1286 (concat
1287 "SELECT A MACRO:\n---------------\n"
1288 (mapconcat
1289 (lambda(x)
1290 (format "[%c] %-20.20s%s" (car x) (nth 1 x)
1291 (if (= 0 (mod (incf i) 3)) "\n" "")))
1292 reftex-key-to-index-macro-alist "")))
1293
1294 ;; Make the full list of section levels
1295 (setq reftex-section-levels-all
1296 (append toc-levels
1297 (get reftex-docstruct-symbol 'reftex-section-levels)
1298 reftex-section-levels))
1299
1300 ;; Calculate the regular expressions
1301 (let* (
1302 ; (wbol "\\(\\`\\|[\n\r]\\)[ \t]*")
1303 (wbol "\\(^\\)[ \t]*") ; Need to keep the empty group because
1304 ;;; because match number are hard coded
1305 (label-re "\\\\label{\\([^}]*\\)}")
1306 (include-re (concat wbol
1307 "\\\\\\("
1308 (mapconcat 'identity
1309 reftex-include-file-commands "\\|")
1310 "\\)[{ \t]+\\([^} \t\n\r]+\\)"))
1311 (section-re
1312 (concat wbol "\\\\\\("
1313 (mapconcat (lambda (x) (regexp-quote (car x)))
1314 reftex-section-levels-all "\\|")
1315 "\\)\\*?\\(\\[[^]]*\\]\\)?[[{ \t\r\n]"))
1316 (appendix-re (concat wbol "\\(\\\\appendix\\)"))
1317 (macro-re
1318 (if macros-with-labels
1319 (concat "\\("
1320 (mapconcat 'regexp-quote macros-with-labels "\\|")
1321 "\\)[[{]")
1322 ""))
1323 (index-re
1324 (concat "\\("
1325 (mapconcat 'regexp-quote reftex-macros-with-index "\\|")
1326 "\\)[[{]"))
1327 (find-index-re-format
1328 (concat "\\("
1329 (mapconcat 'regexp-quote reftex-macros-with-index "\\|")
1330 "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]"))
1331 (find-label-re-format
1332 (concat "\\("
1333 (mapconcat 'regexp-quote (append '("\\label")
1334 macros-with-labels) "\\|")
1335 "\\)\\([[{][^]}]*[]}]\\)*[[{]\\(%s\\)[]}]"))
1336 (index-level-re
1337 (regexp-quote (nth 0 reftex-index-special-chars)))
1338 (index-key-end-re ;; ^]- not allowed
1339 (concat "[^" (nth 3 reftex-index-special-chars) "]"
1340 "[" (nth 1 reftex-index-special-chars)
1341 (nth 2 reftex-index-special-chars) "]"))
1342 )
1343 (setq reftex-section-regexp section-re
1344 reftex-section-or-include-regexp
1345 (concat section-re "\\|" include-re)
1346 reftex-everything-regexp
1347 (concat label-re "\\|" section-re "\\|" include-re
1348 "\\|" appendix-re
1349 "\\|" index-re
1350 (if macros-with-labels "\\|" "") macro-re)
1351 reftex-everything-regexp-no-index
1352 (concat label-re "\\|" section-re "\\|" include-re
1353 "\\|" appendix-re
1354 "\\|" "\\(\\\\6\\\\3\\\\1\\)" ; This is unlikely to match
1355 (if macros-with-labels "\\|" "") macro-re)
1356 reftex-index-re index-re
1357 reftex-index-level-re index-level-re
1358 reftex-index-key-end-re index-key-end-re
1359 reftex-macros-with-labels macros-with-labels
1360 reftex-find-index-entry-regexp-format find-index-re-format
1361 reftex-find-label-regexp-format find-label-re-format
1362 reftex-find-label-regexp-format2
1363 "\\([]} \t\n\r]\\)\\([[{]\\)\\(%s\\)[]}]")
1364 (message "Compiling label environment definitions...done")))
1365 (put reftex-docstruct-symbol 'reftex-cache
1366 (mapcar 'symbol-value reftex-cache-variables)))
1367
1368 (defun reftex-parse-args (macro)
1369 ;; Return a list of macro name, nargs, arg-nr which is label and a list of
1370 ;; optional argument indices.
1371 (if (string-match "[[{]\\*?[]}]" macro)
1372 (progn
1373 (let ((must-match (substring macro 0 (match-beginning 0)))
1374 (args (substring macro (match-beginning 0)))
1375 opt-list nlabel (cnt 0))
1376 (while (string-match "\\`[[{]\\(\\*\\)?[]}]" args)
1377 (incf cnt)
1378 (when (eq ?\[ (string-to-char args))
1379 (push cnt opt-list))
1380 (when (and (match-end 1)
1381 (not nlabel))
1382 (setq nlabel cnt))
1383 (setq args (substring args (match-end 0))))
1384 (list must-match cnt nlabel opt-list)))
1385 nil))
1386
1387 ;;; =========================================================================
1388 ;;;
1389 ;;; Accessing the parse information
1390
1391 (defun reftex-access-scan-info (&optional rescan file)
1392 "Ensure access to the scanning info for the current file."
1393 ;; When the multifile symbols are not yet tied,
1394 ;; tie them. When they are empty or RESCAN is non-nil, scan the document.
1395 ;; But, when RESCAN is -1, don't rescan even if docstruct is empty.
1396 ;; When FILE is non-nil, parse only from that file.
1397
1398 ;; Error out in a buffer without a file.
1399 (if (and reftex-mode
1400 (not (buffer-file-name)))
1401 (error "RefTeX works only in buffers visiting a file"))
1402
1403 ;; Make sure we have the symbols tied
1404 (if (eq reftex-docstruct-symbol nil)
1405 ;; Symbols are not yet tied: Tie them.
1406 (reftex-tie-multifile-symbols))
1407
1408 (reftex-ensure-compiled-variables)
1409
1410 (when (or (null (symbol-value reftex-docstruct-symbol))
1411 (member rescan '(t 1 (4) (16))))
1412 ;; The docstruct will change: Remove selection buffers.
1413 (save-excursion
1414 (reftex-erase-buffer "*toc*")
1415 (reftex-erase-all-selection-and-index-buffers)))
1416
1417 (if (and (null (symbol-value reftex-docstruct-symbol))
1418 (not (member rescan '(t 1 (4) (16))))
1419 reftex-save-parse-info)
1420 ;; Try to read the stuff from a file
1421 (reftex-access-parse-file 'read))
1422
1423 (cond
1424 ((equal rescan -1)) ;; We are not allowed to scan.
1425 ((not (symbol-value reftex-docstruct-symbol))
1426 ;; Scan the whole document
1427 (reftex-do-parse 1 file))
1428 ((member rescan '(t 1 (4) (16)))
1429 ;; Scan whatever was required by the caller.
1430 (reftex-do-parse rescan file))))
1431
1432 (defun reftex-scanning-info-available-p ()
1433 "Is the scanning info about the current document available?"
1434 (unless reftex-docstruct-symbol
1435 (reftex-tie-multifile-symbols))
1436 (and (symbolp reftex-docstruct-symbol)
1437 (symbol-value reftex-docstruct-symbol)
1438 t))
1439
1440 (defun reftex-silence-toc-markers (list n)
1441 ;; Set all toc markers in the first N entries in list to nil
1442 (while (and list (> (decf n) -1))
1443 (and (eq (car (car list)) 'toc)
1444 (markerp (nth 4 (car list)))
1445 (set-marker (nth 4 (car list)) nil))
1446 (pop list)))
1447
1448 (defun reftex-access-parse-file (action)
1449 "Perform ACTION on the parse file (the .rel file).
1450 Valid actions are: readable, restore, read, kill, write."
1451 (let* ((list (symbol-value reftex-docstruct-symbol))
1452 (docstruct-symbol reftex-docstruct-symbol)
1453 (master (reftex-TeX-master-file))
1454 (enable-local-variables nil)
1455 (file (if (string-match "\\.[a-zA-Z]+\\'" master)
1456 (concat (substring master 0 (match-beginning 0))
1457 reftex-parse-file-extension)
1458 (concat master reftex-parse-file-extension))))
1459 (cond
1460 ((eq action 'readable)
1461 (file-readable-p file))
1462 ((eq action 'restore)
1463 (put reftex-docstruct-symbol 'modified nil)
1464 (if (eq reftex-docstruct-symbol nil)
1465 ;; Symbols are not yet tied: Tie them.
1466 (reftex-tie-multifile-symbols))
1467 (if (file-exists-p file)
1468 ;; load the file and return t for success
1469 (condition-case nil
1470 (progn (load-file file) t)
1471 (error (set reftex-docstruct-symbol nil)
1472 (error "Error while loading file %s" file)))
1473 ;; Throw an exception if the file does not exist
1474 (error "No restore file %s" file)))
1475 ((eq action 'read)
1476 (put reftex-docstruct-symbol 'modified nil)
1477 (if (file-exists-p file)
1478 ;; load the file and return t for success
1479 (condition-case nil
1480 (progn
1481 (load-file file)
1482 (reftex-check-parse-consistency)
1483 t)
1484 (error (message "Error while restoring file %s" file)
1485 (set reftex-docstruct-symbol nil)
1486 nil))
1487 ;; return nil for failure, but no exception
1488 nil))
1489 ((eq action 'kill)
1490 ;; Remove the file
1491 (when (and (file-exists-p file) (file-writable-p file))
1492 (message "Unlinking file %s" file)
1493 (delete-file file)))
1494 (t
1495 (put docstruct-symbol 'modified nil)
1496 (save-excursion
1497 (if (file-writable-p file)
1498 (with-temp-file file
1499 (message "Writing parse file %s" (abbreviate-file-name file))
1500 (insert (format ";; RefTeX parse info file\n"))
1501 (insert (format ";; File: %s\n" master))
1502 (insert (format ";; User: %s (%s)\n\n"
1503 (user-login-name) (user-full-name)))
1504 (insert "(set reftex-docstruct-symbol '(\n\n")
1505 (let ((standard-output (current-buffer)))
1506 (mapc
1507 (lambda (x)
1508 (cond ((eq (car x) 'toc)
1509 ;; A toc entry. Do not save the marker.
1510 ;; Save the markers position at position 8
1511 (print (list 'toc "toc" (nth 2 x) (nth 3 x)
1512 nil (nth 5 x) (nth 6 x) (nth 7 x)
1513 (or (and (markerp (nth 4 x))
1514 (marker-position (nth 4 x)))
1515 (nth 8 x)))))
1516 ((and (not (eq t reftex-support-index))
1517 (eq (car x) 'index))
1518 ;; Don't save index entries
1519 )
1520 (t (print x))))
1521 list))
1522 (insert "))\n\n"))
1523 (error "Cannot write to file %s" file)))
1524 t))))
1525
1526 (defun reftex-check-parse-consistency ()
1527 ;; Check if parse file is consistent, throw an error if not.
1528
1529 ;; Check if the master is the same: when moving a document, this will see it.
1530 (let* ((real-master (reftex-TeX-master-file))
1531 (parsed-master
1532 (nth 1 (assq 'bof (symbol-value reftex-docstruct-symbol)))))
1533 (unless (string= (file-truename real-master) (file-truename parsed-master))
1534 (message "Master file name in load file is different: %s versus %s"
1535 parsed-master real-master)
1536 (error "Master file name error")))
1537
1538 ;; Check for the existence of all document files
1539 ;;; (let* ((all (symbol-value reftex-docstruct-symbol)))
1540 ;;; (while all
1541 ;;; (when (and (eq (car (car all)) 'bof)
1542 ;;; (not (file-regular-p (nth 1 (car all)))))
1543 ;;; (message "File %s in saved parse info not avalable" (cdr (car all)))
1544 ;;; (error "File not found"))
1545 ;;; (setq all (cdr all))))
1546 )
1547
1548 (defun reftex-select-external-document (xr-alist xr-index)
1549 ;; Return index of an external document.
1550 (let* ((len (length xr-alist)) (highest (1- (+ ?0 len)))
1551 (prompt (format "[%c-%c] Select TAB: Read prefix with completion"
1552 ?0 highest))
1553 key prefix)
1554 (cond
1555 ((= len 1)
1556 (message "No external documents available")
1557 (ding) (sit-for 1) 0)
1558 ((= len 2)
1559 (- 1 xr-index))
1560 (t
1561 (save-excursion
1562 (let* ((length (apply 'max (mapcar
1563 (lambda(x) (length (car x))) xr-alist)))
1564 (fmt (format " [%%c] %%-%ds %%s\n" length))
1565 (n (1- ?0)))
1566 (setq key
1567 (reftex-select-with-char
1568 prompt
1569 (concat
1570 "SELECT EXTERNAL DOCUMENT\n------------------------\n"
1571 (mapconcat
1572 (lambda (x)
1573 (format fmt (incf n) (or (car x) "")
1574 (abbreviate-file-name (cdr x))))
1575 xr-alist ""))
1576 nil t))
1577 (cond
1578 ((and (>= key ?0) (<= key highest)) (- key ?0))
1579 ((= key ?\C-i)
1580 (setq prefix (completing-read "Prefix: " xr-alist nil t))
1581 (- len (length (memq (assoc prefix xr-alist) xr-alist))))
1582 (t (error "Invalid document selection [%c]" key)))))))))
1583
1584 ;;; =========================================================================
1585 ;;;
1586 ;;; Finding files
1587
1588 (defun reftex-locate-file (file type master-dir &optional die)
1589 "Find FILE of type TYPE in MASTER-DIR or on the path associcted with TYPE.
1590 If the file does not have any of the valid extensions for TYPE,
1591 try first the default extension and only then the naked file name.
1592 When DIE is non-nil, throw an error if file not found."
1593 (let* ((rec-values (if reftex-search-unrecursed-path-first '(nil t) '(t)))
1594 (extensions (cdr (assoc type reftex-file-extensions)))
1595 (def-ext (car extensions))
1596 (ext-re (concat "\\("
1597 (mapconcat 'regexp-quote extensions "\\|")
1598 "\\)\\'"))
1599 (files (if (string-match ext-re file)
1600 (cons file nil)
1601 (if reftex-try-all-extensions
1602 (append (mapcar (lambda (x) (concat file x))
1603 extensions)
1604 (list file))
1605 (list (concat file def-ext) file))))
1606 path old-path file1 f fs)
1607 (cond
1608 ((file-name-absolute-p file)
1609 (while (setq f (pop files))
1610 (if (file-regular-p f)
1611 (setq file1 f files nil))))
1612 ((and reftex-use-external-file-finders
1613 (assoc type reftex-external-file-finders))
1614 (setq file1 (reftex-find-file-externally file type master-dir)))
1615 (t
1616 (while (and (null file1) rec-values)
1617 (setq path (reftex-access-search-path
1618 type (pop rec-values) master-dir file))
1619 (setq fs files)
1620 (while (and (null file1) (setq f (pop fs)))
1621 (when (or (null old-path)
1622 (not (eq old-path path)))
1623 (setq old-path path
1624 path (cons master-dir path))
1625 (setq file1 (reftex-find-file-on-path f path master-dir)))))))
1626 (cond (file1 file1)
1627 (die (error "No such file: %s" file) nil)
1628 (t (message "No such file: %s (ignored)" file) nil))))
1629
1630 (defun reftex-find-file-externally (file type &optional master-dir)
1631 ;; Use external program to find FILE.
1632 ;; The program is taken from `reftex-external-file-finders'.
1633 ;; Interprete relative path definitions starting from MASTER-DIR.
1634 (let ((default-directory (or master-dir default-directory))
1635 (prg (cdr (assoc type reftex-external-file-finders)))
1636 out)
1637 (if (string-match "%f" prg)
1638 (setq prg (replace-match file t t prg)))
1639 (setq out (apply 'reftex-process-string (split-string prg)))
1640 (if (string-match "[ \t\n]+\\'" out) ; chomp
1641 (setq out (replace-match "" nil nil out)))
1642 (cond ((equal out "") nil)
1643 ((file-regular-p out) (expand-file-name out master-dir))
1644 (t nil))))
1645
1646 (defun reftex-process-string (program &rest args)
1647 "Execute PROGRAM with arguments ARGS and return its STDOUT as a string."
1648 (let ((calling-dir default-directory)) ; remember default directory
1649 (with-output-to-string
1650 (with-current-buffer standard-output
1651 (let ((default-directory calling-dir)) ; set default directory
1652 (apply 'call-process program nil '(t nil) nil args))))))
1653
1654 (defun reftex-access-search-path (type &optional recurse master-dir file)
1655 ;; Access path from environment variables. TYPE is either "tex" or "bib".
1656 ;; When RECURSE is t, expand path elements ending in `//' recursively.
1657 ;; Relative path elements are left as they are. However, relative recursive
1658 ;; elements are expanded with MASTER-DIR as default directory.
1659 ;; The expanded path is cached for the next search.
1660 ;; FILE is just for the progress message.
1661 ;; Returns the derived path.
1662 (let* ((pathvar (intern (concat "reftex-" type "-path"))))
1663 (when (null (get pathvar 'status))
1664 ;; Get basic path
1665 (set pathvar
1666 (reftex-uniquify
1667 (reftex-parse-colon-path
1668 (mapconcat
1669 (lambda(x)
1670 (if (string-match "^!" x)
1671 (apply 'reftex-process-string
1672 (split-string (substring x 1)))
1673 (or (getenv x) x)))
1674 ;; For consistency, the next line should look like this:
1675 ;; (cdr (assoc type reftex-path-environment))
1676 ;; However, historically we have separate options for the
1677 ;; environment variables, so we have to do this:
1678 (symbol-value (intern (concat "reftex-" type
1679 "path-environment-variables")))
1680 path-separator))))
1681 (put pathvar 'status 'split)
1682 ;; Check if we have recursive elements
1683 (let ((path (symbol-value pathvar)) dir rec)
1684 (while (setq dir (pop path))
1685 (when (string= (substring dir -2) "//")
1686 (if (file-name-absolute-p dir)
1687 (setq rec (or rec 'absolute))
1688 (setq rec 'relative))))
1689 (put pathvar 'rec-type rec)))
1690
1691 (if recurse
1692 ;; Return the recursive expansion of the path
1693 (cond
1694 ((not (get pathvar 'rec-type))
1695 ;; Path does not contain recursive elements - use simple path
1696 (symbol-value pathvar))
1697 ((or (not (get pathvar 'recursive-path))
1698 (and (eq (get pathvar 'rec-type) 'relative)
1699 (not (equal master-dir (get pathvar 'master-dir)))))
1700 ;; Either: We don't have a recursive expansion yet.
1701 ;; or: Relative recursive path elements need to be expanded
1702 ;; relative to new default directory
1703 (message "Expanding search path to find %s file: %s ..." type file)
1704 (put pathvar 'recursive-path
1705 (reftex-expand-path (symbol-value pathvar) master-dir))
1706 (put pathvar 'master-dir master-dir)
1707 (get pathvar 'recursive-path))
1708 (t
1709 ;; Recursive path computed earlier is still OK.
1710 (get pathvar 'recursive-path)))
1711 ;; The simple path was requested
1712 (symbol-value pathvar))))
1713
1714 (defun reftex-find-file-on-path (file path &optional def-dir)
1715 ;; Find FILE along the directory list PATH.
1716 ;; DEF-DIR is the default directory for expanding relative path elements.
1717 (catch 'exit
1718 (when (file-name-absolute-p file)
1719 (if (file-regular-p file)
1720 (throw 'exit file)
1721 (throw 'exit nil)))
1722 (let* ((thepath path) file1 dir)
1723 (while (setq dir (pop thepath))
1724 (when (string= (substring dir -2) "//")
1725 (setq dir (substring dir 0 -1)))
1726 (setq file1 (expand-file-name file (expand-file-name dir def-dir)))
1727 (if (file-regular-p file1)
1728 (throw 'exit file1)))
1729 ;; No such file
1730 nil)))
1731
1732 (defun reftex-parse-colon-path (path)
1733 ;; Like parse-colon-parse, but // or /~ are left alone.
1734 ;; Trailing ! or !! will be converted into `//' (emTeX convention)
1735 (mapcar
1736 (lambda (dir)
1737 (if (string-match "\\(//+\\|/*!+\\)\\'" dir)
1738 (setq dir (replace-match "//" t t dir)))
1739 (file-name-as-directory dir))
1740 (delete "" (split-string path (concat path-separator "+")))))
1741
1742 (defun reftex-expand-path (path &optional default-dir)
1743 ;; Expand parts of path ending in `//' recursively into directory list.
1744 ;; Relative recursive path elements are expanded relative to DEFAULT-DIR.
1745 (let (path1 dir recursive)
1746 (while (setq dir (pop path))
1747 (if (setq recursive (string= (substring dir -2) "//"))
1748 (setq dir (substring dir 0 -1)))
1749 (if (and recursive
1750 (not (file-name-absolute-p dir)))
1751 (setq dir (expand-file-name dir default-dir)))
1752 (if recursive
1753 ;; Expand recursively
1754 (setq path1 (append (reftex-recursive-directory-list dir) path1))
1755 ;; Keep unchanged
1756 (push dir path1)))
1757 (nreverse path1)))
1758
1759 (defun reftex-recursive-directory-list (dir)
1760 ;; Return a list of all directories below DIR, including DIR itself
1761 (let ((path (list dir)) path1 file files)
1762 (while (setq dir (pop path))
1763 (when (file-directory-p dir)
1764 (setq files (nreverse (directory-files dir t "[^.]")))
1765 (while (setq file (pop files))
1766 (if (file-directory-p file)
1767 (push (file-name-as-directory file) path)))
1768 (push dir path1)))
1769 path1))
1770
1771 ;;; =========================================================================
1772 ;;;
1773 ;;; Some generally useful functions
1774
1775 (defun reftex-typekey-check (typekey conf-variable &optional n)
1776 ;; Check if CONF-VARIABLE is true or contains TYPEKEY
1777 (and n (setq conf-variable (nth n conf-variable)))
1778 (or (eq conf-variable t)
1779 (and (stringp conf-variable)
1780 (string-match (concat "[" conf-variable "]") typekey))))
1781
1782 (defun reftex-check-recursive-edit ()
1783 ;; Check if we are already in a recursive edit. Abort with helpful
1784 ;; message if so.
1785 (if (marker-position reftex-recursive-edit-marker)
1786 (error
1787 (substitute-command-keys
1788 "In unfinished selection process. Finish, or abort with \\[abort-recursive-edit]"))))
1789
1790 (defun reftex-in-comment ()
1791 (save-excursion
1792 (skip-chars-backward "^%\n\r")
1793 (eq (preceding-char) ?%)))
1794
1795 (defun reftex-no-props (string)
1796 ;; Return STRING with all text properties removed
1797 (and (stringp string)
1798 (set-text-properties 0 (length string) nil string))
1799 string)
1800
1801 (defun reftex-match-string (n)
1802 ;; Match string without properties
1803 (when (match-beginning n)
1804 (buffer-substring-no-properties (match-beginning n) (match-end n))))
1805
1806 (defun reftex-region-active-p ()
1807 "Should we operate on an active region?"
1808 (if (fboundp 'use-region-p)
1809 (use-region-p)
1810 ;; For XEmacs.
1811 (region-active-p)))
1812
1813 (defun reftex-kill-buffer (buffer)
1814 ;; Kill buffer if it exists.
1815 (and (setq buffer (get-buffer buffer))
1816 (kill-buffer buffer)))
1817
1818 (defun reftex-erase-buffer (&optional buffer)
1819 ;; Erase BUFFER if it exists. BUFFER defaults to current buffer.
1820 ;; This even erases read-only buffers.
1821 (cond
1822 ((null buffer)
1823 ;; erase current buffer
1824 (let ((buffer-read-only nil)) (erase-buffer)))
1825 ((setq buffer (get-buffer buffer))
1826 ;; buffer exists
1827 (save-excursion
1828 (set-buffer buffer)
1829 (let ((buffer-read-only nil)) (erase-buffer))))))
1830
1831 (defun reftex-this-word (&optional class)
1832 ;; Grab the word around point.
1833 (setq class (or class "-a-zA-Z0-9:_/.*;|"))
1834 (save-excursion
1835 (buffer-substring-no-properties
1836 (progn (skip-chars-backward class) (point))
1837 (progn (skip-chars-forward class) (point)))))
1838
1839 (defun reftex-number (n unit &optional ending)
1840 (if (and (integerp n) (stringp unit))
1841 (format "%d %s%s" n unit (if (= n 1) "" (or ending "s")))
1842 ""))
1843
1844 (defun reftex-all-assq (key list)
1845 ;; Return a list of all associations of KEY in LIST. Comparison with eq.
1846 (let (rtn)
1847 (while (setq list (memq (assq key list) list))
1848 (push (car list) rtn)
1849 (pop list))
1850 (nreverse rtn)))
1851
1852 (defun reftex-all-assoc-string (key list)
1853 ;; Return a list of all associations of KEY in LIST. Comparison with string=.
1854 (let (rtn)
1855 (while list
1856 (if (string= (car (car list)) key)
1857 (push (car list) rtn))
1858 (pop list))
1859 (nreverse rtn)))
1860
1861 (defun reftex-last-assoc-before-elt (key elt list &optional exclusive)
1862 ;; Find the last association of KEY in LIST before or at ELT
1863 ;; ELT is found in LIST with equal, not eq.
1864 ;; Returns nil when either KEY or elt are not found in LIST.
1865 ;; When EXCLUSIVE is non-nil, ELT cannot be the return value.
1866 ;; On success, returns the association.
1867 (let* ((elt (car (member elt list))) (ex (not exclusive)) ass last-ass)
1868 (while (and (setq ass (assoc key list))
1869 (setq list (memq ass list))
1870 (or ex (not (eq elt (car list))))
1871 (memq elt list))
1872 (setq last-ass ass
1873 list (cdr list)))
1874 last-ass))
1875
1876 (defun reftex-sublist-nth (list nth predicate &optional completion)
1877 ;; Make a list of the NTH elements of all members of LIST which
1878 ;; fulfill PREDICATE.
1879 ;; When COMPLETION is non-nil, make all elements of the resulting
1880 ;; list also a list, so that the result can be used for completion.
1881 (let (rtn)
1882 (while list
1883 (if (funcall predicate (car list))
1884 (push (if completion
1885 (list (nth nth (car list)))
1886 (nth nth (car list)))
1887 rtn))
1888 (setq list (cdr list)))
1889 (nreverse rtn)))
1890
1891 (defun reftex-make-selection-buffer-name (type &optional index)
1892 ;; Make unique name for a selection buffer.
1893 (format " *RefTeX[%s][%d]*"
1894 type (or index (get reftex-docstruct-symbol :master-index) 0)))
1895
1896 (defun reftex-make-index-buffer-name (tag &optional cnt)
1897 ;; Make unique name for an index buffer.
1898 (format "*Index[%s][%d]*"
1899 tag (or cnt (get reftex-docstruct-symbol :master-index) 0)))
1900
1901 (defun reftex-truncate (string ncols &optional ellipses padding)
1902 ;; Truncate STRING to NCOLS characters.
1903 ;; When PADDING is non-nil, and string is shorter than NCOLS, fill with
1904 ;; white space to NCOLS characters. When ELLIPSES is non-nil and the
1905 ;; string needs to be truncated, replace last 3 characters by dots.
1906 (setq string
1907 (if (<= (length string) ncols)
1908 string
1909 (if ellipses
1910 (concat (substring string 0 (- ncols 3)) "...")
1911 (substring string 0 ncols))))
1912 (if padding
1913 (format (format "%%-%ds" ncols) string)
1914 string))
1915
1916 (defun reftex-nearest-match (regexp &optional max-length)
1917 ;; Find the nearest match of REGEXP. Set the match data.
1918 ;; If POS is given, calculate distances relative to it.
1919 ;; Return nil if there is no match.
1920 (let ((pos (point))
1921 (dist (or max-length (length regexp)))
1922 match1 match2 match)
1923 (goto-char (min (+ pos dist) (point-max)))
1924 (when (re-search-backward regexp nil t)
1925 (setq match1 (match-data)))
1926 (goto-char (max (- pos dist) (point-min)))
1927 (when (re-search-forward regexp nil t)
1928 (setq match2 (match-data)))
1929 (goto-char pos)
1930 (setq match
1931 (cond
1932 ((not match1) match2)
1933 ((not match2) match1)
1934 ((< (abs (- pos (car match1))) (abs (- pos (car match2)))) match1)
1935 (t match2)))
1936 (if match (progn (set-match-data match) t) nil)))
1937
1938 (defun reftex-auto-mode-alist ()
1939 ;; Return an `auto-mode-alist' with only the .gz (etc) thingies.
1940 ;; Stolen from gnus nnheader.
1941 (let ((alist auto-mode-alist)
1942 out)
1943 (while alist
1944 (when (listp (cdr (car alist)))
1945 (push (car alist) out))
1946 (pop alist))
1947 (nreverse out)))
1948
1949 (defun reftex-window-height ()
1950 (if (fboundp 'window-displayed-height)
1951 (window-displayed-height)
1952 (window-height)))
1953
1954 (defun reftex-enlarge-to-fit (buf2 &optional keep-current)
1955 ;; Enlarge other window displaying buffer to show whole buffer if possible.
1956 ;; If KEEP-CURRENT in non-nil, current buffer must remain visible.
1957 (let* ((win1 (selected-window))
1958 (buf1 (current-buffer))
1959 (win2 (get-buffer-window buf2))) ;; Only on current frame.
1960 (when win2
1961 (select-window win2)
1962 (unless (and (pos-visible-in-window-p (point-min))
1963 (pos-visible-in-window-p (point-max)))
1964 (enlarge-window (1+ (- (count-lines (point-min) (point-max))
1965 (reftex-window-height))))))
1966 (cond
1967 ((window-live-p win1) (select-window win1))
1968 (keep-current
1969 ;; we must have the old buffer!
1970 (switch-to-buffer-other-window buf1)
1971 (shrink-window (- (window-height) window-min-height))))))
1972
1973 (defun reftex-select-with-char (prompt help-string &optional delay-time scroll)
1974 ;; Offer to select something with PROMPT and, after DELAY-TIME seconds,
1975 ;; also with HELP-STRING.
1976 ;; When SCROLL is non-nil, use SPC and DEL to scroll help window.
1977 (let ((char ?\?))
1978 (save-window-excursion
1979 (catch 'exit
1980 (message "%s (?=Help)" prompt)
1981 (when (or (sit-for (or delay-time 0))
1982 (= ?\? (setq char (read-char-exclusive))))
1983 (reftex-kill-buffer "*RefTeX Select*")
1984 (switch-to-buffer-other-window "*RefTeX Select*")
1985 (insert help-string)
1986 (goto-char 1)
1987 (unless (and (pos-visible-in-window-p (point-min))
1988 (pos-visible-in-window-p (point-max)))
1989 (enlarge-window (1+ (- (count-lines (point-min) (point-max))
1990 (reftex-window-height)))))
1991 (setq truncate-lines t))
1992 (if (and (pos-visible-in-window-p (point-min))
1993 (pos-visible-in-window-p (point-max)))
1994 nil
1995 (setq prompt (concat prompt (if scroll " (SPC/DEL=Scroll)" ""))))
1996 (message "%s" prompt)
1997 (and (equal char ?\?) (setq char (read-char-exclusive)))
1998 (while t
1999 (cond ((equal char ?\C-g) (keyboard-quit))
2000 ((equal char ?\?))
2001 ((and scroll (equal char ?\ ))
2002 (condition-case nil (scroll-up) (error nil))
2003 (message "%s" prompt))
2004 ((and scroll (equal char ?\C-? ))
2005 (condition-case nil (scroll-down) (error nil))
2006 (message "%s" prompt))
2007 (t (message "")
2008 (throw 'exit char)))
2009 (setq char (read-char-exclusive)))))))
2010
2011
2012 (defun reftex-make-regexp-allow-for-ctrl-m (string)
2013 ;; convert STRING into a regexp, allowing ^M for \n and vice versa
2014 (let ((start -2))
2015 (setq string (regexp-quote string))
2016 (while (setq start (string-match "[\n\r]" string (+ 3 start)))
2017 (setq string (replace-match "[\n\r]" nil t string)))
2018 string))
2019
2020 (defun reftex-get-buffer-visiting (file)
2021 ;; return a buffer visiting FILE
2022 (cond
2023 ((boundp 'find-file-compare-truenames) ; XEmacs
2024 (let ((find-file-compare-truenames t))
2025 (get-file-buffer file)))
2026 ((fboundp 'find-buffer-visiting) ; Emacs
2027 (find-buffer-visiting file))
2028 (t (error "This should not happen (reftex-get-buffer-visiting)"))))
2029
2030 ;; Define `current-message' for compatibility with XEmacs prior to 20.4
2031 (defvar message-stack)
2032 (if (and (featurep 'xemacs)
2033 (not (fboundp 'current-message)))
2034 (defun current-message (&optional frame)
2035 (cdr (car message-stack))))
2036
2037 (defun reftex-visited-files (list)
2038 ;; Takes a list of filenames and returns the buffers of those already visited
2039 (delq nil (mapcar (lambda (x) (if (reftex-get-buffer-visiting x) x nil))
2040 list)))
2041
2042 (defun reftex-get-file-buffer-force (file &optional mark-to-kill)
2043 ;; Return a buffer visiting file. Make one, if necessary.
2044 ;; If neither such a buffer nor the file exist, return nil.
2045 ;; If MARK-TO-KILL is t and there is no live buffer, visit the file with
2046 ;; initializations according to `reftex-initialize-temporary-buffers',
2047 ;; and mark the buffer to be killed after use.
2048
2049 (let ((buf (reftex-get-buffer-visiting file)))
2050
2051 (cond (buf
2052 ;; We have it already as a buffer - just return it
2053 buf)
2054
2055 ((file-readable-p file)
2056 ;; At least there is such a file and we can read it.
2057
2058 (if (or (not mark-to-kill)
2059 (eq t reftex-initialize-temporary-buffers))
2060
2061 ;; Visit the file with full magic
2062 (setq buf (find-file-noselect file))
2063
2064 ;; Else: Visit the file just briefly, without or
2065 ;; with limited Magic
2066
2067 ;; The magic goes away
2068 (let ((format-alist nil)
2069 (auto-mode-alist (reftex-auto-mode-alist))
2070 (default-major-mode 'fundamental-mode)
2071 (enable-local-variables nil)
2072 (after-insert-file-functions nil))
2073 (setq buf (find-file-noselect file)))
2074
2075 ;; Is there a hook to run?
2076 (when (listp reftex-initialize-temporary-buffers)
2077 (save-excursion
2078 (set-buffer buf)
2079 (run-hooks 'reftex-initialize-temporary-buffers))))
2080
2081 ;; Lets see if we got a license to kill :-|
2082 (and mark-to-kill
2083 (add-to-list 'reftex-buffers-to-kill buf))
2084
2085 ;; Return the new buffer
2086 buf)
2087
2088 ;; If no such file exists, return nil
2089 (t nil))))
2090
2091 (defun reftex-kill-temporary-buffers (&optional buffer)
2092 ;; Kill all buffers in the list reftex-kill-temporary-buffers.
2093 (cond
2094 (buffer
2095 (when (member buffer reftex-buffers-to-kill)
2096 (kill-buffer buffer)
2097 (setq reftex-buffers-to-kill
2098 (delete buffer reftex-buffers-to-kill))))
2099 (t
2100 (while (setq buffer (pop reftex-buffers-to-kill))
2101 (when (bufferp buffer)
2102 (and (buffer-modified-p buffer)
2103 (y-or-n-p (format "Save file %s? "
2104 (buffer-file-name buffer)))
2105 (save-excursion
2106 (set-buffer buffer)
2107 (save-buffer)))
2108 (kill-buffer buffer))
2109 (pop reftex-buffers-to-kill)))))
2110
2111 (defun reftex-splice-symbols-into-list (list alist)
2112 ;; Splice the association in ALIST of any symbols in LIST into the list.
2113 ;; Return new list.
2114 (let (rtn tmp)
2115 (while list
2116 (while (and (not (null (car list))) ;; keep list elements nil
2117 (symbolp (car list)))
2118 (setq tmp (car list))
2119 (cond
2120 ((assoc tmp alist)
2121 (setq list (append (nth 2 (assoc tmp alist)) (cdr list))))
2122 (t
2123 (error "Cannot treat symbol %s in reftex-label-alist"
2124 (symbol-name tmp)))))
2125 (push (pop list) rtn))
2126 (nreverse rtn)))
2127
2128 (defun reftex-remove-symbols-from-list (list)
2129 ;; Remove all symbols from list
2130 (let (rtn)
2131 (while list
2132 (unless (symbolp (car list))
2133 (push (car list) rtn))
2134 (setq list (cdr list)))
2135 (nreverse rtn)))
2136
2137 (defun reftex-uniquify (list)
2138 ;; Return a list of all elements in LIST, but each only once, keeping order
2139 (let (new elm)
2140 (while list
2141 (setq elm (pop list))
2142 (unless (member elm new)
2143 (push elm new)))
2144 (nreverse new)))
2145
2146 (defun reftex-uniquify-by-car (alist &optional keep-list)
2147 ;; Return a list of all elements in ALIST, but each car only once.
2148 ;; Elements of KEEP-LIST are not removed even if duplicate.
2149 (let (new elm)
2150 (while alist
2151 (setq elm (pop alist))
2152 (if (or (member (car elm) keep-list)
2153 (not (assoc (car elm) new)))
2154 (push elm new)))
2155 (nreverse new)))
2156
2157 (defun reftex-abbreviate-title (string)
2158 (reftex-convert-string string "[-~ \t\n\r,;]" nil t t
2159 5 40 nil 1 " " (nth 5 reftex-derive-label-parameters)))
2160
2161 (defun reftex-convert-string (string split-re invalid-re dot keep-fp
2162 nwords maxchar invalid abbrev sep
2163 ignore-words &optional downcase)
2164 "Convert a string (a sentence) to something shorter.
2165 SPLIT-RE is the regular expression used to split the string into words.
2166 INVALID-RE matches characters which are invalid in the final string.
2167 DOT t means add dots to abbreviated words.
2168 KEEP-FP t means to keep a final punctuation when applicable.
2169 NWORDS Number of words to use.
2170 MAXCHAR Maximum number of characters in the final string.
2171 INVALID nil: Throw away any words containing stuff matched with INVALID-RE.
2172 t: Throw away only the matched part, not the whole word.
2173 ABBREV nil: Never abbreviate words.
2174 t: Always abbreviate words (see `reftex-abbrev-parameters').
2175 not t and not nil: Abbreviate words if necessary to shorten
2176 string below MAXCHAR.
2177 SEP String separating different words in the output string.
2178 IGNORE-WORDS List of words which should be removed from the string."
2179
2180 (let* ((words0 (split-string string (or split-re "[ \t\n\r]")))
2181 (reftex-label-illegal-re (or invalid-re "\000"))
2182 (abbrev-re (concat
2183 "\\`\\("
2184 (make-string (nth 0 reftex-abbrev-parameters) ?.)
2185 "[" (nth 2 reftex-abbrev-parameters) "]*"
2186 "\\)"
2187 "[" (nth 3 reftex-abbrev-parameters) "]"
2188 (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
2189 words word)
2190
2191 ;; Remove words from the ignore list or with funny characters
2192 (while (setq word (pop words0))
2193 (if downcase (setq word (downcase word)))
2194 (cond
2195 ((member (downcase word) ignore-words))
2196 ((string-match reftex-label-illegal-re word)
2197 (when invalid
2198 (while (string-match reftex-label-illegal-re word)
2199 (setq word (replace-match "" nil nil word)))
2200 (push word words)))
2201 (t
2202 (push word words))))
2203 (setq words (nreverse words))
2204
2205 ;; Restrict number of words
2206 (if (> (length words) nwords)
2207 (setcdr (nthcdr (1- nwords) words) nil))
2208
2209 ;; First, try to use all words
2210 (setq string (mapconcat 'identity words sep))
2211
2212 ;; Abbreviate words if enforced by user settings or string length
2213 (if (or (eq t abbrev)
2214 (and abbrev
2215 (> (length string) maxchar)))
2216 (setq words
2217 (mapcar
2218 (lambda (w) (if (string-match abbrev-re w)
2219 (if dot
2220 (concat (match-string 1 w) ".")
2221 (match-string 1 w))
2222 w))
2223 words)
2224 string (mapconcat 'identity words sep)))
2225
2226 ;; Shorten if still to long
2227 (setq string
2228 (if (> (length string) maxchar)
2229 (substring string 0 maxchar)
2230 string))
2231
2232 ;; Delete the final punctuation, if any
2233 (if (and (not keep-fp) (string-match "\\s.+\\'" string))
2234 (setq string (replace-match "" nil nil string)))
2235 string))
2236
2237 (defun reftex-nicify-text (text)
2238 ;; Make TEXT nice for inclusion as context into label menu.
2239 ;; 1. remove line breaks and extra white space
2240 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
2241 (setq text (replace-match " " nil t text)))
2242 ;; 2. cut before the next `\end{' or `\item' or `\\'
2243 (if (string-match "\\(\\\\end{\\|\\\\item\\|\\\\\\\\\\).*" text)
2244 (setq text (replace-match "" nil t text)))
2245 ;; 3. kill the embedded label
2246 (if (string-match "\\\\label{[^}]*}" text)
2247 (setq text (replace-match "" nil t text)))
2248 ;; 4. remove leading garbage
2249 (if (string-match "\\`[ }]+" text)
2250 (setq text (replace-match "" nil t text)))
2251 ;; 5. limit length
2252 (cond
2253 ((> (length text) 100) (substring text 0 100))
2254 ((= (length text) 0) (make-string 1 ?\ ))
2255 (t text)))
2256
2257 ;;; =========================================================================
2258 ;;;
2259 ;;; Fontification and Highlighting
2260
2261 (defun reftex-use-fonts ()
2262 ;; Return t if we can and want to use fonts.
2263 (and ; window-system
2264 reftex-use-fonts
2265 (featurep 'font-lock)))
2266
2267 (defun reftex-refontify ()
2268 ;; Return t if we need to refontify context
2269 (and (reftex-use-fonts)
2270 (or (eq t reftex-refontify-context)
2271 (and (eq 1 reftex-refontify-context)
2272 ;; Test of we use the font-lock version of x-symbol
2273 (and (featurep 'x-symbol-tex) (not (boundp 'x-symbol-mode)))))))
2274
2275 (defvar font-lock-defaults-computed)
2276 (defun reftex-fontify-select-label-buffer (parent-buffer)
2277 ;; Fontify the `*RefTeX Select*' buffer. Buffer is temporarily renamed to
2278 ;; start with none-SPC char, beacuse Font-Lock otherwise refuses operation.
2279 (run-hook-with-args 'reftex-pre-refontification-functions
2280 parent-buffer 'reftex-ref)
2281 (let* ((oldname (buffer-name))
2282 (newname (concat "Fontify-me-" oldname)))
2283 (unwind-protect
2284 (progn
2285 ;; Rename buffer temporarily to start w/o space (because of font-lock)
2286 (rename-buffer newname t)
2287 (cond
2288 ((fboundp 'font-lock-default-fontify-region)
2289 ;; Good: we have the indirection functions
2290 (set (make-local-variable 'font-lock-fontify-region-function)
2291 'reftex-select-font-lock-fontify-region)
2292 (let ((major-mode 'latex-mode))
2293 (font-lock-mode 1)))
2294 ((fboundp 'font-lock-set-defaults-1)
2295 ;; Looks like the XEmacs font-lock stuff.
2296 ;; FIXME: this is still kind of a hack, but it works.
2297 (set (make-local-variable 'font-lock-keywords) nil)
2298 (let ((major-mode 'latex-mode)
2299 (font-lock-defaults-computed nil))
2300 (font-lock-set-defaults-1)
2301 (reftex-select-font-lock-fontify-region (point-min) (point-max))))
2302 (t
2303 ;; Oops?
2304 (message "Sorry: cannot refontify RefTeX Select buffer."))))
2305 (rename-buffer oldname))))
2306
2307 (defun reftex-select-font-lock-fontify-region (beg end &optional loudly)
2308 ;; Fontify a region, but only lines starting with a dot.
2309 (let ((func (if (fboundp 'font-lock-default-fontify-region)
2310 'font-lock-default-fontify-region
2311 'font-lock-fontify-region))
2312 beg1 end1)
2313 (goto-char beg)
2314 (while (re-search-forward "^\\." end t)
2315 (setq beg1 (point) end1 (progn (skip-chars-forward "^\n") (point)))
2316 (funcall func beg1 end1 nil)
2317 (goto-char end1))))
2318
2319 (defun reftex-select-font-lock-unfontify (&rest ignore) t)
2320
2321 (defun reftex-verified-face (&rest faces)
2322 ;; Return the first valid face in FACES, or nil if none is valid.
2323 ;; Also, when finding a nil element in FACES, return nil. This
2324 ;; function is just a safety net to catch name changes of builtin
2325 ;; fonts. Currently it is only used for reftex-label-face, which has
2326 ;; as default font-lock-reference-face, which was recently renamed
2327 ;; to font-lock-constant-face.
2328 (let (face)
2329 (catch 'exit
2330 (while (setq face (pop faces))
2331 (if (featurep 'xemacs)
2332 (if (find-face face) (throw 'exit face))
2333 (if (facep face) (throw 'exit face)))))))
2334
2335 ;; Highlighting uses overlays. For XEmacs, we use extends.
2336 (defalias 'reftex-make-overlay
2337 (if (featurep 'xemacs) 'make-extent 'make-overlay))
2338 (defalias 'reftex-overlay-put
2339 (if (featurep 'xemacs) 'set-extent-property 'overlay-put))
2340 (defalias 'reftex-move-overlay
2341 (if (featurep 'xemacs) 'set-extent-endpoints 'move-overlay))
2342 (defalias 'reftex-delete-overlay
2343 (if (featurep 'xemacs) 'detach-extent 'delete-overlay))
2344
2345 ;; We keep a vector with several different overlays to do our highlighting.
2346 (defvar reftex-highlight-overlays [nil nil nil])
2347
2348 ;; Initialize the overlays
2349 (aset reftex-highlight-overlays 0 (reftex-make-overlay 1 1))
2350 (reftex-overlay-put (aref reftex-highlight-overlays 0)
2351 'face 'highlight)
2352 (aset reftex-highlight-overlays 1 (reftex-make-overlay 1 1))
2353 (reftex-overlay-put (aref reftex-highlight-overlays 1)
2354 'face reftex-cursor-selected-face)
2355 (aset reftex-highlight-overlays 2 (reftex-make-overlay 1 1))
2356 (reftex-overlay-put (aref reftex-highlight-overlays 2)
2357 'face reftex-cursor-selected-face)
2358
2359 ;; Two functions for activating and deactivation highlight overlays
2360 (defun reftex-highlight (index begin end &optional buffer)
2361 "Highlight a region with overlay INDEX."
2362 (reftex-move-overlay (aref reftex-highlight-overlays index)
2363 begin end (or buffer (current-buffer))))
2364 (defun reftex-unhighlight (index)
2365 "Detach overlay INDEX."
2366 (reftex-delete-overlay (aref reftex-highlight-overlays index)))
2367
2368 (defun reftex-highlight-shall-die ()
2369 ;; Function used in pre-command-hook to remove highlights.
2370 (remove-hook 'pre-command-hook 'reftex-highlight-shall-die)
2371 (reftex-unhighlight 0))
2372
2373 ;;; =========================================================================
2374 ;;;
2375 ;;; Keybindings
2376
2377 ;; The default bindings in the mode map.
2378 (loop for x in
2379 '(("\C-c=" . reftex-toc)
2380 ("\C-c-" . reftex-toc-recenter)
2381 ("\C-c(" . reftex-label)
2382 ("\C-c)" . reftex-reference)
2383 ("\C-c[" . reftex-citation)
2384 ("\C-c<" . reftex-index)
2385 ("\C-c>" . reftex-display-index)
2386 ("\C-c/" . reftex-index-selection-or-word)
2387 ("\C-c\\" . reftex-index-phrase-selection-or-word)
2388 ("\C-c|" . reftex-index-visit-phrases-buffer)
2389 ("\C-c&" . reftex-view-crossref))
2390 do (define-key reftex-mode-map (car x) (cdr x)))
2391
2392 ;; Bind `reftex-mouse-view-crossref' only when the key is still free
2393 (if (featurep 'xemacs)
2394 (unless (key-binding [(shift button2)])
2395 (define-key reftex-mode-map [(shift button2)]
2396 'reftex-mouse-view-crossref))
2397 (unless (key-binding [(shift mouse-2)])
2398 (define-key reftex-mode-map [(shift mouse-2)]
2399 'reftex-mouse-view-crossref)))
2400
2401 ;; Bind `reftex-view-crossref-from-bibtex' in BibTeX mode map
2402 (eval-after-load
2403 "bibtex"
2404 '(define-key bibtex-mode-map "\C-c&" 'reftex-view-crossref-from-bibtex))
2405
2406 ;; If the user requests so, she can have a few more bindings:
2407 (when reftex-extra-bindings
2408 (loop for x in
2409 '(("\C-ct" . reftex-toc)
2410 ("\C-cl" . reftex-label)
2411 ("\C-cr" . reftex-reference)
2412 ("\C-cc" . reftex-citation)
2413 ("\C-cv" . reftex-view-crossref)
2414 ("\C-cg" . reftex-grep-document)
2415 ("\C-cs" . reftex-search-document))
2416 do (define-key reftex-mode-map (car x) (cdr x))))
2417
2418 ;;; =========================================================================
2419 ;;;
2420 ;;; Menu
2421
2422 ;; Define a menu for the menu bar if Emacs is running under X
2423
2424 (defvar reftex-isearch-minor-mode nil)
2425 (make-variable-buffer-local 'reftex-isearch-minor-mode)
2426
2427 (easy-menu-define reftex-mode-menu reftex-mode-map
2428 "Menu used in RefTeX mode"
2429 `("Ref"
2430 ["Table of Contents" reftex-toc t]
2431 ["Recenter TOC" reftex-toc-recenter t]
2432 "--"
2433 ["\\label" reftex-label t]
2434 ["\\ref" reftex-reference t]
2435 ["\\cite" reftex-citation t]
2436 ("\\index"
2437 ["\\index" reftex-index t]
2438 ["\\index{THIS}" reftex-index-selection-or-word t]
2439 "--"
2440 ["Add THIS to Index Phrases" reftex-index-phrase-selection-or-word t]
2441 ["Visit Phrase Buffer" reftex-index-visit-phrases-buffer t]
2442 ["Apply Phrases to Region" reftex-index-phrases-apply-to-region t]
2443 "--"
2444 ["Display the Index" reftex-display-index t])
2445 "--"
2446 ["View Crossref" reftex-view-crossref t]
2447 "--"
2448 ("Parse Document"
2449 ["One File" reftex-parse-one reftex-enable-partial-scans]
2450 ["Entire Document" reftex-parse-all t]
2451 ["Save to File" (reftex-access-parse-file 'write)
2452 (> (length (symbol-value reftex-docstruct-symbol)) 0)]
2453 ["Restore from File" (reftex-access-parse-file 'restore) t])
2454 ("Global Actions"
2455 ["Search Whole Document" reftex-search-document t]
2456 ["Search Again" tags-loop-continue t]
2457 ["Replace in Document" reftex-query-replace-document t]
2458 ["Grep on Document" reftex-grep-document t]
2459 "--"
2460 ["Goto Label" reftex-goto-label t]
2461 ["Find Duplicate Labels" reftex-find-duplicate-labels t]
2462 ["Change Label and Refs" reftex-change-label t]
2463 ["Renumber Simple Labels" reftex-renumber-simple-labels t]
2464 "--"
2465 ["Create BibTeX File" reftex-create-bibtex-file t]
2466 "--"
2467 ["Create TAGS File" reftex-create-tags-file t]
2468 "--"
2469 ["Save Document" reftex-save-all-document-buffers t])
2470 "--"
2471 ("Options"
2472 "PARSER"
2473 ["Partial Scans"
2474 (setq reftex-enable-partial-scans (not reftex-enable-partial-scans))
2475 :style toggle :selected reftex-enable-partial-scans]
2476 ["Auto-Save Parse Info"
2477 (setq reftex-save-parse-info (not reftex-save-parse-info))
2478 :style toggle :selected reftex-save-parse-info]
2479 "--"
2480 "TOC RECENTER"
2481 ["Automatic Recenter" reftex-toggle-auto-toc-recenter
2482 :style toggle :selected reftex-toc-auto-recenter-timer]
2483 "--"
2484 "CROSSREF INFO"
2485 ["Automatic Info" reftex-toggle-auto-view-crossref
2486 :style toggle :selected reftex-auto-view-crossref-timer]
2487 ["...in Echo Area" (setq reftex-auto-view-crossref t)
2488 :style radio :selected (eq reftex-auto-view-crossref t)]
2489 ["...in Other Window" (setq reftex-auto-view-crossref 'window)
2490 :style radio :selected (eq reftex-auto-view-crossref 'window)]
2491 "--"
2492 "MISC"
2493 ["AUC TeX Interface" reftex-toggle-plug-into-AUCTeX
2494 :style toggle :selected reftex-plug-into-AUCTeX]
2495 ["isearch whole document" reftex-isearch-minor-mode
2496 :style toggle :selected reftex-isearch-minor-mode])
2497 ("Reference Style"
2498 ["Default" (setq reftex-vref-is-default nil
2499 reftex-fref-is-default nil)
2500 :style radio :selected (not (or reftex-vref-is-default
2501 reftex-fref-is-default))]
2502 ["Varioref" (setq reftex-vref-is-default t
2503 reftex-fref-is-default nil)
2504 :style radio :selected reftex-vref-is-default]
2505 ["Fancyref" (setq reftex-fref-is-default t
2506 reftex-vref-is-default nil)
2507 :style radio :selected reftex-fref-is-default])
2508 ("Citation Style"
2509 ,@(mapcar
2510 (lambda (x)
2511 (vector
2512 (capitalize (symbol-name (car x)))
2513 (list 'reftex-set-cite-format (list 'quote (car x)))
2514 :style 'radio :selected
2515 (list 'eq (list 'reftex-get-cite-format) (list 'quote (car x)))))
2516 reftex-cite-format-builtin)
2517 "--"
2518 "Sort Database Matches"
2519 ["Not" (setq reftex-sort-bibtex-matches nil)
2520 :style radio :selected (eq reftex-sort-bibtex-matches nil)]
2521 ["by Author" (setq reftex-sort-bibtex-matches 'author)
2522 :style radio :selected (eq reftex-sort-bibtex-matches 'author)]
2523 ["by Year" (setq reftex-sort-bibtex-matches 'year)
2524 :style radio :selected (eq reftex-sort-bibtex-matches 'year)]
2525 ["by Year, reversed" (setq reftex-sort-bibtex-matches 'reverse-year)
2526 :style radio :selected (eq reftex-sort-bibtex-matches 'reverse-year)])
2527 ("Index Style"
2528 ,@(mapcar
2529 (lambda (x)
2530 (vector
2531 (capitalize (symbol-name (car x)))
2532 (list 'reftex-add-index-macros (list 'list (list 'quote (car x))))
2533 :style 'radio :selected
2534 (list 'memq (list 'quote (car x))
2535 (list 'get 'reftex-docstruct-symbol
2536 (list 'quote 'reftex-index-macros-style)))))
2537 reftex-index-macros-builtin))
2538 "--"
2539 ["Reset RefTeX Mode" reftex-reset-mode t]
2540 "--"
2541 ("Customize"
2542 ["Browse RefTeX Group" reftex-customize t]
2543 "--"
2544 ["Build Full Customize Menu" reftex-create-customize-menu
2545 (fboundp 'customize-menu-create)])
2546 ("Documentation"
2547 ["Info" reftex-info t]
2548 ["Commentary" reftex-show-commentary t])))
2549
2550 (defun reftex-customize ()
2551 "Call the customize function with reftex as argument."
2552 (interactive)
2553 (customize-browse 'reftex))
2554
2555 (defun reftex-create-customize-menu ()
2556 "Create a full customization menu for RefTeX, insert it into the menu."
2557 (interactive)
2558 (if (fboundp 'customize-menu-create)
2559 (progn
2560 (easy-menu-change
2561 '("Ref") "Customize"
2562 `(["Browse RefTeX group" reftex-customize t]
2563 "--"
2564 ,(customize-menu-create 'reftex)
2565 ["Set" Custom-set t]
2566 ["Save" Custom-save t]
2567 ["Reset to Current" Custom-reset-current t]
2568 ["Reset to Saved" Custom-reset-saved t]
2569 ["Reset to Standard Settings" Custom-reset-standard t]))
2570 (message "\"Ref\"-menu now contains full customization menu"))
2571 (error "Cannot expand menu (outdated version of cus-edit.el)")))
2572
2573 (defun reftex-show-commentary ()
2574 "Use the finder to view the file documentation from `reftex.el'."
2575 (interactive)
2576 (finder-commentary "reftex.el"))
2577
2578 (defun reftex-info (&optional node)
2579 "Read documentation for RefTeX in the info system.
2580 With optional NODE, go directly to that node."
2581 (interactive)
2582 (info (format "(reftex)%s" (or node ""))))
2583
2584 ;;; Install the kill-buffer and kill-emacs hooks ------------------------------
2585
2586 (add-hook 'kill-buffer-hook 'reftex-kill-buffer-hook)
2587 (add-hook 'kill-emacs-hook 'reftex-kill-emacs-hook)
2588
2589 ;;; Run Hook ------------------------------------------------------------------
2590
2591 (run-hooks 'reftex-load-hook)
2592
2593 ;;; That's it! ----------------------------------------------------------------
2594
2595 (setq reftex-tables-dirty t) ; in case this file is evaluated by hand
2596 (provide 'reftex)
2597
2598 ;;;============================================================================
2599
2600 ;; arch-tag: 49e0da4e-bd5e-4cfc-a717-fb444fccb9e6
2601 ;;; reftex.el ends here