*** empty log message ***
[bpt/emacs.git] / lisp / textmodes / reftex.el
CommitLineData
1c25ed90
CD
1;;; reftex.el --- Minor mode for doing \label, \ref, \cite, \index in LaTeX
2;; Copyright (c) 1997, 1998, 1999 Free Software Foundation, Inc.
a7ec1775
RS
3
4;; Author: Carsten Dominik <dominik@strw.LeidenUniv.nl>
7c4d13cc 5;; Version: 4.9
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
7c4d13cc 303(defconst reftex-version "RefTeX version 4.9"
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)
1227 (concat (substring master 0 (match-beginning 0)) ".rel")
1228 (concat master ".rel"))))
1229 (cond
1230 ((eq action 'readable)
1231 (file-readable-p file))
1232 ((eq action 'restore)
1233 (put reftex-docstruct-symbol 'modified nil)
1234 (if (eq reftex-docstruct-symbol nil)
1235 ;; Symbols are not yet tied: Tie them.
1236 (reftex-tie-multifile-symbols))
1237 (if (file-exists-p file)
1238 ;; load the file and return t for success
1239 (condition-case nil
1240 (progn (load-file file) t)
1241 (error (set reftex-docstruct-symbol nil)
1242 (error "Error while loading file %s" file)))
1243 ;; Throw an exception if the file does not exist
1244 (error "No restore file %s" file)))
1245 ((eq action 'read)
1246 (put reftex-docstruct-symbol 'modified nil)
1247 (if (file-exists-p file)
1248 ;; load the file and return t for success
1249 (condition-case nil
1250 (progn
1251 (load-file file)
1252 (reftex-check-parse-consistency)
f9ad2e24 1253 t)
1c25ed90
CD
1254 (error (message "Error while restoring file %s" file)
1255 (set reftex-docstruct-symbol nil)
1256 nil))
1257 ;; return nil for failure, but no exception
1258 nil))
1259 ((eq action 'kill)
1260 ;; Remove the file
1261 (when (and (file-exists-p file) (file-writable-p file))
1262 (message "Unlinking file %s" file)
1263 (delete-file file)))
1264 (t
1265 (put docstruct-symbol 'modified nil)
1266 (save-excursion
1267 (if (file-writable-p file)
1268 (progn
1269 (message "Writing parse file %s" (abbreviate-file-name file))
1270 (find-file file)
1271 (erase-buffer)
1272 (insert (format ";; RefTeX parse info file\n"))
1273 (insert (format ";; File: %s\n" master))
1274 (insert (format ";; User: %s (%s)\n\n"
1275 (user-login-name) (user-full-name)))
1276 (insert "(set reftex-docstruct-symbol '(\n\n")
1277 (let ((standard-output (current-buffer)))
1278 (mapcar
1279 (lambda (x)
1280 (cond ((eq (car x) 'toc)
1281 ;; A toc entry. Do not save the marker.
1282 ;; Save the markers position at position 8
1283 (print (list 'toc "toc" (nth 2 x) (nth 3 x)
1284 nil (nth 5 x) (nth 6 x) (nth 7 x)
1285 (or (and (markerp (nth 4 x))
1286 (marker-position (nth 4 x)))
1287 (nth 8 x)))))
1288 ((and (not (eq t reftex-support-index))
1289 (eq (car x) 'index))
1290 ;; Don't save index entries
1291 )
1292 (t (print x))))
1293 list))
1294 (insert "))\n\n")
1295 (save-buffer 0)
1296 (kill-buffer (current-buffer)))
1297 (error "Cannot write to file %s" file)))
1298 t))))
921759ee 1299
1c25ed90
CD
1300(defun reftex-check-parse-consistency ()
1301 ;; Check if parse file is consistent, throw an error if not.
1302
1303 ;; Check if the master is the same: when moving a document, this will see it.
1304 (let* ((real-master (reftex-TeX-master-file))
1305 (parsed-master
1306 (nth 1 (assq 'bof (symbol-value reftex-docstruct-symbol)))))
1307 (unless (string= (file-truename real-master) (file-truename parsed-master))
1308 (message "Master file name in load file is different: %s versus %s"
1309 parsed-master real-master)
1310 (error "Master file name error")))
1311
1312 ;; Check for the existence of all document files
1313;;; (let* ((all (symbol-value reftex-docstruct-symbol)))
1314;;; (while all
1315;;; (when (and (eq (car (car all)) 'bof)
1316;;; (not (file-regular-p (nth 1 (car all)))))
1317;;; (message "File %s in saved parse info not avalable" (cdr (car all)))
1318;;; (error "File not found"))
1319;;; (setq all (cdr all))))
1320 )
1321
1322(defun reftex-select-external-document (xr-alist xr-index)
1323 ;; Return index of an external document.
1324 (let* ((len (length xr-alist)) (highest (1- (+ ?0 len)))
1325 (prompt (format "[%c-%c] Select TAB: Read prefix with completion"
1326 ?0 highest))
1327 key prefix)
1328 (cond
1329 ((= len 1)
1330 (message "No external documents available")
1331 (ding) (sit-for 1) 0)
1332 ((= len 2)
1333 (- 1 xr-index))
1334 (t
1335 (save-excursion
1336 (let* ((length (apply 'max (mapcar
1337 (lambda(x) (length (car x))) xr-alist)))
1338 (fmt (format " [%%c] %%-%ds %%s\n" length))
1339 (n (1- ?0)))
1340 (setq key
1341 (reftex-select-with-char
1342 prompt
1343 (concat
1344 "SELECT EXTERNAL DOCUMENT\n------------------------\n"
1345 (mapconcat
1346 (lambda (x)
1347 (format fmt (incf n) (or (car x) "")
1348 (abbreviate-file-name (cdr x))))
1349 xr-alist ""))
1350 nil t))
1351 (cond
1352 ((and (>= key ?0) (<= key highest)) (- key ?0))
1353 ((= key ?\C-i)
1354 (setq prefix (completing-read "Prefix: " xr-alist nil t))
1355 (- len (length (memq (assoc prefix xr-alist) xr-alist))))
1356 (t (error "Illegal document selection [%c]" key)))))))))
b849548d
CD
1357
1358;;; =========================================================================
1359;;;
1360;;; Finding files
1361
f9ad2e24
CD
1362(defun reftex-locate-file (file type master-dir &optional die)
1363 "Find FILE of type TYPE in MASTER-DIR or on the path associcted with TYPE.
1364If the file does not have any of the legal extensions for TYPE,
1365try first the default extension and only then the naked file name.
1366When DIE is non-nil, throw an error if file not found."
1367 (let* ((rec-values (if reftex-search-unrecursed-path-first '(nil t) '(t)))
1368 (extensions (cdr (assoc type reftex-file-extensions)))
1369 (def-ext (car extensions))
1370 (ext-re (concat "\\("
1371 (mapconcat 'regexp-quote extensions "\\|")
1372 "\\)\\'"))
1373 (files (if (string-match ext-re file)
1374 (cons file nil)
1375 (cons (concat file def-ext) file)))
1376 path old-path file1)
51d628c8
CD
1377 (cond
1378 ((file-name-absolute-p file)
f9ad2e24
CD
1379 (setq file1
1380 (or
1381 (and (car files) (file-regular-p (car files)) (car files))
1382 (and (cdr files) (file-regular-p (cdr files)) (cdr files)))))
51d628c8 1383 ((and reftex-use-external-file-finders
f9ad2e24
CD
1384 (assoc type reftex-external-file-finders))
1385 (setq file1 (reftex-find-file-externally file type master-dir)))
51d628c8 1386 (t
b849548d 1387 (while (and (null file1) rec-values)
a6611c0d 1388 (setq path (reftex-access-search-path
f9ad2e24 1389 type (pop rec-values) master-dir file))
b849548d
CD
1390 (if (or (null old-path)
1391 (not (eq old-path path)))
1392 (setq old-path path
1393 path (cons master-dir path)
f9ad2e24
CD
1394 file1 (or (and (car files)
1395 (reftex-find-file-on-path
1396 (car files) path master-dir))
1397 (and (cdr files)
1398 (reftex-find-file-on-path
1399 (cdr files) path master-dir))))))))
b849548d
CD
1400 (cond (file1 file1)
1401 (die (error "No such file: %s" file) nil)
1402 (t (message "No such file: %s (ignored)" file) nil))))
1403
51d628c8
CD
1404(defun reftex-find-file-externally (file type &optional master-dir)
1405 ;; Use external program to find FILE.
f9ad2e24 1406 ;; The program is taken from `reftex-external-file-finders'.
51d628c8
CD
1407 ;; Interprete relative path definitions starting from MASTER-DIR.
1408 (let ((default-directory (or master-dir default-directory))
1409 (prg (cdr (assoc type reftex-external-file-finders)))
1410 out)
1411 (if (string-match "%f" prg)
1412 (setq prg (replace-match file t t prg)))
1413 (setq out (apply 'reftex-process-string (split-string prg)))
1c25ed90 1414 (if (string-match "[ \t\n]+\\'" out) ; chomp
51d628c8
CD
1415 (setq out (replace-match "" nil nil out)))
1416 (cond ((equal out "") nil)
1c25ed90 1417 ((file-regular-p out) (expand-file-name out master-dir))
51d628c8
CD
1418 (t nil))))
1419
1420(defun reftex-process-string (program &rest args)
1421 "Execute PROGRAM with arguments ARGS and return its STDOUT as a string."
1c25ed90
CD
1422 (let ((calling-dir default-directory)) ; remember default directory
1423 (with-output-to-string
1424 (with-current-buffer standard-output
1425 (let ((default-directory calling-dir)) ; set default directory
1426 (apply 'call-process program nil '(t nil) nil args))))))
51d628c8 1427
f9ad2e24
CD
1428(defun reftex-access-search-path (type &optional recurse master-dir file)
1429 ;; Access path from environment variables. TYPE is either "tex" or "bib".
b849548d
CD
1430 ;; When RECURSE is t, expand path elements ending in `//' recursively.
1431 ;; Relative path elements are left as they are. However, relative recursive
1432 ;; elements are expanded with MASTER-DIR as default directory.
1433 ;; The expanded path is cached for the next search.
1434 ;; FILE is just for the progress message.
1435 ;; Returns the derived path.
f9ad2e24 1436 (let* ((pathvar (intern (concat "reftex-" type "-path"))))
b849548d 1437 (when (null (get pathvar 'status))
f9ad2e24
CD
1438 ;; Get basic path
1439 (set pathvar
1440 (reftex-uniq
1441 (reftex-parse-colon-path
1442 (mapconcat
1443 (lambda(x)
1444 (if (string-match "^!" x)
1445 (apply 'reftex-process-string
1446 (split-string (substring x 1)))
1447 (or (getenv x) x)))
1448 ;; For consistency, the next line should look like this:
1449 ;; (cdr (assoc type reftex-path-environment))
1450 ;; However, historically we have separate options for the
1451 ;; environment variables, so we have to do this:
1452 (symbol-value (intern (concat "reftex-" type
1453 "path-environment-variables")))
1454 path-separator))))
b849548d
CD
1455 (put pathvar 'status 'split)
1456 ;; Check if we have recursive elements
1457 (let ((path (symbol-value pathvar)) dir rec)
1458 (while (setq dir (pop path))
1459 (when (string= (substring dir -2) "//")
1460 (if (file-name-absolute-p dir)
1461 (setq rec (or rec 'absolute))
1462 (setq rec 'relative))))
1463 (put pathvar 'rec-type rec)))
1464
1465 (if recurse
1466 ;; Return the recursive expansion of the path
1467 (cond
1468 ((not (get pathvar 'rec-type))
1469 ;; Path does not contain recursive elements - use simple path
1470 (symbol-value pathvar))
1471 ((or (not (get pathvar 'recursive-path))
1472 (and (eq (get pathvar 'rec-type) 'relative)
1473 (not (equal master-dir (get pathvar 'master-dir)))))
1474 ;; Either: We don't have a recursive expansion yet.
1475 ;; or: Relative recursive path elements need to be expanded
1476 ;; relative to new default directory
f9ad2e24 1477 (message "Expanding search path to find %s file: %s ..." type file)
b849548d
CD
1478 (put pathvar 'recursive-path
1479 (reftex-expand-path (symbol-value pathvar) master-dir))
1480 (put pathvar 'master-dir master-dir)
1481 (get pathvar 'recursive-path))
1482 (t
1483 ;; Recursive path computed earlier is still OK.
1484 (get pathvar 'recursive-path)))
1485 ;; The simple path was requested
1486 (symbol-value pathvar))))
1487
1488(defun reftex-find-file-on-path (file path &optional def-dir)
1489 ;; Find FILE along the directory list PATH.
1490 ;; DEF-DIR is the default directory for expanding relative path elements.
1491 (catch 'exit
1492 (when (file-name-absolute-p file)
a6611c0d 1493 (if (file-regular-p file)
b849548d
CD
1494 (throw 'exit file)
1495 (throw 'exit nil)))
f9ad2e24 1496 (let* ((thepath path) file1 dir)
b849548d
CD
1497 (while (setq dir (pop thepath))
1498 (when (string= (substring dir -2) "//")
1499 (setq dir (substring dir 0 -1)))
1500 (setq file1 (expand-file-name file (expand-file-name dir def-dir)))
a6611c0d 1501 (if (file-regular-p file1)
b849548d
CD
1502 (throw 'exit file1)))
1503 ;; No such file
1504 nil)))
1505
1506(defun reftex-parse-colon-path (path)
1507 ;; Like parse-colon-parse, but // or /~ are left alone.
1508 ;; Trailing ! or !! will be converted into `//' (emTeX convention)
1509 (mapcar
1510 (lambda (dir)
1511 (if (string-match "\\(//+\\|/*!+\\)\\'" dir)
1512 (setq dir (replace-match "//" t t dir)))
1513 (file-name-as-directory dir))
1514 (delete "" (split-string path (concat path-separator "+")))))
1515
1516(defun reftex-expand-path (path &optional default-dir)
1517 ;; Expand parts of path ending in `//' recursively into directory list.
1518 ;; Relative recursive path elements are expanded relative to DEFAULT-DIR.
1519 (let (path1 dir recursive)
1520 (while (setq dir (pop path))
1521 (if (setq recursive (string= (substring dir -2) "//"))
1522 (setq dir (substring dir 0 -1)))
1523 (if (and recursive
1524 (not (file-name-absolute-p dir)))
1525 (setq dir (expand-file-name dir default-dir)))
1526 (if recursive
1527 ;; Expand recursively
1528 (setq path1 (append (reftex-recursive-directory-list dir) path1))
1529 ;; Keep unchanged
1530 (push dir path1)))
1531 (nreverse path1)))
a7ec1775 1532
b849548d
CD
1533(defun reftex-recursive-directory-list (dir)
1534 ;; Return a list of all directories below DIR, including DIR itself
1535 (let ((path (list dir)) path1 file files)
1536 (while (setq dir (pop path))
1537 (when (file-directory-p dir)
1538 (setq files (nreverse (directory-files dir t "[^.]")))
1539 (while (setq file (pop files))
1540 (if (file-directory-p file)
1541 (push (file-name-as-directory file) path)))
1542 (push dir path1)))
1543 path1))
a7ec1775 1544
f9ad2e24
CD
1545(defun reftex-uniq (list)
1546 (let (new)
1547 (while list
1548 (or (member (car list) new)
1549 (push (car list) new))
1550 (pop list))
1551 (nreverse new)))
1552
1c25ed90
CD
1553
1554;;; =========================================================================
1555;;;
1556;;; Parser functions
1557
1558(autoload 'reftex-parse-one "reftex-parse"
1559 "Re-parse this file." t)
1560(autoload 'reftex-parse-all "reftex-parse"
1561 "Re-parse entire document." t)
1562(autoload 'reftex-do-parse "reftex-parse")
1563(autoload 'reftex-where-am-I "reftex-parse")
1564(autoload 'reftex-init-section-numbers "reftex-parse")
1565(autoload 'reftex-section-info "reftex-parse")
1566(autoload 'reftex-section-number "reftex-parse")
1567(autoload 'reftex-what-macro "reftex-parse")
1568(autoload 'reftex-what-macro-safe "reftex-parse")
1569(autoload 'reftex-index-info "reftex-parse")
1570(autoload 'reftex-index-info-safe "reftex-parse")
1571(autoload 'reftex-short-context "reftex-parse")
1572(autoload 'reftex-what-environment "reftex-parse")
1573(autoload 'reftex-what-special-env "reftex-parse")
1574(autoload 'reftex-move-over-touching-args "reftex-parse")
1575(autoload 'reftex-notice-new "reftex-parse")
1576(autoload 'reftex-nth-arg "reftex-parse")
1577(autoload 'reftex-locate-bibliography-files "reftex-parse")
1578(autoload 'reftex-all-document-files "reftex-parse")
1579(autoload 'reftex-ensure-index-support "reftex-parse")
1580(autoload 'reftex-everything-regexp "reftex-parse")
1581
1582
1583;;; =========================================================================
1584;;;
1585;;; Labels and References
1586
1587(autoload 'reftex-label-location "reftex-ref")
1588(autoload 'reftex-label-info-update "reftex-ref")
1589(autoload 'reftex-label-info "reftex-ref")
1590(autoload 'reftex-label "reftex-ref"
1591 "Insert a unique label." t)
1592(autoload 'reftex-reference "reftex-ref"
1593 "Make a LaTeX reference." t)
1594(autoload 'reftex-show-label-location "reftex-ref")
1595(autoload 'reftex-query-label-type "reftex-ref")
1596
1597
1598;;; =========================================================================
1599;;;
1600;;; Table of contents
1601
1602(autoload 'reftex-toc "reftex-toc"
1603 "Show the table of contents for the current document." t)
1604
1605
1606;;; =========================================================================
1607;;;
1608;;; BibTeX citations.
1609
1610(autoload 'reftex-make-cite-echo-string "reftex-cite")
1611(autoload 'reftex-get-bibfile-list "reftex-cite")
1612(autoload 'reftex-pop-to-bibtex-entry "reftex-cite")
1613(autoload 'reftex-end-of-bib-entry "reftex-cite")
1614(autoload 'reftex-parse-bibtex-entry "reftex-cite")
1615(autoload 'reftex-citation "reftex-cite"
1616 "Make a citation using BibTeX database files." t)
1617(autoload 'reftex-default-bibliography "reftex-cite")
1618
1619
1620;;; =========================================================================
1621;;;
1622;;; Selection
1623
1624(autoload 'reftex-select-label-mode "reftex-sel")
1625(autoload 'reftex-select-bib-mode "reftex-sel")
1626(autoload 'reftex-find-start-point "reftex-sel")
1627(autoload 'reftex-insert-docstruct "reftex-sel")
1628(autoload 'reftex-get-offset "reftex-sel")
1629(autoload 'reftex-select-item "reftex-sel")
1630
1631
1632;;; =========================================================================
1633;;;
1634;;; Index support
1635
1636(autoload 'reftex-index "reftex-index"
1637 "Query for an index macro and insert it along with its argments." t)
1638(autoload 'reftex-index-selection-or-word "reftex-index"
1639 "Put selection or the word near point into the default index macro." t)
7c4d13cc
CD
1640(autoload 'reftex-index-phrase-selection-or-word "reftex-index"
1641 "Put selection or the word near point into Index Phrases File." t)
1c25ed90
CD
1642(autoload 'reftex-display-index "reftex-index"
1643 "Display a buffer with an index compiled from the current document." t)
7c4d13cc
CD
1644(autoload 'reftex-index-visit-phrases-buffer "reftex-index"
1645 "Visit the Index Phrases File." t)
1646(autoload 'reftex-index-phrases-mode "reftex-index"
1647 "Major mode for managing the Index phrases of a LaTeX document." t)
1c25ed90
CD
1648(autoload 'reftex-index-complete-tag "reftex-index")
1649(autoload 'reftex-index-complete-key "reftex-index")
1650(autoload 'reftex-index-show-entry "reftex-index")
1651(autoload 'reftex-index-select-tag "reftex-index")
1652
1653
1654;;; =========================================================================
1655;;;
1656;;; View cross references
1657
df543367 1658(autoload 'reftex-view-crossref "reftex-dcr"
1c25ed90 1659 "View cross reference of \\ref or \\cite macro at point." t)
df543367 1660(autoload 'reftex-mouse-view-crossref "reftex-dcr"
1c25ed90 1661 "View cross reference of \\ref or \\cite macro where you click." t)
df543367
CD
1662(autoload 'reftex-toggle-auto-view-crossref "reftex-dcr")
1663(autoload 'reftex-view-crossref-from-bibtex "reftex-dcr"
1c25ed90
CD
1664 "View location in a LaTeX document which cites the BibTeX entry at point." t)
1665
1666
1667;;; =========================================================================
1668;;;
1669;;; Operations on entire Multifile documents
1670
1671(autoload 'reftex-create-tags-file "reftex-global"
1672 "Create TAGS file by running `etags' on the current document." t)
1673(autoload 'reftex-grep-document "reftex-global"
1674 "Run grep query through all files related to this document." t)
1675(autoload 'reftex-search-document "reftex-global"
1676 "Regexp search through all files of the current TeX document." t)
1677(autoload 'reftex-query-replace-document "reftex-global"
1678 "Run a query-replace-regexp of FROM with TO over the entire TeX document." t)
1679(autoload 'reftex-find-duplicate-labels "reftex-global"
1680 "Produce a list of all duplicate labels in the document." t)
1681(autoload 'reftex-change-label "reftex-global"
1682 "Query replace FROM with TO in all \\label and \\ref commands." t)
1683(autoload 'reftex-renumber-simple-labels "reftex-global"
1684 "Renumber all simple labels in the document to make them sequentially." t)
1685(autoload 'reftex-save-all-document-buffers "reftex-global"
1686 "Save all documents associated with the current document." t)
1687
1688
1689;;; =========================================================================
1690;;;
1691;;; AUCTeX Interface
1692
1693(autoload 'reftex-arg-label "reftex-auc")
1694(autoload 'reftex-arg-cite "reftex-auc")
1695(autoload 'reftex-arg-index-tag "reftex-auc")
1696(autoload 'reftex-arg-index "reftex-auc")
1697(autoload 'reftex-plug-into-AUCTeX "reftex-auc")
1698(autoload 'reftex-toggle-plug-into-AUCTeX "reftex-auc"
1699 "Toggle Interface between AUCTeX and RefTeX on and off." t)
1700(autoload 'reftex-add-label-environments "reftex-auc")
7c4d13cc 1701(autoload 'reftex-add-to-label-alist "reftex-auc")
1c25ed90
CD
1702(autoload 'reftex-add-section-levels "reftex-auc")
1703(autoload 'reftex-notice-new-section "reftex-auc")
1704
b849548d
CD
1705;;; =========================================================================
1706;;;
1707;;; Some generally useful functions
a7ec1775 1708
1c25ed90
CD
1709(defun reftex-typekey-check (typekey conf-variable &optional n)
1710 ;; Check if CONF-VARIABLE is true or contains TYPEKEY
1711 (and n (setq conf-variable (nth n conf-variable)))
1712 (or (eq conf-variable t)
1713 (and (stringp conf-variable)
1714 (string-match (concat "[" conf-variable "]") typekey))))
1715
1716(defun reftex-check-recursive-edit ()
1717 ;; Check if we are already in a recursive edit. Abort with helpful
1718 ;; message if so.
1719 (if (marker-position reftex-recursive-edit-marker)
1720 (error
1721 (substitute-command-keys
1722 "In unfinished selection process. Finish, or abort with \\[abort-recursive-edit]"))))
1723
1724(defun reftex-in-comment ()
1725 (save-excursion
1726 (skip-chars-backward "^%\n\r")
1727 (eq (preceding-char) ?%)))
1728
a7ec1775
RS
1729(defun reftex-no-props (string)
1730 ;; Return STRING with all text properties removed
1731 (and (stringp string)
1732 (set-text-properties 0 (length string) nil string))
1733 string)
1734
396e0b08
KH
1735(defun reftex-match-string (n)
1736 ;; Match string without properties
1737 (when (match-beginning n)
1738 (buffer-substring-no-properties (match-beginning n) (match-end n))))
1739
2faef409 1740(defun reftex-kill-buffer (buffer)
29d593f8 1741 ;; Kill buffer if it exists.
2faef409
RS
1742 (and (setq buffer (get-buffer buffer))
1743 (kill-buffer buffer)))
1744
29d593f8
KH
1745(defun reftex-erase-buffer (&optional buffer)
1746 ;; Erase BUFFER if it exists. BUFFER defaults to current buffer.
1747 ;; This even erases read-only buffers.
1748 (cond
1749 ((null buffer)
1750 ;; erase current buffer
1751 (let ((buffer-read-only nil)) (erase-buffer)))
1752 ((setq buffer (get-buffer buffer))
1753 ;; buffer exists
1754 (save-excursion
1755 (set-buffer buffer)
1756 (let ((buffer-read-only nil)) (erase-buffer))))))
2faef409 1757
396e0b08
KH
1758(defun reftex-this-word (&optional class)
1759 ;; Grab the word around point.
1760 (setq class (or class "-a-zA-Z0-9:_/.*;|"))
1761 (save-excursion
1762 (buffer-substring-no-properties
1763 (progn (skip-chars-backward class) (point))
1764 (progn (skip-chars-forward class) (point)))))
1765
7c4d13cc
CD
1766(defun reftex-number (n unit &optional ending)
1767 (if (and (integerp n) (stringp unit))
1768 (format "%d %s%s" n unit (if (= n 1) "" (or ending "s")))
1769 ""))
1770
b849548d
CD
1771(defun reftex-all-assq (key list)
1772 ;; Return a list of all associations of KEY in LIST. Comparison with eq.
1773 (let (rtn)
1774 (while (setq list (memq (assq key list) list))
1775 (push (car list) rtn)
1776 (pop list))
1777 (nreverse rtn)))
1778
1779(defun reftex-all-assoc-string (key list)
1780 ;; Return a list of all associations of KEY in LIST. Comparison with string=.
1781 (let (rtn)
1782 (while list
1783 (if (string= (car (car list)) key)
1784 (push (car list) rtn))
1785 (pop list))
1786 (nreverse rtn)))
1787
1c25ed90 1788(defun reftex-last-assoc-before-elt (key elt list &optional exclusive)
b849548d
CD
1789 ;; Find the last association of KEY in LIST before or at ELT
1790 ;; ELT is found in LIST with equal, not eq.
1791 ;; Returns nil when either KEY or elt are not found in LIST.
1c25ed90 1792 ;; When EXCLUSIVE is non-nil, ELT cannot be the return value.
b849548d 1793 ;; On success, returns the association.
1c25ed90 1794 (let* ((elt (car (member elt list))) (ex (not exclusive)) ass last-ass)
b849548d
CD
1795 (while (and (setq ass (assoc key list))
1796 (setq list (memq ass list))
1c25ed90 1797 (or ex (not (eq elt (car list))))
b849548d
CD
1798 (memq elt list))
1799 (setq last-ass ass
1800 list (cdr list)))
1801 last-ass))
1802
1c25ed90
CD
1803(defun reftex-sublist-nth (list nth predicate &optional completion)
1804 ;; Make a list of the NTH elements of all members of LIST which
1805 ;; fulfill PREDICATE.
1806 ;; When COMPLETION is non-nil, make all elements of the resulting
1807 ;; list also a list, so that the result can be used for completion.
1808 (let (rtn)
1809 (while list
1810 (if (funcall predicate (car list))
1811 (push (if completion
1812 (list (nth nth (car list)))
1813 (nth nth (car list)))
1814 rtn))
1815 (setq list (cdr list)))
1816 (nreverse rtn)))
1817
1818(defun reftex-make-selection-buffer-name (type &optional index)
1819 ;; Make unique name for a selection buffer.
1820 (format " *RefTeX[%s][%d]*"
1821 type (or index (get reftex-docstruct-symbol :master-index) 0)))
1822
1823(defun reftex-make-index-buffer-name (tag &optional cnt)
1824 ;; Make unique name for an index buffer.
1825 (format "*Index[%s][%d]*"
1826 tag (or cnt (get reftex-docstruct-symbol :master-index) 0)))
1827
396e0b08 1828(defun reftex-truncate (string ncols &optional ellipses padding)
f9ad2e24
CD
1829 ;; Truncate STRING to NCOLS characters.
1830 ;; When PADDING is non-nil, and string is shorter than NCOLS, fill with
1831 ;; white space to NCOLS characters. When ELLIPSES is non-nil and the
1832 ;; string needs to be truncated, replace last 3 characters by dots.
396e0b08 1833 (setq string
f9ad2e24
CD
1834 (if (<= (length string) ncols)
1835 string
1836 (if ellipses
1837 (concat (substring string 0 (- ncols 3)) "...")
1838 (substring string 0 ncols))))
396e0b08
KH
1839 (if padding
1840 (format (format "%%-%ds" ncols) string)
1841 string))
1842
1c25ed90 1843(defun reftex-nearest-match (regexp &optional max-length)
b849548d
CD
1844 ;; Find the nearest match of REGEXP. Set the match data.
1845 ;; If POS is given, calculate distances relative to it.
1846 ;; Return nil if there is no match.
1c25ed90
CD
1847 (let ((pos (point))
1848 (dist (or max-length (length regexp)))
1849 match1 match2 match)
1850 (goto-char (min (+ pos dist) (point-max)))
b849548d
CD
1851 (when (re-search-backward regexp nil t)
1852 (setq match1 (match-data)))
1c25ed90 1853 (goto-char (max (- pos dist) (point-min)))
b849548d
CD
1854 (when (re-search-forward regexp nil t)
1855 (setq match2 (match-data)))
1c25ed90 1856 (goto-char pos)
b849548d
CD
1857 (setq match
1858 (cond
1859 ((not match1) match2)
1860 ((not match2) match1)
1861 ((< (abs (- pos (car match1))) (abs (- pos (car match2)))) match1)
1862 (t match2)))
1863 (if match (progn (set-match-data match) t) nil)))
1864
1865(defun reftex-auto-mode-alist ()
1866 ;; Return an `auto-mode-alist' with only the .gz (etc) thingies.
1867 ;; Stolen from gnus nnheader.
1868 (let ((alist auto-mode-alist)
1869 out)
1870 (while alist
1871 (when (listp (cdr (car alist)))
1872 (push (car alist) out))
1873 (pop alist))
1874 (nreverse out)))
1875
921759ee
CD
1876(defun reftex-window-height ()
1877 (if (fboundp 'window-displayed-height)
1878 (window-displayed-height)
1879 (window-height)))
1880
b849548d
CD
1881(defun reftex-enlarge-to-fit (buf2 &optional keep-current)
1882 ;; Enlarge other window displaying buffer to show whole buffer if possible.
1883 ;; If KEEP-CURRENT in non-nil, current buffer must remain visible.
1884 (let* ((win1 (selected-window))
1885 (buf1 (current-buffer))
921759ee 1886 (win2 (get-buffer-window buf2))) ;; Only on current frame.
b849548d
CD
1887 (when win2
1888 (select-window win2)
1889 (unless (and (pos-visible-in-window-p 1)
1890 (pos-visible-in-window-p (point-max)))
1891 (enlarge-window (1+ (- (count-lines 1 (point-max))
921759ee 1892 (reftex-window-height))))))
b849548d
CD
1893 (cond
1894 ((window-live-p win1) (select-window win1))
1895 (keep-current
1896 ;; we must have the old buffer!
1897 (switch-to-buffer-other-window buf1)
1898 (shrink-window (- (window-height) window-min-height))))))
1899
1900(defun reftex-select-with-char (prompt help-string &optional delay-time scroll)
1901 ;; Offer to select something with PROMPT and, after DELAY-TIME seconds,
1902 ;; also with HELP-STRING.
1903 ;; When SCROLL is non-nil, use SPC and DEL to scroll help window.
1904 (let ((char ?\?))
1905 (save-window-excursion
1906 (catch 'exit
1907 (message (concat prompt " (?=Help)"))
1908 (when (or (sit-for (or delay-time 0))
1909 (= ?\? (setq char (read-char-exclusive))))
921759ee
CD
1910 (reftex-kill-buffer "*RefTeX Select*")
1911 (switch-to-buffer-other-window "*RefTeX Select*")
1912 (insert help-string)
1913 (goto-char 1)
1914 (unless (and (pos-visible-in-window-p 1)
1915 (pos-visible-in-window-p (point-max)))
1916 (enlarge-window (1+ (- (count-lines 1 (point-max))
1917 (reftex-window-height)))))
b849548d 1918 (setq truncate-lines t))
1c25ed90
CD
1919 (if (and (pos-visible-in-window-p 1)
1920 (pos-visible-in-window-p (point-max)))
1921 nil
1922 (setq prompt (concat prompt (if scroll " (SPC/DEL=Scroll)" ""))))
b849548d
CD
1923 (message prompt)
1924 (and (equal char ?\?) (setq char (read-char-exclusive)))
1925 (while t
1926 (cond ((equal char ?\C-g) (keyboard-quit))
1927 ((equal char ?\?))
1928 ((and scroll (equal char ?\ ))
1929 (condition-case nil (scroll-up) (error nil))
1930 (message prompt))
1931 ((and scroll (equal char ?\C-? ))
1932 (condition-case nil (scroll-down) (error nil))
1933 (message prompt))
1c25ed90
CD
1934 (t (message "")
1935 (throw 'exit char)))
b849548d 1936 (setq char (read-char-exclusive)))))))
1c25ed90 1937
b849548d
CD
1938
1939(defun reftex-make-regexp-allow-for-ctrl-m (string)
1940 ;; convert STRING into a regexp, allowing ^M for \n and vice versa
1941 (let ((start -2))
1942 (setq string (regexp-quote string))
1943 (while (setq start (string-match "[\n\r]" string (+ 3 start)))
1944 (setq string (replace-match "[\n\r]" nil t string)))
1945 string))
1946
1947(defun reftex-get-buffer-visiting (file)
1948 ;; return a buffer visiting FILE
1949 (cond
1950 ((boundp 'find-file-compare-truenames) ; XEmacs
1951 (let ((find-file-compare-truenames t))
1952 (get-file-buffer file)))
1953 ((fboundp 'find-buffer-visiting) ; Emacs
1954 (find-buffer-visiting file))
1955 (t (error "This should not happen (reftex-get-buffer-visiting)"))))
1956
1957;; Define `current-message' for compatibility with XEmacs prior to 20.4
1958(defvar message-stack)
1959(if (and (featurep 'xemacs)
1960 (not (fboundp 'current-message)))
1961 (defun current-message (&optional frame)
1962 (cdr (car message-stack))))
1963
1964(defun reftex-visited-files (list)
1965 ;; Takes a list of filenames and returns the buffers of those already visited
1966 (delq nil (mapcar (lambda (x) (if (reftex-get-buffer-visiting x) x nil))
1967 list)))
1968
1969(defun reftex-get-file-buffer-force (file &optional mark-to-kill)
1970 ;; Return a buffer visiting file. Make one, if necessary.
1971 ;; If neither such a buffer nor the file exist, return nil.
1972 ;; If MARK-TO-KILL is t and there is no live buffer, visit the file with
1973 ;; initializations according to `reftex-initialize-temporary-buffers',
1974 ;; and mark the buffer to be killed after use.
1975
1976 (let ((buf (reftex-get-buffer-visiting file)))
1977
1978 (cond (buf
1979 ;; We have it already as a buffer - just return it
1980 buf)
1981
1982 ((file-readable-p file)
1983 ;; At least there is such a file and we can read it.
1984
1985 (if (or (not mark-to-kill)
1986 (eq t reftex-initialize-temporary-buffers))
1987
1988 ;; Visit the file with full magic
1989 (setq buf (find-file-noselect file))
1990
1991 ;; Else: Visit the file just briefly, without or
1992 ;; with limited Magic
1993
1994 ;; The magic goes away
1995 (let ((format-alist nil)
1996 (auto-mode-alist (reftex-auto-mode-alist))
1997 (default-major-mode 'fundamental-mode)
1998 (enable-local-variables nil)
1999 (after-insert-file-functions nil))
2000 (setq buf (find-file-noselect file)))
2001
2002 ;; Is there a hook to run?
2003 (when (listp reftex-initialize-temporary-buffers)
2004 (save-excursion
2005 (set-buffer buf)
2006 (run-hooks 'reftex-initialize-temporary-buffers))))
2007
2008 ;; Lets see if we got a license to kill :-|
2009 (and mark-to-kill
1c25ed90 2010 (add-to-list 'reftex-buffers-to-kill buf))
a7ec1775 2011
1c25ed90
CD
2012 ;; Return the new buffer
2013 buf)
396e0b08 2014
1c25ed90
CD
2015 ;; If no such file exists, return nil
2016 (t nil))))
396e0b08 2017
1c25ed90
CD
2018(defun reftex-kill-temporary-buffers (&optional buffer)
2019 ;; Kill all buffers in the list reftex-kill-temporary-buffers.
2020 (cond
2021 (buffer
2022 (when (member buffer reftex-buffers-to-kill)
2023 (kill-buffer buffer)
2024 (setq reftex-buffers-to-kill
2025 (delete buffer reftex-buffers-to-kill))))
2026 (t
2027 (while (setq buffer (pop reftex-buffers-to-kill))
2028 (when (bufferp buffer)
2029 (and (buffer-modified-p buffer)
2030 (y-or-n-p (format "Save file %s? "
2031 (buffer-file-name buffer)))
2032 (save-excursion
2033 (set-buffer buffer)
2034 (save-buffer)))
2035 (kill-buffer buffer))
2036 (pop reftex-buffers-to-kill)))))
396e0b08 2037
1c25ed90
CD
2038(defun reftex-splice-symbols-into-list (list alist)
2039 ;; Splice the association in ALIST of any symbols in LIST into the list.
2040 ;; Return new list.
2041 (let (rtn tmp)
2042 (while list
2043 (while (and (not (null (car list))) ;; keep list elements nil
2044 (symbolp (car list)))
2045 (setq tmp (car list))
2046 (cond
2047 ((assoc tmp alist)
2048 (setq list (append (nth 2 (assoc tmp alist)) (cdr list))))
2049 (t
2050 (error "Cannot treat symbol %s in reftex-label-alist"
2051 (symbol-name tmp)))))
2052 (push (pop list) rtn))
2053 (nreverse rtn)))
396e0b08 2054
1c25ed90
CD
2055(defun reftex-remove-symbols-from-list (list)
2056 ;; Remove all symbols from list
2057 (let (rtn)
2058 (while list
2059 (unless (symbolp (car list))
2060 (push (car list) rtn))
2061 (setq list (cdr list)))
2062 (nreverse rtn)))
b849548d 2063
48ffe14f
CD
2064(defun reftex-uniquify (list)
2065 ;; Return a list of all elements in LIST, but each only once
2066 (let (new elm)
2067 (while list
2068 (setq elm (pop list))
2069 (unless (member elm new)
2070 (push elm new)))
2071 (nreverse new)))
2072
1c25ed90
CD
2073(defun reftex-uniquify-by-car (alist &optional keep-list)
2074 ;; Return a list of all elements in ALIST, but each car only once.
2075 ;; Elements of KEEP-LIST are not removed even if duplicate.
2076 (let (new elm)
2077 (while alist
2078 (setq elm (pop alist))
2079 (if (or (member (car elm) keep-list)
2080 (not (assoc (car elm) new)))
2081 (push elm new)))
2082 (nreverse new)))
b849548d 2083
1c25ed90
CD
2084(defun reftex-abbreviate-title (string)
2085 (reftex-convert-string string "[-~ \t\n\r,;]" nil t t
2086 5 40 nil 1 " " (nth 5 reftex-derive-label-parameters)))
b849548d 2087
1c25ed90
CD
2088(defun reftex-convert-string (string split-re illegal-re dot keep-fp
2089 nwords maxchar illegal abbrev sep
2090 ignore-words &optional downcase)
2091 "Convert a string (a sentence) to something shorter.
2092SPLIT-RE is the regular expression used to split the string into words.
2093ILLEGAL-RE matches characters which are illegal in the final string.
2094DOT t means add dots to abbreviated words.
2095KEEP-FP t means to keep a final punctuation when applicable.
2096NWORDS Number of words to use.
2097MAXCHAR Maximum number of characters in the final string.
2098ILLEGAL nil: Throw away any words containing stuff matched with ILLEGAL-RE.
2099 t: Throw away only the matched part, not the whole word.
2100ABBREV nil: Never abbreviate words.
2101 t: Always abbreviate words (see `reftex-abbrev-parameters').
2102 not t and not nil: Abbreviate words if necessary to shorten
2103 string below MAXCHAR.
2104SEP String separating different words in the output string.
2105IGNORE-WORDS List of words which should be removed from the string."
396e0b08 2106
1c25ed90
CD
2107 (let* ((words0 (split-string string (or split-re "[ \t\n\r]")))
2108 (reftex-label-illegal-re (or illegal-re "\000"))
2109 (abbrev-re (concat
2110 "\\`\\("
2111 (make-string (nth 0 reftex-abbrev-parameters) ?.)
2112 "[" (nth 2 reftex-abbrev-parameters) "]*"
2113 "\\)"
2114 "[" (nth 3 reftex-abbrev-parameters) "]"
2115 (make-string (1- (nth 1 reftex-abbrev-parameters)) ?.)))
2116 words word)
396e0b08 2117
1c25ed90
CD
2118 ;; Remove words from the ignore list or with funny characters
2119 (while (setq word (pop words0))
2120 (if downcase (setq word (downcase word)))
2121 (cond
2122 ((member (downcase word) ignore-words))
2123 ((string-match reftex-label-illegal-re word)
2124 (when illegal
2125 (while (string-match reftex-label-illegal-re word)
2126 (setq word (replace-match "" nil nil word)))
2127 (push word words)))
2128 (t
2129 (push word words))))
2130 (setq words (nreverse words))
2131
2132 ;; Restrict number of words
2133 (if (> (length words) nwords)
2134 (setcdr (nthcdr (1- nwords) words) nil))
2135
2136 ;; First, try to use all words
2137 (setq string (mapconcat 'identity words sep))
2138
2139 ;; Abbreviate words if enforced by user settings or string length
2140 (if (or (eq t abbrev)
2141 (and abbrev
2142 (> (length string) maxchar)))
2143 (setq words
2144 (mapcar
2145 (lambda (w) (if (string-match abbrev-re w)
2146 (if dot
2147 (concat (match-string 1 w) ".")
2148 (match-string 1 w))
2149 w))
2150 words)
2151 string (mapconcat 'identity words sep)))
b849548d 2152
1c25ed90
CD
2153 ;; Shorten if still to long
2154 (setq string
2155 (if (> (length string) maxchar)
2156 (substring string 0 maxchar)
2157 string))
396e0b08 2158
1c25ed90
CD
2159 ;; Delete the final punctuation, if any
2160 (if (and (not keep-fp) (string-match "\\s.+\\'" string))
2161 (setq string (replace-match "" nil nil string)))
2162 string))
396e0b08 2163
1c25ed90
CD
2164(defun reftex-nicify-text (text)
2165 ;; Make TEXT nice for inclusion as context into label menu.
2166 ;; 1. remove line breaks and extra white space
2167 (while (string-match "[\n\r\t]\\|[ \t][ \t]+" text)
2168 (setq text (replace-match " " nil t text)))
2169 ;; 2. cut before the next `\end{' or `\item' or `\\'
2170 (if (string-match "\\(\\\\end{\\|\\\\item\\|\\\\\\\\\\).*" text)
2171 (setq text (replace-match "" nil t text)))
2172 ;; 3. kill the embedded label
2173 (if (string-match "\\\\label{[^}]*}" text)
2174 (setq text (replace-match "" nil t text)))
2175 ;; 4. remove leading garbage
2176 (if (string-match "\\`[ }]+" text)
2177 (setq text (replace-match "" nil t text)))
2178 ;; 5. limit length
2179 (cond
2180 ((> (length text) 100) (substring text 0 100))
2181 ((= (length text) 0) (make-string 1 ?\ ))
2182 (t text)))
396e0b08 2183
b849548d
CD
2184;;; =========================================================================
2185;;;
1c25ed90 2186;;; Fontification and Highlighting
a7ec1775 2187
1c25ed90
CD
2188(defun reftex-use-fonts ()
2189 ;; Return t if we can and want to use fonts.
2190 (and window-system
2191 reftex-use-fonts
2192 (featurep 'font-lock)))
a7ec1775 2193
1c25ed90
CD
2194(defun reftex-refontify ()
2195 ;; Return t if we need to refontify context
2196 (and (reftex-use-fonts)
2197 (or (eq t reftex-refontify-context)
2198 (and (eq 1 reftex-refontify-context)
2199 ;; Test of we use the font-lock version of x-symbol
2200 (and (featurep 'x-symbol-tex) (not (boundp 'x-symbol-mode)))))))
a7ec1775 2201
1c25ed90
CD
2202(defvar font-lock-defaults-computed)
2203(defun reftex-fontify-select-label-buffer (parent-buffer)
2204 ;; Fontify the `*RefTeX Select*' buffer. Buffer is temporarily renamed to
2205 ;; start with none-SPC char, beacuse Font-Lock otherwise refuses operation.
2206 (run-hook-with-args 'reftex-pre-refontification-functions
2207 parent-buffer 'reftex-ref)
2208 (let* ((oldname (buffer-name))
2209 (newname (concat "Fontify-me-" oldname)))
2210 (unwind-protect
b849548d 2211 (progn
1c25ed90
CD
2212 ;; Rename buffer temporarily to start w/o space (because of font-lock)
2213 (rename-buffer newname t)
2214 (cond
2215 ((fboundp 'font-lock-default-fontify-region)
2216 ;; Good: we have the indirection functions
2217 (set (make-local-variable 'font-lock-fontify-region-function)
2218 'reftex-select-font-lock-fontify-region)
2219 (let ((major-mode 'latex-mode))
2220 (font-lock-mode 1)))
2221 ((fboundp 'font-lock-set-defaults-1)
2222 ;; Looks like the XEmacs font-lock stuff.
2223 ;; FIXME: this is still kind of a hack, but it works.
2224 (set (make-local-variable 'font-lock-keywords) nil)
2225 (let ((major-mode 'latex-mode)
2226 (font-lock-defaults-computed nil))
2227 (font-lock-set-defaults-1)
2228 (reftex-select-font-lock-fontify-region (point-min) (point-max))))
2229 (t
2230 ;; Oops?
2231 (message "Sorry: cannot refontify RefTeX Select buffer."))))
2232 (rename-buffer oldname))))
a7ec1775 2233
1c25ed90
CD
2234(defun reftex-select-font-lock-fontify-region (beg end &optional loudly)
2235 ;; Fontify a region, but only lines starting with a dot.
2236 (let ((func (if (fboundp 'font-lock-default-fontify-region)
2237 'font-lock-default-fontify-region
2238 'font-lock-fontify-region))
2239 beg1 end1)
2240 (goto-char beg)
2241 (while (re-search-forward "^\\." end t)
2242 (setq beg1 (point) end1 (progn (skip-chars-forward "^\n") (point)))
2243 (funcall func beg1 end1 nil)
2244 (goto-char end1))))
a7ec1775 2245
1c25ed90 2246(defun reftex-select-font-lock-unfontify (&rest ignore) t)
a7ec1775 2247
1c25ed90
CD
2248(defun reftex-verified-face (&rest faces)
2249 ;; Return the first valid face in FACES, or nil if none is valid.
2250 ;; Also, when finding a nil element in FACES, return nil. This
2251 ;; function is just a safety net to catch name changes of builtin
2252 ;; fonts. Currently it is only used for reftex-label-face, which has
2253 ;; as default font-lock-reference-face, which was recently renamed
2254 ;; to font-lock-constant-face.
2255 (let (face)
2256 (catch 'exit
2257 (while (setq face (pop faces))
2258 (if (featurep 'xemacs)
2259 (if (find-face face) (throw 'exit face))
2260 (if (facep face) (throw 'exit face)))))))
a7ec1775 2261
1c25ed90
CD
2262;; Highlighting uses overlays. For XEmacs, we need the emulation.
2263(if (featurep 'xemacs) (require 'overlay))
396e0b08 2264
1c25ed90
CD
2265;; We keep a vector with several different overlays to do our highlighting.
2266(defvar reftex-highlight-overlays [nil nil])
b849548d 2267
1c25ed90
CD
2268;; Initialize the overlays
2269(aset reftex-highlight-overlays 0 (make-overlay 1 1))
2270(overlay-put (aref reftex-highlight-overlays 0)
2271 'face 'highlight)
2272(aset reftex-highlight-overlays 1 (make-overlay 1 1))
2273(overlay-put (aref reftex-highlight-overlays 1)
2274 'face reftex-cursor-selected-face)
b849548d 2275
1c25ed90
CD
2276;; Two functions for activating and deactivation highlight overlays
2277(defun reftex-highlight (index begin end &optional buffer)
2278 "Highlight a region with overlay INDEX."
2279 (move-overlay (aref reftex-highlight-overlays index)
2280 begin end (or buffer (current-buffer))))
2281(defun reftex-unhighlight (index)
2282 "Detach overlay INDEX."
2283 (delete-overlay (aref reftex-highlight-overlays index)))
2faef409 2284
1c25ed90
CD
2285(defun reftex-highlight-shall-die ()
2286 ;; Function used in pre-command-hook to remove highlights.
2287 (remove-hook 'pre-command-hook 'reftex-highlight-shall-die)
2288 (reftex-unhighlight 0))
b849548d
CD
2289
2290;;; =========================================================================
2291;;;
2292;;; Keybindings
a7ec1775 2293
b849548d
CD
2294;; The default bindings in the mode map.
2295(loop for x in
7c4d13cc
CD
2296 '(("\C-c=" . reftex-toc)
2297 ("\C-c(" . reftex-label)
2298 ("\C-c)" . reftex-reference)
2299 ("\C-c[" . reftex-citation)
2300 ("\C-c<" . reftex-index)
2301 ("\C-c>" . reftex-display-index)
2302 ("\C-c/" . reftex-index-selection-or-word)
2303 ("\C-c\\" . reftex-index-phrase-selection-or-word)
2304 ("\C-c|" . reftex-index-visit-phrases-buffer)
2305 ("\C-c&" . reftex-view-crossref))
b849548d 2306 do (define-key reftex-mode-map (car x) (cdr x)))
a7ec1775 2307
1c25ed90
CD
2308;; Bind `reftex-mouse-view-crossref' only when the key is still free
2309(if (featurep 'xemacs)
2310 (unless (key-binding [(shift button2)])
2311 (define-key reftex-mode-map [(shift button2)]
2312 'reftex-mouse-view-crossref))
2313 (unless (key-binding [(shift mouse-2)])
2314 (define-key reftex-mode-map [(shift mouse-2)]
2315 'reftex-mouse-view-crossref)))
2316
2317;; Bind `reftex-view-crossref-from-bibtex' in BibTeX mode map
2318(eval-after-load
921759ee
CD
2319 "bibtex"
2320 '(define-key bibtex-mode-map "\C-c&" 'reftex-view-crossref-from-bibtex))
2321
a7ec1775 2322;; If the user requests so, she can have a few more bindings:
b849548d
CD
2323(when reftex-extra-bindings
2324 (loop for x in
2325 '(("\C-ct" . reftex-toc)
2326 ("\C-cl" . reftex-label)
2327 ("\C-cr" . reftex-reference)
2328 ("\C-cc" . reftex-citation)
2329 ("\C-cv" . reftex-view-crossref)
2330 ("\C-cg" . reftex-grep-document)
2331 ("\C-cs" . reftex-search-document))
2332 do (define-key reftex-mode-map (car x) (cdr x))))
2333
b849548d
CD
2334;;; =========================================================================
2335;;;
2336;;; Menu
a7ec1775
RS
2337
2338;; Define a menu for the menu bar if Emacs is running under X
2339
2340(require 'easymenu)
2341
f9ad2e24 2342(easy-menu-define reftex-mode-menu reftex-mode-map
a7ec1775 2343 "Menu used in RefTeX mode"
396e0b08 2344 `("Ref"
206c6f82 2345 ["Table of Contents" reftex-toc t]
1c25ed90 2346 "--"
206c6f82
RS
2347 ["\\label" reftex-label t]
2348 ["\\ref" reftex-reference t]
2349 ["\\cite" reftex-citation t]
7c4d13cc
CD
2350 ("\\index"
2351 ["\\index" reftex-index t]
2352 ["\\index{THIS}" reftex-index-selection-or-word t]
2353 "--"
2354 ["Add THIS to Index Phrases" reftex-index-phrase-selection-or-word t]
2355 ["Visit Phrase Buffer" reftex-index-visit-phrases-buffer t]
2356 ["Apply Phrases to Region" reftex-index-phrases-apply-to-region t]
2357 "--"
2358 ["Display the Index" reftex-display-index t])
1c25ed90 2359 "--"
7c4d13cc 2360 ["View Crossref" reftex-view-crossref t]
1c25ed90 2361 "--"
396e0b08 2362 ("Parse Document"
1c25ed90
CD
2363 ["One File" reftex-parse-one reftex-enable-partial-scans]
2364 ["Entire Document" reftex-parse-all t]
baec1250 2365 ["Save to File" (reftex-access-parse-file 'write)
396e0b08 2366 (> (length (symbol-value reftex-docstruct-symbol)) 0)]
2faef409 2367 ["Restore from File" (reftex-access-parse-file 'restore) t]
1c25ed90 2368 "--"
396e0b08 2369 ["Reset RefTeX Mode" reftex-reset-mode t])
2faef409 2370 ("Global Actions"
baec1250
KH
2371 ["Search Whole Document" reftex-search-document t]
2372 ["Replace in Document" reftex-query-replace-document t]
2373 ["Grep on Document" reftex-grep-document t]
1c25ed90 2374 "--"
baec1250 2375 ["Find Duplicate Labels" reftex-find-duplicate-labels t]
2faef409 2376 ["Change Label and Refs" reftex-change-label t]
b849548d 2377 ["Renumber Simple Labels" reftex-renumber-simple-labels t]
1c25ed90 2378 "--"
1c25ed90
CD
2379 ["Create TAGS File" reftex-create-tags-file t]
2380 "--"
f9ad2e24 2381 ["Save Document" reftex-save-all-document-buffers t])
1c25ed90 2382 "--"
b849548d 2383 ("Options"
921759ee
CD
2384 "PARSER"
2385 ["Partial Scans"
2386 (setq reftex-enable-partial-scans (not reftex-enable-partial-scans))
2387 :style toggle :selected reftex-enable-partial-scans]
2388 ["Auto-Save Parse Info"
2389 (setq reftex-save-parse-info (not reftex-save-parse-info))
2390 :style toggle :selected reftex-save-parse-info]
1c25ed90 2391 "--"
921759ee
CD
2392 "CROSSREF INFO"
2393 ["Automatic Info" reftex-toggle-auto-view-crossref
2394 :style toggle :selected reftex-auto-view-crossref-timer]
2395 ["...in Echo Area" (setq reftex-auto-view-crossref t)
2396 :style radio :selected (eq reftex-auto-view-crossref t)]
2397 ["...in Other Window" (setq reftex-auto-view-crossref 'window)
2398 :style radio :selected (eq reftex-auto-view-crossref 'window)]
1c25ed90 2399 "--"
921759ee
CD
2400 "MISC"
2401 ["AUC TeX Interface" reftex-toggle-plug-into-AUCTeX
2402 :style toggle :selected reftex-plug-into-AUCTeX])
2403 ("Reference Style"
1c25ed90
CD
2404 ["Default" (setq reftex-vref-is-default nil
2405 reftex-fref-is-default nil)
2406 :style radio :selected (not (or reftex-vref-is-default
2407 reftex-fref-is-default))]
2408 ["Varioref" (setq reftex-vref-is-default t
2409 reftex-fref-is-default nil)
2410 :style radio :selected reftex-vref-is-default]
2411 ["Fancyref" (setq reftex-fref-is-default t
2412 reftex-vref-is-default nil)
2413 :style radio :selected reftex-fref-is-default])
921759ee
CD
2414 ("Citation Style"
2415 ,@(mapcar
1c25ed90
CD
2416 (lambda (x)
2417 (vector
2418 (capitalize (symbol-name (car x)))
2419 (list 'reftex-set-cite-format (list 'quote (car x)))
2420 :style 'radio :selected
2421 (list 'eq (list 'reftex-get-cite-format) (list 'quote (car x)))))
921759ee 2422 reftex-cite-format-builtin)
1c25ed90 2423 "--"
921759ee
CD
2424 "Sort Database Matches"
2425 ["Not" (setq reftex-sort-bibtex-matches nil)
2426 :style radio :selected (eq reftex-sort-bibtex-matches nil)]
2427 ["by Author" (setq reftex-sort-bibtex-matches 'author)
2428 :style radio :selected (eq reftex-sort-bibtex-matches 'author)]
2429 ["by Year" (setq reftex-sort-bibtex-matches 'year)
2430 :style radio :selected (eq reftex-sort-bibtex-matches 'year)]
2431 ["by Year, reversed" (setq reftex-sort-bibtex-matches 'reverse-year)
2432 :style radio :selected (eq reftex-sort-bibtex-matches 'reverse-year)])
1c25ed90
CD
2433 ("Index Style"
2434 ,@(mapcar
2435 (lambda (x)
2436 (vector
2437 (capitalize (symbol-name (car x)))
2438 (list 'reftex-add-index-macros (list 'list (list 'quote (car x))))
2439 :style 'radio :selected
2440 (list 'memq (list 'quote (car x))
2441 (list 'get 'reftex-docstruct-symbol
2442 (list 'quote 'reftex-index-macros-style)))))
2443 reftex-index-macros-builtin))
2444 "--"
2faef409 2445 ("Customize"
f9ad2e24 2446 ["Browse RefTeX Group" reftex-customize t]
1c25ed90 2447 "--"
2faef409
RS
2448 ["Build Full Customize Menu" reftex-create-customize-menu
2449 (fboundp 'customize-menu-create)])
2faef409
RS
2450 ("Documentation"
2451 ["Info" reftex-info t]
2452 ["Commentary" reftex-show-commentary t])))
a7ec1775 2453
b849548d
CD
2454(defun reftex-customize ()
2455 "Call the customize function with reftex as argument."
2456 (interactive)
2457 (customize-browse 'reftex))
2458
2459(defun reftex-create-customize-menu ()
2460 "Create a full customization menu for RefTeX, insert it into the menu."
2461 (interactive)
2462 (if (fboundp 'customize-menu-create)
2463 (progn
2464 (easy-menu-change
2465 '("Ref") "Customize"
2466 `(["Browse RefTeX group" reftex-customize t]
1c25ed90 2467 "--"
b849548d
CD
2468 ,(customize-menu-create 'reftex)
2469 ["Set" Custom-set t]
2470 ["Save" Custom-save t]
2471 ["Reset to Current" Custom-reset-current t]
2472 ["Reset to Saved" Custom-reset-saved t]
2473 ["Reset to Standard Settings" Custom-reset-standard t]))
2474 (message "\"Ref\"-menu now contains full customization menu"))
2475 (error "Cannot expand menu (outdated version of cus-edit.el)")))
2476
2477(defun reftex-show-commentary ()
2478 "Use the finder to view the file documentation from `reftex.el'."
2479 (interactive)
2480 (require 'finder)
2481 (finder-commentary "reftex.el"))
2482
7c4d13cc
CD
2483(defun reftex-info (&optional node)
2484 "Read documentation for RefTeX in the info system.
2485With optional NODE, go directly to that node."
b849548d
CD
2486 (interactive)
2487 (require 'info)
7c4d13cc 2488 (Info-goto-node (format "(reftex)%s" (or node ""))))
b849548d 2489
b849548d
CD
2490;;; Install the kill-buffer and kill-emacs hooks ------------------------------
2491
2492(add-hook 'kill-buffer-hook 'reftex-kill-buffer-hook)
2493(add-hook 'kill-emacs-hook 'reftex-kill-emacs-hook)
2494
a7ec1775
RS
2495;;; Run Hook ------------------------------------------------------------------
2496
2497(run-hooks 'reftex-load-hook)
2498
2499;;; That's it! ----------------------------------------------------------------
2500
6b94c6ad 2501(setq reftex-tables-dirty t) ; in case this file is evaluated by hand
396e0b08
KH
2502(provide 'reftex)
2503
a7ec1775
RS
2504;;;============================================================================
2505
c52bdfca 2506;;; reftex.el ends here
7c4d13cc 2507