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