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