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