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