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