1207bd65c363fac8484386dfb3dfe77bc799f8d1
[packages] / xemacs-packages / auctex / bib-cite.el
1 ;;; bib-cite.el --- test
2 ;; bib-cite.el - Display \cite, \ref or \label / Extract refs from BiBTeX file.
3
4 ;; Copyright (C) 1994-1999, 2001, 2003-2005, 2014
5 ;; Free Software Foundation, Inc.
6
7 ;; Author:    Peter S. Galbraith <psg@debian.org>
8 ;; Created:   06 July 1994
9 ;; Version:   3.28  (Feb 23 2005)
10 ;; Keywords:  bibtex, cite, auctex, emacs, xemacs
11
12 ;;; This file is not part of GNU Emacs.
13
14 ;; This package is free software; you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation; either version 3, or (at your option)
17 ;; any later version.
18
19 ;; This package is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
26 ;; Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
27 ;; Boston, MA 02110-1301, USA.
28
29 ;; LCD Archive Entry:
30 ;; bib-cite|Peter Galbraith|GalbraithP@dfo-mpo.gc.ca|
31 ;; Display \cite, \ref or \label / Extract refs from BiBTeX file.|
32 ;; 21-May-1997|3.01|~/misc/bib-cite.el.gz|
33
34 ;; ----------------------------------------------------------------------------
35 ;;; Commentary:
36 ;; This minor-mode is used in various TeX modes to display or edit references
37 ;; associated with \cite commands, or matching \ref and \label commands.
38
39 ;; New versions of this package (if they exist) may be found at:
40 ;;   http://people.debian.org/~psg/elisp/bib-cite.el
41 ;; and in AUCTeX's Git archive at
42 ;;   http://git.savannah.gnu.org/cgit/auctex.git
43
44 ;; Operating Systems:
45 ;;  Works in unix, DOS and OS/2.  Developped under Linux.
46
47 ;; AUCTeX users:
48 ;;  AUCTeX is a super-charged LaTeX mode for emacs. Get it at:
49 ;;
50 ;;    ftp://ftp.gnu.org/pub/gnu/auctex/
51 ;;
52 ;;  WWW users may want to check out the AUCTeX page at
53 ;;    http://www.gnu.org/software/auctex/
54 ;;
55 ;;  bib-cite.el is included in the AUCTeX distribution.  Therefore, if
56 ;;  you use AUCTeX and didn't obtained bib-cite.el separately, make sure
57 ;;  that you are actually using the more recent version.
58
59 ;; RefTeX users:
60 ;;  RefTeX is a package with similar functions to bib-cite.
61 ;;    http://www.astro.uva.nl/~dominik/Tools/reftex/
62 ;;  RefTeX is bundled and preinstalled with Emacs since version 20.2.
63 ;;  It was also bundled with XEmacs 19.16--20.x.
64 ;;
65 ;;  I suggest that you use RefTeX to help you type-in text as it's functions
66 ;;  are better suited to this task than bib-cite, and use bib-cite's features
67 ;;  when you proof-read the text.
68 ;;  If you wish bib-cite to use RefTeX's reftex-view-crossref command to
69 ;;  display and find \label's and \cite bibliography entries, set the variable
70 ;;  bib-cite-use-reftex-view-crossref to t.
71
72 ;; MS-DOS users:
73 ;;  Multifile documents are supported by bib-cite by using etags (TAGS files)
74 ;;  which contains a bug for MSDOS (at least for emacs 19.27 it does).
75 ;;  Get the file
76 ;;    http://people.debian.org/~psg/elisp/bib-cite.etags-bug-report
77 ;;  to see what patches to make to etags.c to fix it.
78
79 ;; Description:
80 ;; ~~~~~~~~~~~
81 ;; This package is used in various TeX modes to display or edit references
82 ;; associated with \cite commands, or matching \eqref, \ref and \label
83 ;; commands  (so I actually overstep BiBTeX bounds here...).
84 ;;
85 ;; These are the functions:
86 ;;
87 ;;    bib-display bib-display-mouse
88 ;;                           - Display citation, \ref or \label under point
89 ;;    bib-find    bib-find-mouse
90 ;;                           - Edit citation, \ref or \label under point
91 ;;    bib-find-next          - Find next occurrence of a \ref or \eqref
92 ;;    bib-make-bibliography  - Make BiBTeX file containing only cite keys used.
93 ;;    bib-apropos            - Search BiBTeX source files for keywords.
94 ;;    bib-etags              - Refreshes (or builds) the TAGS files for
95 ;;                             multi-file documents.
96 ;;    bib-create-auto-file   - Used in bibtex-mode to create cite key
97 ;;                             completion .el file for AUCTeX.
98 ;;    bib-highlight-mouse    - Highlight \cite, \ref and \label commands in
99 ;;                             green when the mouse is over them.
100
101 ;; About Cite Commands and related functions:
102 ;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
103 ;;  Various flavors of \cite commands are allowed (as long as they contain
104 ;;  the word `cite') and they may optionally have bracketed [] options.
105 ;;  Bibtex Cross-references are displayed, and @string abbreviations are
106 ;;  substituted or included.
107 ;;
108 ;;  The \cite text is found (by emacs) in the bibtex source files listed in the
109 ;;  \bibliography command.  The BiBTeX files can be located in a search path
110 ;;  defined by an environment variable (typically BIBINPUTS, but you can change
111 ;;  this).
112 ;;
113 ;;  All citations used in a buffer can also be listed in a new bibtex buffer by
114 ;;  using bib-make-bibliography.  This is useful to make a bibtex file for a
115 ;;  document from a large bibtex database.  In this case, cross-references are
116 ;;  included, as well as the @string commands used. The @string abbreviations
117 ;;  are not substituted.
118 ;;
119 ;;  The bibtex files can also be searched for entries matching a regular
120 ;;  expression using bib-apropos.
121
122 ;; Usage instructions:
123 ;; ~~~~~~~~~~~~~~~~~~
124 ;;  bib-display   Bound to Mouse-3 when specially highlighted.
125 ;;                In Hyperbole, bound to the Assist key.
126 ;;                Bound to `\C-c b d'
127 ;;
128 ;;   bib-display will show the bibtex entry or the corresponding label or
129 ;;   ref commands from anywhere within a document.
130 ;;    With cursor on the \cite command itslef
131 ;;        -> display all citations of the cite command from the BiBTeX source.
132 ;;    With cursor on a particular cite key within the brackets
133 ;;        -> display that citation's text from the BiBTeX source file(s).
134 ;;
135 ;;       Example:
136 ;;
137 ;;       \cite{Wadhams81,Bourke.et.al87,SchneiderBudeus94}
138 ;;         ^Cursor -> Display-all-citations    ^Cursor -> Display-this-citation
139 ;;
140 ;;    With cursor on a \label command
141 ;;        -> Display first matching \ref command in the document
142 ;;    With cursor on a \ref command
143 ;;        -> Display environment associated with the matching \label command.
144 ;;
145 ;;   Finding a ref or label within a multi-file document requires a TAGS file,
146 ;;   which is automatically generated for you.  This enables you to then use
147 ;;   any tags related emacs features.
148 ;;
149 ;;  bib-find      Bound to Mouse-2 when specially highlighted.
150 ;;                In Hyperbole, bound to the Action key.
151 ;;                Bound to `\C-c b f'
152 ;;
153 ;;    bib-find will select the buffer and move point to the BiBTeX source file
154 ;;    at the proper citation for a cite command, or move point to anywhere
155 ;;    within a document for a label or ref command.  The ref chosen is the
156 ;;    first occurrance within a document (using a TAGS file).  If point is
157 ;;    moved within the same buffer, mark is set before the move and a message
158 ;;    stating so is given.  If point is moved to another file, this is done in
159 ;;    a new window using tag functions.
160 ;;
161 ;;    The next occurrence of a \ref or \eqref command may be found by invoking
162 ;;    bib-find-next, usually bound to `C-c b n'.
163 ;;
164 ;;    For multi-file documents, you must be using AUCTeX (so that bib-cite can
165 ;;    find the master file) and all \input and \include commands must be first
166 ;;    on a line (not preceeded by any non-white text).
167 ;;
168 ;;  bib-make-bibliography:     Bound to `\C-c b m'
169 ;;
170 ;;   Extract citations used in the current document from the \bibliography{}
171 ;;   file(s).  Put them into a new suitably-named buffer.  In a AUCTeX
172 ;;   multi-file document, the .aux files are used to find the cite keys (for
173 ;;   speed).  You will be warned if these are out of date.
174 ;;
175 ;;   This buffer is not saved to a file.  It is your job to save it to whatever
176 ;;   name you wish.  Note that AUCTeX has a unique name space for LaTeX and
177 ;;   BiBTeX files, so you should *not* name the bib file associated with
178 ;;   example.tex as example.bib!  Rather, name it something like
179 ;;   example-bib.bib.
180 ;;
181 ;;  bib-apropos:               Bound to `\C-c b a'
182 ;;
183 ;;   Searches the \bibliography{} file(s) for entries containing a keyword and
184 ;;   display them in the *help* buffer.  You can trim down your search by using
185 ;;   bib-apropos in the *Help* buffer after the first invocation.  the current
186 ;;   buffer is also searched for keyword matches if it is in bibtex-mode.
187 ;;
188 ;;   It doesn't display cross-references nor does it substitute or display
189 ;;   @string commands used.  It could easily be added, but it's faster this
190 ;;   way.  Drop me a line if this would be a useful addition.
191 ;;
192 ;;   If you find yourself entering a cite command and have forgotten which key
193 ;;   you want, but have entered a few initial characters as in `\cite{Gal',
194 ;;   then invoke bib-apropos.  It will take that string (in this case `Gal') as
195 ;;   an initial response to the apropos prompt.  You are free to edit it, or
196 ;;   simply press carriage return.
197 ;;
198 ;;  bib-etags:                 Bound to `\C-c b e'
199 ;;
200 ;;   Creates a TAGS file for AUCTeX's multi-file document (or refreshes it).
201 ;;   This is used by bib-find when editing multi-file documents.  The TAGS file
202 ;;   is created automatically, but it isn't refreshed automatically.  So if
203 ;;   bib-find can't find something, try running bib-etags again.
204 ;;
205 ;;  bib-create-auto-file:
206 ;;
207 ;;   Use this when editing a BiBTeX buffer to generate the AUCTeX .el file
208 ;;   which tell emacs about all its cite keys.  I've added this command to
209 ;;   bibtex-mode pull-down menu.
210 ;;
211 ;;  bib-highlight-mouse:       Bound to `\C-c b h'
212 ;;
213 ;;   Highlights \cite, \ref and \label commands in green when the mouse is over
214 ;;   them.  By default, a call to this function is added to LaTeX-mode-hook
215 ;;   (via bib-cite-initialize) if you set bib-highlight-mouse-t to true.  But
216 ;;   you may want to run this command to refresh the highlighting for newly
217 ;;   edited text.
218
219 ;; Installation instructions:
220 ;; ~~~~~~~~~~~~~~~~~~~~~~~~~
221 ;;  bib-cite is a minor-mode, so you could invoke it in a LaTeX-mode hook.
222 ;;  e.g. If you are using AUCTeX (http://www.gnu.org/software/auctex/), you
223 ;;  could use:
224 ;;
225 ;;   (autoload 'turn-on-bib-cite "bib-cite")
226 ;;   (add-hook 'LaTeX-mode-hook 'turn-on-bib-cite)
227 ;;
228 ;;  If you are using Emacs' regular LaTeX-mode, use instead:
229 ;;
230 ;;   (autoload 'turn-on-bib-cite "bib-cite")
231 ;;   (add-hook 'latex-mode-hook 'turn-on-bib-cite)
232 ;;
233 ;;  bib-cite can be used with AUCTeX, or stand-alone.  If used with AUCTeX on a
234 ;;  multi-file document (and AUCTeX's parsing is used), then all \bibliography
235 ;;  commands in the document will be found and used.
236 ;;  ---
237 ;;  The following variable can be unset (like shown) to tell bib-cite to
238 ;;  not give advice messages about which commands to use to find the next
239 ;;  occurrence of a search:
240 ;;
241 ;;    (setq bib-novice nil)
242 ;;  ---
243 ;;  If you wish bib-cite to use RefTeX's reftex-view-crossref command to
244 ;;  display and find \label's and \cite bibliography entries, set the variable
245 ;;  bib-cite-use-reftex-view-crossref to t:
246 ;;
247 ;;    (setq bib-cite-use-reftex-view-crossref t)
248 ;;  ---
249 ;;  The following variable determines whether we will attempt to highlight
250 ;;  citation, ref and label commands in green when they are under the
251 ;;  mouse.  When highlighted, the mouse keys work to call bib-display
252 ;;  (bound to [mouse-3]) and bib-find (bound to [mouse-2]).  If you use a
253 ;;  mode other than LaTeX-mode, you'll want to call bib-highlight-mouse with
254 ;;  a hook (See how we do this at the end of this file with the add-hook
255 ;;  command).
256 ;;
257 ;;    (setq bib-highlight-mouse-t nil)
258 ;;  ---
259 ;;  The variable bib-switch-to-buffer-function sets the function used to
260 ;;  select buffers (if they differ from the original) in bib-cite commands
261 ;;  bib-make-bibliography, bib-display, bib-find
262 ;;  You may use `switch-to-buffer' `switch-to-buffer-other-window' or
263 ;;  `switch-to-buffer-other-frame'.
264 ;;  ---
265 ;;  If you use DOS or OS/2, you may have to set the following variable:
266 ;;
267 ;;    (setq bib-dos-or-os2-variable t)
268 ;;
269 ;;    if bib-cite.el fails to determine that you are using DOS or OS/2.
270 ;;  Try `C-h v bib-dos-or-os2-variable' to see if it needs to be set manually.
271 ;;  ---
272 ;;  bib-cite needs to call the etags program with its output file option
273 ;;  and also with the append option (usually -a).
274 ;;  I figured that DOS and OS/2 would use "etags /o=" instead of the unix
275 ;;  variant "etags -o ", but users have reported differently.  So while the
276 ;;  unix notation is used here, you can reset it if you need to like so:
277 ;;
278 ;;    (setq bib-etags-command  "etags  /r='/.*\\\(eq\|page\|[fvF]\)ref.*/' /o=")
279 ;;    (setq bib-etags-append-command
280 ;;                             "etags  /r='/.*\\\(eq\|page\|[fvF]\)ref.*/' /a /o=")
281 ;;  ---
282 ;;  For multi-file documents, a TAGS file is generated by etags.
283 ;;  By default, its name is TAGS.  You can change this like so:
284 ;;
285 ;;    (setq bib-etags-filename "TAGSLaTeX")
286 ;;  ---
287 ;;  If your environment variable to find BiBTeX files is not BIBINPUTS, then
288 ;;  reset it with the following variable (here, assuming it's TEXBIB instead):
289 ;;
290 ;;    (setq bib-bibtex-env-variable "TEXBIB")
291 ;;
292 ;;  Note that any directory ending in a double slash will cause bib-cite to
293 ;;  search recursively through subdirectories for your .bib files.  This can
294 ;;  be slow, so use this judiciously.
295 ;;  e.g.  setenv BIBINPUTS .:/home/psg/LaTeX/bibinputs//
296 ;;        -> all directories below /home/psg/LaTeX/bibinputs/ will be
297 ;;           searched.
298 ;;
299 ;;  If your bibtex setup works but Emacs can't see the environment variable
300 ;;  correctly (Check `C-h v process-environment'), then customize the
301 ;;  variable `bib-cite-inputs'  (e.g. `M-x customize-variable bib-cite-imputs')
302 ;;
303 ;;  ---
304 ;;  If you do not wish bib-display to substitute @string abbreviations,
305 ;;  then set the following variable like so:
306 ;;
307 ;;    (setq bib-substitute-string-in-display nil)
308 ;;  ---
309 ;;  Warnings are given when @string abbreviations are not defined in your bib
310 ;;  files.  The exception is for months, usually defined in style files. If you
311 ;;  use other definitions in styles file (e.g. journals), then you may add them
312 ;;  to the `bib-substitute-string-in-display' list variable.
313
314 ;; If you find circumstances in which this package fails, please let me know.
315
316 ;; Things for me to do in later versions:
317 ;; - treat @Strings correctly, not just in isolation.
318 ;; - use  `kpsewhich -expand-path='$BIBINPUTS'`  instead of BIBINPUTS.
319 ;; - jmv@di.uminho.pt (Jose Manuel Valenca) wants:
320 ;;   - prompt for \cite as well as \label and \ref
321 ;;     (and use AUCTeX's completion list)
322 ;;   - implement string concatenation, with #[ \t\n]*STRING_NAME
323 ;;   - Create new command to substitute @string text in any bibtex buffer.
324 ;; ----------------------------------------------------------------------------
325 ;;; Change log:
326 ;; V3.28 Feb 23 2005 - Ralf Angeli
327 ;;  - Some doc fixes in the commentary section.
328 ;; V3.27 Feb 09 2005 - PSG
329 ;;  - Patch from Peter Heslin.  TeX-master can now have symbol values.
330 ;; V3.26 Aug 06 2004 - Reiner Steib
331 ;;  - Changed URL of AUCTeX. Use "AUCTeX", not "auc-tex" (skipped Change log).
332 ;; V3.25 Feb 15 2004 - PSG
333 ;;  - Check existence of font-lock-unset-defaults; no longer defined in CVS
334 ;;    Emacs. Thanks to Adrian Lanz for reporting the problem.
335 ;; V3.24 Oct 28 2003 - PSG
336 ;;  - bib-cite-file-directory-p: new function to replace ff-paths code.
337 ;; V3.23 Oct 09 2003 - PSG
338 ;;  - some checkdoc cleanup; not yet complete.
339 ;; V3.22 Sep 17 2003 - PSG
340 ;;  - bib-cite-aux-inputs:  new defcustom.
341 ;;  - minor cleanup for `match-string'.
342 ;; V3.21 Sep 08 2003 - PSG
343 ;;  - Ripping out off-topic imenu code.
344 ;; V3.20 Aug 14 2003 - PSG
345 ;;  - psg-checkfor-file-list: Allow for relative directoties as entries in
346 ;;    BIBINPUTS.
347 ;;  - bib-cite-inputs:  new defcustom equivalent to BIBINPUTS.
348 ;;  - bib-label-help-echo-format: fixed defcustom.
349 ;;  - psg-list-env: code cleanup.
350 ;;  - trailing whitespace cleanup.
351 ;; V3.19 Apr 06 2003 - PSG
352 ;;    Remove code that ran when defcustom not present.
353 ;;    Remove hilit19 obsolete code.
354 ;; V3.18 Mar 27 2003 - Bruce Ravel <ravel@phys.washington.edu>
355 ;;    Play well with the varioref and fancyref latex styles (vref, fref, Fref).
356 ;; V3.17 May 01 2001 - (RCS V1.38)
357 ;;  - XEmacs has imenu after all.
358 ;; V3.16 Dec 20 99 - (RCS V1.37)
359 ;;  - Added customize support.
360 ;; V3.15 Dec 20 99 - (RCS V1.36)
361 ;;  - Removed stupid debugging code that I had left in.
362 ;; V3.14 Dec 20 99 -
363 ;;  - New variable bib-ref-regexp for \ref regexp to match \label constructs
364 ;;    and added \pageref. (RCS V1.34)
365 ;;  - Edited bib-etags-command snd bib-etags-append-command to match.
366 ;; V3.13 Dec 20 99 - (RCS V1.32)
367 ;;  - License changed to GPL.
368 ;;  - Kai Engelhardt <ke@socs.uts.edu.au> bib-master-file takes .ltx extension
369 ;;  - imenu--create-LaTeX-index-for-document and bib-document-TeX-files
370 ;;    edited to accept .ltx extension.
371 ;;  - Michael Steiner <steiner@cs.uni-sb.de> added journals to @string
372 ;;    abbrevs and contributed `member-cis' to complaces @strings in a
373 ;;    case-insensitive manner.
374 ;; V3.12 Dec 10 98 - Bruce Ravel <bruce.ravel@nist.gov> (RCS V1.30)
375 ;;    Fixed bib-label-help.
376 ;; V3.11 Oct 06 98 - PSG (RCS V1.29)
377 ;;    Quote \ character fot replace-match;
378 ;;    Applies to: @String{JGR = "J. Geophys.\ Res."}
379 ;; V3.10 Sep 21 98 - Matt Hodges <mph1002@cam.ac.uk> (RCS V1.28)
380 ;;    Removed instance of expand-file-name due to new behaviour in Emacs-20.3.
381 ;; V3.09 Sep 09 98 - PSG (RCS V1.27)
382 ;;    Added support for \eqref; Added bib-find-next.
383 ;; V3.08 Aug 20 98 - PSG (RCS V1.26)
384 ;;    Fixed imenu bug (prev-pos (point-max))
385 ;; V3.07 Nov 20 97 - Christoph Wedler <wedler@fmi.uni-passau.de>  (RCS V1.24)
386 ;;    bib-ext-list variable made permanent-local, otherwise VC registration
387 ;;    would use two extents for each reference etc. This was not a visible bug.
388 ;; V3.06 Nov 12 97 - PSG (RCS V1.23)
389 ;;    Support use of reftex's reftex-view-crossref command.
390 ;; V3.05 Nov 12 97 - Vladimir Alexiev <vladimir@cs.ualberta.ca> (RCS V1.22)
391 ;;    regexp-quote the bibliography keys so a key like galbraith+kelley97 works
392 ;; V3.04 Aug 25 97 - Christoph Wedler  <wedler@fmi.uni-passau.de> (RCS V1.20)
393 ;;    (bib-highlight-mouse): Would bug out on detached extents,
394 ;;    e.g. when killing a whole citation.
395 ;; V3.03 Jul 16 97 - Christoph Wedler  <wedler@fmi.uni-passau.de> (RCS V1.18)
396 ;;    turn-on-bib-cite back to non-interactive.
397 ;; V3.02 Jul 11 97 - Christoph Wedler  <wedler@fmi.uni-passau.de> (RCS V1.17)
398 ;;    * auctex/bib-cite.el (turn-on-bib-cite): Make interactive.
399 ;;    Argument to `bib-cite-minor-mode' is 1.
400 ;;    (bib-label-help-echo-format): New variable.
401 ;;    (bib-label-help-echo): New function.
402 ;;    (bib-label-help): Addition argument format.
403 ;;    (bib-highlight-mouse): Set extent property `help-echo' for XEmacs.
404 ;; V3.01 May 22 97 - Diego Calvanese <calvanes@dis.uniroma1.it> (RCS V1.16)
405 ;;    bib-make-bibliography handles commas separated citations in aux files.
406 ;; V3.00 May 16 97 - Peter Galbraith (RCS V1.15)
407 ;;    bib-cite is now a minor mode.
408 ;; V2.32 Apr 30 97 - Anders Stenman <stenman@isy.liu.se> (RCS V1.14)
409 ;;  - Support for balloon-help.
410 ;; V2.31 Mar 20 97 - Christoph Wedler <wedler@fmi.uni-passau.de> (RCS V1.12)
411 ;;  - Better fontification of help buffer as bibtex or latex for XEmacs.
412 ;; V2.30 Feb 10 97 - Peter Galbraith (RCS V1.11)
413 ;;  - Better fontification of help buffer as bibtex or latex.
414 ;; V2.29 Jan 29 97 - Peter Galbraith (RCS V1.10)
415 ;;  - imenu looks for `\label{stuff}' instead of `\label'
416 ;; V2.28 Jan 22 97 - Peter Galbraith (RCS V1.9)
417 ;;  - Bug in bib-create-auto-file.
418 ;; V2.27 Dec 31 96 - Peter Galbraith (RCS V1.8)
419 ;;  - allow spaces between cite keys.
420 ;;  - Vladimir Alexiev <vladimir@cs.ualberta.ca>
421 ;;     Allow () delimiters as well as {}.
422 ;;     Better check on bibtex-menu
423 ;;     Erase *bibtex-bibliography* buffer.
424 ;; V2.26 Sep 24 96 - Peter Galbraith (RCS V1.7)
425 ;;  imenu bug fix.
426 ;; V2.25 Sep 23 96 - Anders Stenman <stenman@isy.liu.se> (RCS V1.6)
427 ;;  XEmacs bib-cite-fontify-help-as-latex bug fix.
428 ;; V2.24 Aug 19 96 - Peter Galbraith (RCS V1.3)
429 ;;  XEmacs bug fix, minor defvars - Vladimir Alexiev <vladimir@cs.ualberta.ca>
430 ;; V2.23 Aug 13 96 - Peter Galbraith (RCS V1.2)
431 ;;   XEmacs - Add bib-cite entries to bibtex-mode popup menu.
432 ;; V2.22 July 22 96 - Peter Galbraith (RCS V1.1)
433 ;;   local-map has `m' for bib-make-bibliography instead of `b'
434 ;;   set-buffer-menubar in XEmacs so that menu disappears after use.
435 ;; V2.21 July 12 96 - Peter Galbraith
436 ;;   Define `\C-c b' keymap for both plain tex and auctex, in XEmacs and emacs.
437 ;;   Separate menu-bar menu in gnu emacs.
438 ;;   font-lock support for bib-display'ed citations (bibtex fontification)
439 ;;    and for matching \ref{} and \labels (latex fontification).
440 ;;   buffer-substring-no-properties in bib-apropos
441 ;;    (bug in completing-read with mouse faces)
442 ;;   imenu-sort-function made local and nil.
443 ;;   imenu--LaTeX-name-and-position fixed for section name containing "\"
444 ;;   Various other things... (whitespace within label strings, etc...)
445 ;; V2.20 June 25 96 - Peter Galbraith
446 ;;   imenu fixed for emacs-19.31.
447 ;; V2.19 May 13 96
448 ;;  PSG:
449 ;;  - @string substitution fixed; bib-edit-citation fixed when buffer exists;
450 ;;  Christoph Wedler <wedler@fmi.uni-passau.de>:
451 ;;  - Added bib-switch-to-buffer-function
452 ;;  - (setq tags-always-exact nil) for xemacs
453 ;;  - removed eval-after-load foe xemacs
454 ;; V2.18 May 06 96 - PSG
455 ;;   New eval-after-load from Fred Devernay <Frederic.Devernay@sophia.inria.fr>
456 ;; V2.17 May 03 96 - PSG
457 ;;   Fixed bug introduced in V2.16, reported by Dennis Dams <wsindd@win.tue.nl>
458 ;; V2.16 May 02 96 - Vladimir Alexiev <vladimir@cs.ualberta.ca>
459 ;; - somewhat compatible with Hyperbole by binding bib-find and bib-display to
460 ;;   the Action and Assist keys inside the bib-highlight-mouse-keymap.
461 ;; - makes more liberal provisions for users with a tty.
462 ;; V2.15 Apr 09 96 -
463 ;; - fix "Buffer read-only" error caused by mouse-face text properties
464 ;;   patch by Piet van Oostrum <piet@cs.ruu.nl>
465 ;; - Use tmm non-X menu, patch by Vladimir Alexiev <vladimir@cs.ualberta.ca>
466 ;; - input{file.txt} would not work.
467 ;;   bug report: David Kastrup <dak@pool.informatik.rwth-aachen.de>
468 ;; V2.14 Feb 26 96 - PSG - define eval-after-load for xemacs
469 ;; Frederic Devernay's <Frederic.Devernay@sophia.inria.fr> suggestion.
470 ;; V2.13 Feb 08 96 - Peter Galbraith - Fixed recursive use of bib-apropos.
471 ;; V2.12 Jan 19 96 - Peter Galbraith
472 ;;   emacs-19.30's [down-mouse-1] is defined (rather than [mouse-1]), so
473 ;;   bib-highlight-mouse-keymap now has [down-mouse-1] defined to override it.
474 ;; V2.11  Nov 21 95 - Peter Galbraith
475 ;; - Fixed bib-create-auto-file when bib file loaded before LaTeX file.
476 ;; - Michal Mnuk's better imenu labels menu <Michal.Mnuk@risc.uni-linz.ac.at>
477 ;; - [mouse-1] and [mouse-2] key defs for highlighted regions.
478 ;; - Improve X menus.
479 ;; - Skip over style files in bib-document-TeX-files.
480 ;; - Add menus and mouse highlighting for xemacs
481 ;;   Anders Stenman <stenman@isy.liu.se> Dima Barsky <D.Barsky@ee.surrey.ac.uk>
482 ;; - Check bib-use-imenu before calling LaTeX-hook-setq-imenu.
483 ;;   From: Kurt Hornik <hornik@ci.tuwien.ac.at>
484 ;; - Remove mouse face properties before inserting new ones.
485 ;;   From: Peter Whaite <peta@Whippet.McRCIM.McGill.EDU>
486 ;; V2.10  Aug 17 95 - Peter Galbraith - fatal bugs in bib-make-bibliography.
487 ;; V2.09  Jul 19 95 - Peter Galbraith
488 ;;   - Had introduced bug in search-directory-tree. synced with ff-paths.el.
489 ;; V2.08  Jul 13 95 - Peter Galbraith
490 ;;     Fred Douglis <douglis@research.att.com> says etags should be required
491 ;; V2.07  Jul 04 95 - Peter Galbraith
492 ;;   - Minor changes with filename manipulations (careful with DOS...)
493 ;;   - Problem if auc-tex not already loaded -> LaTeX-mode-map
494 ;; V2.06  Jul 03 95 - Peter Galbraith - Added recursion through BIBINPUTS path.
495 ;; V2.05  Jun 22 95 - Peter Galbraith  Bug: Hanno Wirth <wirth@jake.igd.fhg.de>
496 ;;   bib-get-citations would truncate @String{KEY ="J. {\"u} Res."}
497 ;; V2.04  Jun 19 95 - Peter Galbraith -
498 ;;   - use bibtex-mode syntax table in bib buffer, else bib-apropos truncates
499 ;;     an article if it contains an unbalanced closing parenthesis.
500 ;;   - bib-highlight-mouse would mark a buffer modified
501 ;; V2.03  May 16 95 - Peter Galbraith -
502 ;;   auc-tec menu compatible with old "AUC TeX" pull-down name
503 ;; V2.02  May 10 95 - Peter Galbraith -
504 ;;   bug report by Bodo Huckestein <bh@thp.Uni-Koeln.DE> (getenv env) under DOS
505 ;; V2.01  Mar 27 95 - Peter Galbraith - No imenu on xemacs; check BIBINPUT also
506 ;; V2.00  Mar 27 95 - Peter Galbraith
507 ;;   - bib-find and bib-display replace bib-edit-citation and
508 ;;      bib-display-citation
509 ;;   - bib-apropos now take initial guess from start of cite argument at point.
510 ;;   - Multi-file support for bib-make-bibliography using .aux files.
511 ;;   - \label and \ref functionality for bib-find and bib-display:
512 ;;     - \label may appear within an \begin\end or to label a (sub-)section.
513 ;;     - Cursor on \label, goto first \ref, set next i-search to pattern.
514 ;;     - Cursor on \ref, goto \label or display it's environment or section.
515 ;;     - Works on hidden code!
516 ;; V1.08  Jan 16 95 - Peter Galbraith
517 ;;     bib-apropos can be used within *Help* buffer to trim a search.
518 ;; V1.07  Dec 13 94 - Peter Galbraith
519 ;;   - Fixed: multi-line @string commands in non-inserted display.
520 ;;   - Fixed: quoted \ character in @string commands.
521 ;;   - BiBTeX comments should not affect bib-cite
522 ;;   - Fixed bib-apropos (from Christoph Wedler <wedler@fmi.uni-passau.de>)
523 ;;      Faster now, and avoids infinite loops.
524 ;;   - Added bib-edit-citation to edit a bibtex files about current citation.
525 ;;   - Allow space and newlines between citations: \cite{ entry1, entry2}
526 ;;   - Added bib-substitute-string-in-display,  bib-string-ignored-warning
527 ;;     and bib-string-regexp.
528 ;;   - bib-display-citation (from Markus Stricker <stricki@vision.ee.ethz.ch>)
529 ;;      Could not find entry with trailing spaces
530 ;; V1.06  Nov 20 94 - Peter Galbraith
531 ;;   - Fixed bib-apropos for:
532 ;;        hilighting without invoking bibtex mode.
533 ;;        display message when no matches found.
534 ;;        would search only last bib file listed (forgot to `goto-char 1')
535 ;;   - Fixed bib-make-bibliography that would only see first citation in a
536 ;;     multi-key \cite command (found by Michail Rozman <roz@physik.uni-ulm.de>
537 ;;   - bib-make-bibliography didn't see \cite[A-Z]* commands.
538 ;;     Found by Richard Stanton <stanton@haas.berkeley.edu>
539 ;;     **************************************************
540 ;;   - * Completely rewritten code to support crossrefs *
541 ;;     **************************************************
542 ;;   - autodetection of OS/2 and DOS for bib-dos-or-os2-variable
543 ;;   - Created bib-display-citation-mouse
544 ;;   - bib-apropos works in bibtex-mode on the current buffer
545 ;;   - bibtex entry may have comma on next line (!)
546 ;;       @ARTICLE{Kiryati-91
547 ;;         , YEAR          = {1991    }
548 ;;         ...
549 ;; V1.05  Nov 02 94 - Peter Galbraith
550 ;;   - bug fix by rossmann@TI.Uni-Trier.DE (Jan Rossmann)
551 ;;     for (boundp 'TeX-check-path) instead of fboundp.  Thanks!
552 ;;   - Translate environment variable set by bib-bibtex-env-variable.
553 ;;     (suggested by Richard Stanton <stanton@haas.berkeley.edu>)
554 ;;   - add bib-dos-or-os2-variable to set environment variable path separator
555 ;;   - Add key-defs for any tex-mode and auc-tex menu-bar entries.
556 ;;       [in auc-tec TeX-mode-map is common to both TeX and LaTeX at startup
557 ;;        (but TeX-mode-map is only copied to LaTeX-mode-map at initilisation)
558 ;;        in plain emacs, use tex-mode-map for both TeX and LaTeX.]
559 ;;   - Add key def for bibtex-mode to create auc-tex's parsing file.
560 ;;   - Fix bugs found by <thompson@loon.econ.wisc.edu>
561 ;;     - fix bib-get-citation for options
562 ;;     - fix bib-get-citation for commas preceeded citation command
563 ;;     - better regexp for citations and their keys.
564 ;;     - Added @string support for any entry (not just journal entries).
565 ;;       (I had to disallow numbers in @string keys because of years.
566 ;;        Is that ok?)
567 ;;   - added bib-apropos
568 ;; V1.04  Oct 24 94 - Peter Galbraith
569 ;;   - Don't require dired-aux, rather define the function we need from it.
570 ;;   - Regexp-quote the re-search for keys.
571 ;;   - Name the bib-make-bibliography buffer diffently than LaTeX buffer
572 ;;     because auc-tex's parsing gets confused if same name base is used.
573 ;; V1.03  Oct 24 94 - Peter Galbraith - require dired-aux for dired-split
574 ;; V1.02  Oct 19 94 - Peter Galbraith
575 ;;   - If using auc-tex with parsing activated, use auc-tex's functions
576 ;;     to find all \bibliography files in a multi-file document.
577 ;;   - Find bib files in pwd, BIBINPUTS environment variable path and
578 ;;     TeX-check-path elisp variable path.
579 ;;   - Have the parser ignore \bibliography that is on a commented `%' line.
580 ;;     (patched by Karl Eichwalder <karl@pertron.central.de>)
581 ;;   - Allow for spaces between entry type and key in bib files:
582 ;;     (e.g  @Article{  key} )
583 ;;     (suggested by Nathan E. Doss <doss@ERC.MsState.Edu>)
584 ;;   - Allows options in \cite command (e.g. agu++ package \cite[e.g.][]{key})
585 ;;   - Includes @String{} abbreviations for `journal' entries
586 ;; V1.01 July 07 94 - Peter Galbraith - \bibliography command may have list of
587 ;;                                      BibTeX files.  All must be readable.
588 ;; V1.00 July 06 94 - Peter Galbraith - Created
589 ;; ----------------------------------------------------------------------------
590 ;;; Code:
591
592 (eval-when-compile (require 'cl))
593
594 (defgroup bib-cite nil
595   "bib-cite, LaTeX minor-mode to display \\cite, \\ref and \\label commands."
596   :group 'tex)
597
598 (defcustom bib-cite-use-reftex-view-crossref nil
599   "*Non-nil means, RefTeX will be used to find cross references.
600 When this variable is non-nil, both `bib-find' and `bib-display' will
601 call a function in RefTeX to find or display the cross reference of a
602 \\ref or \\cite macro at point."
603   :group 'bib-cite
604   :type 'boolean)
605
606 (defcustom bib-novice t
607   "*Give advice to novice users about what commands to use next."
608   :group 'bib-cite
609   :type 'boolean)
610
611 (defcustom bib-switch-to-buffer-function 'switch-to-buffer
612   "*Function used to select buffers if they differ from the original.
613 You may use `switch-to-buffer' `switch-to-buffer-other-window' or
614 `switch-to-buffer-other-frame'."
615   :group 'bib-cite
616   :type '(choice (function-item switch-to-buffer)
617                  (function-item switch-to-buffer-other-window)
618                  (function-item switch-to-buffer-other-frame)))
619
620 (defcustom bib-highlight-mouse-t t
621   "*Call bib-highlight-mouse from `LaTeX-mode-hook' to add green highlight."
622   :group 'bib-cite
623   :type 'boolean)
624
625 (defcustom bib-label-help-echo-format "button2 finds %s, button3 displays %s"
626   "*Format string for info if the mouse is over LaTeX commands.
627 If nil, do not display info."
628   :group 'bib-cite
629   :type '(radio (const :tag "Don't display info" nil)
630                  string))
631
632 (defcustom bib-bibtex-env-variable "BIBINPUTS"
633   "*Environment variable setting the path where BiBTeX input files are found.
634 BiBTeX 0.99b manual says this should be TEXBIB.
635 Another version says it should BSTINPUTS.  I don't know anymore!
636
637 The colon character (:) is the default path separator in unix, but you may
638 use semi-colon (;) for DOS or OS/2 if you set bib-dos-or-os2-variable to t."
639   :group 'bib-cite
640   :type 'string)
641
642 (defcustom bib-cite-inputs nil
643   "*List of directories to search for .bib files.
644 This is in addition to those listed in the environment variable specified by
645 `bib-bibtex-env-variable'."
646   :group 'bib-cite
647   :type '(repeat (file :format "%v")))
648
649 (defcustom bib-cite-aux-inputs nil
650   "*List of directories to search for .aux files.
651 MiKTeX has the LaTeX option -aux-directory to store .aux files in an alternate
652 directory.  You may set this variable to let bib-cite find these .aux files."
653   :group 'bib-cite
654   :type '(repeat (file :format "%v")))
655
656 (defcustom bib-dos-or-os2-variable (or (equal 'emx system-type)
657                                        (equal 'ms-dos system-type))
658   ;; Under OS/2 system-type equals emx
659   ;; Under DOS  system-type equals ms-dos
660   "*Whether you use DOS or OS/2 for bib-make-bibliography/bib-display.
661
662 It tells bib-make-bibliography and bib-display to translate
663 the BIBINPUTS environment variable using the \";\" character as
664 a path separator and to translate DOS' backslash to slash.
665
666 e.g. Use a path like \"c:\\emtex\\bibinput;c:\\latex\\bibinput\"
667
668 \(You can change the environment variable which is searched by setting the  elisp variable bib-bibtex-env-variable)"
669   :group 'bib-cite
670   :type 'boolean)
671
672 (defcustom bib-etags-command "etags -r '/.*\\\\\\(eq\\|page\\|[fvF]\\)ref.*/' -o "
673   "*Variable for the etags command and its output option.
674 In unix, this is usually \"etags -r '/.*\\\(eq\|page\|[fvF]\)ref.*/' -o \"
675 \(we use the -r option to tell etags to list AMS-LaTeX's \\eqref command.)
676 In DOS and OS/2, this *may* be different, e.g. using slashes like \"etags /o=\"
677 If so, set it this variable."
678   :group 'bib-cite
679   :type 'string)
680
681 (defcustom bib-etags-append-command "etags -r '/.*\\\\\\(eq\\|page\\|[fvF]\\)ref.*/' -a -o "
682   "*Variable for the etags command and its append and output option.
683 In unix, this is usually \"etags -r '/.*\\\(eq\|page\|[fvF]\)ref.*/' -a -o \"
684 In DOS and OS/2, this *may* be \"etags /a /o=\"  If so, set it this variable."
685   :group 'bib-cite
686   :type 'string)
687
688 (defcustom bib-etags-filename "TAGS"
689    "*Variable for the filename generated by etags, by defaults this TAGS.
690 but you may want to change this to something like TAGSLaTeX such that it can
691 coexist with some other tags file in your master file directory."
692   :group 'bib-cite
693   :type 'string)
694
695 (defcustom bib-ref-regexp "\\\\\\(eq\\|page\\|[fvF]\\)?ref"
696   "*Regular expression for \\ref LaTeX commands that have a matching \\label.
697 without the curly bracket.
698
699 If you change this variable and you use multi-file documents, make sure you
700 also edit the variables bib-etags-command and bib-etags-append-command."
701   :group 'bib-cite
702   :type 'regexp)
703
704 (defcustom bib-substitute-string-in-display t
705   "*Determines if bib-display will substitute @string definitions.
706 If t, then the @string text is substituted.
707 If nil, the text is not substituted but the @string entry is included."
708   :group 'bib-cite
709   :type 'boolean)
710
711 (defcustom bib-string-ignored-warning
712   '("jan" "feb" "mar" "apr" "may" "jun" "jul" "aug" "sep" "sept" "oct" "nov"
713     "dec" "acmcs" "acta" "cacm" "ibmjrd" "ibmjs" "ieeese" "ieeetcad"
714     "ieeetc" "ipl" "jacm" "jcss" "scp" "sicomp" "tcs" "tocs" "tods" "tog"
715     "toms" "toois" "toplas" )
716   "*@string abbreviations for which a warning is not given if not defined.
717 These are usually month abbreviations (or journals) defined in a style file."
718   :group 'bib-cite
719   :type '(repeat (string :tag "Entry")))
720
721 ;;<<<<<<User-Modifiable variables end here.
722
723 (defvar bib-ref-regexpc (concat bib-ref-regexp "{")
724   "*Regular expression for \\ref LaTeX commands that have a matching \\label.
725 A opening curly bracket is appended to the regexp.")
726
727 (defvar bib-cite-minor-mode nil)
728
729 (defvar bib-highlight-mouse-keymap (make-sparse-keymap)
730   "Keymap for mouse bindings in highlighted texts in bicite.")
731
732 (defvar bib-ext-list nil
733   "Xemacs buffer-local list of bib-cite extents.")
734 (make-variable-buffer-local 'bib-ext-list)
735 (put 'bib-ext-list 'permanent-local t)
736
737 (defvar bib-cite-minor-mode-menu nil)
738
739 ;;;###autoload
740 (defun bib-cite-minor-mode (arg)
741   "Toggle bib-cite mode.
742 When bib-cite mode is enabled, citations, labels and refs are highlighted
743 when the mouse is over them.  Clicking on these highlights with [mouse-2]
744 runs bib-find, and [mouse-3] runs bib-display."
745   (interactive "P")
746   (set (make-local-variable 'bib-cite-minor-mode)
747        (if arg
748            (> (prefix-numeric-value arg) 0)
749          (not bib-cite-minor-mode)))
750   (cond
751    (bib-cite-minor-mode                 ;Setup the minor-mode
752     ;; Christoph Wedler's <wedler@fmi.uni-passau.de> suggestion for xemacs
753     ;; Added for version 2.19
754     (if (boundp 'tags-always-exact)
755         (progn
756           (set (make-local-variable 'tags-always-exact) nil)))
757     ;; mouse overlay
758     (if bib-highlight-mouse-t
759         (progn
760           (bib-cite-setup-highlight-mouse-keymap)
761           (bib-highlight-mouse)
762           (when (featurep 'xemacs)
763             (make-local-hook 'after-change-functions))
764           (add-hook 'after-change-functions
765                     'bib-cite-setup-mouse-function nil t)))
766     (if (featurep 'xemacs)
767         (progn
768           (or (local-variable-p 'current-menubar (current-buffer))
769               (set-buffer-menubar current-menubar))
770           (add-submenu nil bib-cite-minor-mode-menu))))
771    (t
772    ;;;Undo the minor-mode
773     ;; mouse overlay
774     (cond
775      ((featurep 'xemacs)
776       (while bib-ext-list
777         (delete-extent (car bib-ext-list))
778         (setq bib-ext-list (cdr bib-ext-list))))
779      (t
780       (remove-hook 'after-change-functions 'bib-cite-setup-mouse-function t)
781       (let ((before-change-functions) (after-change-functions))
782         ;; FIXME This detroys all mouse-faces and local-maps!
783         ;; FIXME Hope no other package is using them in this buffer!
784         (remove-text-properties (point-min) (point-max)
785                                 '(mouse-face t local-map t)))))
786     (if (featurep 'xemacs)
787         (delete-menu-item '("BCite"))))))
788
789 ;;This must be eval'ed when the LaTeX mode is in use.
790 ;; bib-highlight-mouse-keymap is a local variable so each buffer can have it's
791 ;; own.
792 (defun bib-cite-setup-highlight-mouse-keymap ()
793   "Set up the bib-cite text in the current buffer to be clickable."
794   (set (make-local-variable 'bib-highlight-mouse-keymap)
795    ;;; First, copy the local keymap so we don't have `disappearing' menus
796    ;;; when the mouse is moved over a \ref, \label or \cite command.
797
798    ;;; FIXME: Check out (mouse-major-mode-menu) to see how it grabs the local
799    ;;;        menus to display.  Maybe on `highlighted' commands we could only
800    ;;;        display the bib-cite stuff (or a subset of it).
801         (let ((m (copy-keymap (current-local-map))))
802           (cond
803            ((featurep 'xemacs)
804             (set-keymap-name m 'bib-highlight-mouse-keymap)
805             (cond
806              ;;action-key stuff from Vladimir Alexiev <vladimir@cs.ualberta.ca>
807              ((commandp 'action-key)
808               ;; for hyperbole. The Right Way is to define implicit buttons
809               ;; (defib) bib-cite and label-ref instead of overriding
810               ;; action-key and assist key, so that eg smart key help can
811               ;; be obtained, but I'm lazy.
812               (substitute-key-definition 'action-key 'bib-find m global-map)
813               (substitute-key-definition 'assist-key 'bib-display m global-map)
814               (substitute-key-definition 'action-key-depress
815                                          'bib-find-mouse m global-map)
816               (substitute-key-definition 'assist-key-depress
817                                          'bib-display-mouse m global-map)
818               (substitute-key-definition 'action-mouse-key nil m global-map)
819               (substitute-key-definition 'assist-mouse-key nil m global-map))
820              (t                               ; xemacs, not hyperbole
821               (define-key m "\e\r" 'bib-find-mouse) ;   bug Fixed in V2.17
822               (define-key m "\e\n" 'bib-display-mouse) ;bug Fixed in V2.17
823               ;;(define-key m [(shift button1)] 'bib-display-mouse)
824               (define-key m [button3] 'bib-display-mouse)
825               (define-key m [button2] 'bib-find-mouse))))
826             (t                                 ; emacs 19
827              (cond
828               ((commandp 'action-key)
829                (substitute-key-definition 'action-key 'bib-find m global-map)
830                (substitute-key-definition 'assist-key 'bib-display m global-map)
831                (substitute-key-definition 'action-mouse-key-emacs19
832                                           'bib-find-mouse m global-map)
833                (substitute-key-definition 'assist-mouse-key-emacs19
834                                           'bib-display-mouse m global-map)
835                (substitute-key-definition 'action-key-depress-emacs19
836                                           nil m global-map)
837                (substitute-key-definition 'assist-key-depress-emacs19
838                                           nil m global-map))
839               (t                               ; emacs 19, not hyperbole
840                (define-key m [down-mouse-3] 'bib-display-mouse)
841                (define-key m [mouse-2] 'bib-find-mouse)))))
842           m)))
843
844 ;;;###autoload
845 (defun turn-on-bib-cite ()
846   "Unconditionally turn on Bib Cite mode."
847   (bib-cite-minor-mode 1))
848
849 (defun bib-cite-setup-mouse-function (beg end _old-len)
850   (save-excursion
851     (save-match-data
852       (save-restriction
853         (narrow-to-region
854          (progn (goto-char beg) (beginning-of-line) (point))
855          (progn (goto-char end) (forward-line 1) (point)))
856         (bib-highlight-mouse)))))
857
858 (defvar bib-cite-minor-mode-map
859   (let ((map (make-sparse-keymap)))
860     (define-key map "\C-cba" 'bib-apropos)
861     (define-key map "\C-cbb" 'bib-make-bibliography)
862     (define-key map "\C-cbd" 'bib-display)
863     (define-key map "\C-cbe" 'bib-etags)
864     (define-key map "\C-cbf" 'bib-find)
865     (define-key map "\C-cbn" 'bib-find-next)
866     (define-key map "\C-cbh" 'bib-highlight-mouse)
867     map)
868   "Bib-cite minor-mode keymap.")
869
870 (easy-menu-define
871  bib-cite-minor-mode-menu bib-cite-minor-mode-map "Menu keymap for bib-cite."
872  '("BCite"
873    ["Make BibTeX bibliography buffer" bib-make-bibliography t]
874    ["Display citation or matching \\ref or \\label" bib-display t]
875    ["Find BibTeX citation or matching \\ref or \\label" bib-find t]
876    ["Search apropos BibTeX files" bib-apropos t]
877    ["Build TAGS file for multi-file document" bib-etags (bib-master-file)]
878    ["Refresh \\cite, \\ref and \\label mouse highlight"
879     bib-highlight-mouse t]))
880
881 ;; Install ourselves:
882 (or (assq 'bib-cite-minor-mode minor-mode-alist)
883     (setq minor-mode-alist
884           (cons '(bib-cite-minor-mode " BCite") minor-mode-alist)))
885 (or (assq 'bib-cite-minor-mode minor-mode-map-alist)
886     (setq minor-mode-map-alist
887           (cons (cons 'bib-cite-minor-mode bib-cite-minor-mode-map)
888                 minor-mode-map-alist)))
889
890
891 ;;; Add a menu entry to bibtex.el (Perhaps I should not do this).
892 (cond
893  ((and (featurep 'xemacs)
894        (or window-system
895            (fboundp 'smart-menu)))      ;text menus by Bob Weiner
896   ;;
897   ;; xemacs under X with AUCTeX
898   ;;
899
900   ;; Add to bibtex.el's popup menu
901   (defvar bib-cite-xemacs-bibtex-mode-menu
902     '("---"
903       "Bib-Cite"
904       "---"
905       ["Search apropos BibTeX files" bib-apropos t]
906       ["Create AUCTeX auto parsing file" bib-create-auto-file t])
907     "Submenu of bibtex-mode menu, used by bib-cite.")
908
909   (with-boundp 'bibtex-menu
910     (if (boundp 'bibtex-menu)
911         ;; Add menu now
912         (setq bibtex-menu
913               (append
914                bibtex-menu
915                bib-cite-xemacs-bibtex-mode-menu))
916       ;; Setup to add menu later
917       (defun bib-cite-bibtex-mode-hook ()
918         (if (boundp 'bibtex-menu)
919             (progn
920               (setq bibtex-menu
921                     (append
922                      bibtex-menu
923                      bib-cite-xemacs-bibtex-mode-menu))
924               (remove-hook 'bibtex-mode-hook 'bib-cite-bibtex-mode-hook))))
925       (add-hook 'bibtex-mode-hook 'bib-cite-bibtex-mode-hook)))
926   )
927
928  ((and (not (featurep 'xemacs))
929        (string-equal "19" (substring emacs-version 0 2))
930        (or window-system
931            (fboundp 'tmm-menubar)))     ; 19.30 - Will autoload if necessary
932   ;;
933   ;; emacs-19 under X-windows (or non-X with tmm)
934   ;;
935
936   ;; This *almost* makes me want to switch over to XEmacs...
937
938   ;; to AUCTeX auto file for a bibtex buffer
939   (eval-after-load
940    "bibtex"
941    '(progn
942       (add-hook 'bibtex-mode-hook 'TeX-bibtex-set-BibTeX-dialect)
943       (cond
944        ((lookup-key bibtex-mode-map [menu-bar move/edit])
945         (define-key-after
946           (lookup-key bibtex-mode-map [menu-bar move/edit])
947           [bib-nil] '("---" . nil) '"--")
948         (define-key-after
949           (lookup-key bibtex-mode-map [menu-bar move/edit])
950           [bib-apropos] '("Search Apropos" . bib-apropos) 'bib-nil)
951         (define-key-after
952           (lookup-key bibtex-mode-map [menu-bar move/edit])
953           [auc-tex-parse]
954           '("Create AUCTeX auto parsing file" . bib-create-auto-file)
955           'bib-apropos))
956        ((lookup-key bibtex-mode-map [menu-bar bibtex-edit])
957         (define-key-after
958           (lookup-key bibtex-mode-map [menu-bar bibtex-edit])
959           [bib-nil] '("---" . nil) '"--")
960         (define-key-after
961           (lookup-key bibtex-mode-map [menu-bar bibtex-edit])
962           [bib-apropos] '("Search Apropos" . bib-apropos) 'bib-nil)
963         (define-key-after
964           (lookup-key bibtex-mode-map [menu-bar bibtex-edit])
965           [auc-tex-parse]
966           '("Create AUCTeX auto parsing file" . bib-create-auto-file)
967           'bib-apropos)))))))
968
969 ;; Following from bibtex.el
970 (defvar
971   bib-cite-bibtex-font-lock-keywords
972   '(("^\\( \\|\t\\)*\\(@[A-Za-z]+\\)[ \t]*[({]\\([][A-Za-z0-9.:;?!`'()/*@_+=|<>-]+\\)?"
973      (2 font-lock-function-name-face)
974      (3 font-lock-reference-face nil t))
975     ;; reference type and reference label
976     ("^[ \t]*\\(OPT[^\"#%'(),={} \t\n0-9][^\"#%'(),={} \t\n]*\\)[ \t]*="
977      1 font-lock-comment-face)
978     ;; optional field names (treated as comments)
979     ("^[ \t]*\\([^\"#%'(),={} \t\n0-9][^\"#%'(),={} \t\n]*\\)[ \t]*="
980      1 font-lock-variable-name-face)
981     ;; field names
982     "Default expressions to fontify in BibTeX mode."))
983
984 (defvar bib-cite-bibtex-mode-syntax-table
985   (let ((st (make-syntax-table)))
986     ;; [alarson:19920214.1004CST] make double quote a string quote
987     (modify-syntax-entry ?\" "\"" st)
988     (modify-syntax-entry ?$ "$$  " st)
989     (modify-syntax-entry ?% "<   " st)
990     (modify-syntax-entry ?'  "w   " st)
991     (modify-syntax-entry ?@  "w   " st)
992     (modify-syntax-entry ?\\ "\\" st)
993     (modify-syntax-entry ?\f ">   " st)
994     (modify-syntax-entry ?\n ">   " st)
995     (modify-syntax-entry ?~ " " st)
996     st))
997 ;; Code from bibtex.el ends
998
999 ;; @string starts with a letter and does not contain any of ""#%'(),={}
1000 ;; Here we do not check that the field contains only one string field and
1001 ;; nothing else.
1002 (defvar bib-string-regexp
1003       "^[, \t]*[a-zA-Z]+[ \t]*=[ \t]*\\([a-zA-Z][^#%'(),={}\" \t\n]*\\)"
1004       "Regular expression for field containing a @string.")
1005
1006 (defun bib-cite--kind ()
1007   (save-excursion
1008     (if (not (looking-at "\\\\"))
1009         (search-backward "\\" nil t))
1010     (if (looking-at bib-ref-regexpc)
1011         'ref
1012       (if (looking-at "\\\\label{")
1013           'label
1014         'cite))))
1015
1016 (defun bib-display ()
1017   "Display BibTeX citation or matching \\ref or \\label command under point.
1018
1019 If text under cursor is a \\cite command, then display its BibTeX info from
1020 \\bibliography input file.
1021    Example with cursor located over cite command or arguments:
1022      \cite{Wadhams81,Bourke.et.al87,SchneiderBudeus94}
1023         ^Display-all-citations          ^Display-this-citation
1024
1025 If text under cursor is a \\ref command, then display environment associated
1026 with its matching \\label command.
1027
1028 If text under cursor is a \\label command, then display the text around
1029 the first matching \\ref command.
1030
1031 The user is prompted for a \\label or \\ref is nothing suitable is found under
1032 the cursor.  The first prompt is for a label.  If you answer with an empty
1033 string, a second prompt for a ref will be given.
1034
1035 A TAGS file is created and used for multi-file documents under auctex."
1036   (interactive)
1037   (let ((kind (bib-cite--kind)))
1038     (cond
1039      ;; reftex doesn't handle label->ref
1040      ((and bib-cite-use-reftex-view-crossref
1041            (memq kind '(ref cite)))
1042       ;;;FIXME: reftex doesn't want point on \ref or \cite part, but on keyword
1043       (require 'reftex)
1044       (reftex-view-crossref nil))
1045      ((eq kind 'cite)
1046       (bib-display-citation))
1047      (t
1048       (bib-display-label)))))
1049
1050 (defun bib-find ()
1051   "Edit BibTeX citation or find matching \\ref or \\label command under point.
1052
1053 For multi-entry cite commands, the cursor should be on the actual cite key
1054 desired (otherwise a random entry will be selected).
1055 e.g.: \cite{Wadhams81,Bourke.et.al87,SchneiderBudeus94}
1056                         ^Display-this-citation
1057
1058 If text under cursor is a \\ref command, then point is moved to its matching
1059 \\label command.
1060
1061 If text under cursor is a \\label command, then point is moved to the first
1062 matching \\ref command.
1063
1064 The user is prompted for a \\label or \\ref is nothing suitable is found under
1065 the cursor.  The first prompt is for a label.  If you answer with an empty
1066 string, a second prompt for a ref will be given.
1067
1068 A TAGS file is created and used for multi-file documents under auctex."
1069   (interactive)
1070   (let ((kind (bib-cite--kind)))
1071     (cond
1072      ;; reftex doesn't handle label->ref
1073      ((and bib-cite-use-reftex-view-crossref
1074            (memq kind '(ref cite)))
1075       (require 'reftex)
1076       (reftex-view-crossref t))
1077      ((eq kind 'cite)
1078       (bib-edit-citation))
1079      (t
1080       (bib-find-label)))))
1081
1082 (defvar bib-cite-search-ring nil
1083   "Bib-cite intenal variable to hold last \\ref or \\eqref find.")
1084
1085 (defun bib-find-next (&optional prev-p)
1086   "Find next occurrence of a \ref or \eqref.
1087 This is made necessary because we now use a regexp to find tags in multi-file
1088 documents, and the Emacs command `find-tag' doesn't allow to interactively
1089 find the next occurrence of a regexp."
1090   (interactive "P")
1091   (if (bib-master-file)                 ;Multi-file document
1092       (if prev-p
1093           (find-tag t '- t)
1094         (find-tag t t t))
1095     (if bib-cite-search-ring
1096         ;;FIXME: Should first make sure I move off initial \ref{}.
1097         (let ((regexp (concat bib-ref-regexpc bib-cite-search-ring "}")))
1098           (if prev-p
1099               (if (not (re-search-backward regexp nil t))
1100                   (message "No previous occurrence of reference %s"
1101                            bib-cite-search-ring))
1102             (if (not (re-search-forward regexp nil t))
1103                 (message "No next occurrence of reference %s"
1104                          bib-cite-search-ring))))
1105       (message "Sorry, no previous reference to find.  Use bib-find?"))))
1106
1107 (defun bib-display-mouse (EVENT)
1108   "Display BibTeX citation or matching \\ref or \\label under mouse EVENT.
1109 See bib-display."
1110   (interactive "e")
1111   (mouse-set-point EVENT)
1112   (bib-display))
1113
1114 (defun bib-find-mouse (EVENT)
1115   "Edit BibTeX citation or find matching \\ref or \\label under mouse EVENT.
1116 See bib-find."
1117   (interactive "e")
1118   (mouse-set-point EVENT)
1119   (bib-find))
1120
1121 (defun bib-apropos ()
1122   "Display BibTeX entries containing a keyword from bibliography file.
1123 The files specified in the \\bibliography command are searched unless
1124 the current buffer is in `bibtex-mode' or is the Help buffer.  In those
1125 cases, *it* is searched.  This allows you to trim down a search further
1126 by using bib-apropos sequentially."
1127   ;;(interactive "sBibTeX apropos: ")
1128   (interactive)
1129   (let* ((keylist (and (boundp 'TeX-auto-update) ;Avoid error in FRAMEPOP
1130                        (fboundp 'LaTeX-bibitem-list) ;Use this if using auctex
1131                        (LaTeX-bibitem-list)))
1132          (keyword (bib-apropos-keyword-at-point))
1133          (keyword (completing-read "BiBTeX apropos: " keylist nil nil keyword))
1134          (the-text)(key-point)(start-point)
1135          (new-buffer-f (and (not (string-match "^bib" mode-name))
1136                             (not (string-equal "*Help*" (buffer-name)))))
1137          (bib-buffer (or (and new-buffer-f (bib-get-bibliography nil))
1138                          (current-buffer))))
1139     (with-current-buffer bib-buffer
1140       (goto-char (point-min))
1141       (while (and (re-search-forward "^[ \t]*@" nil t)
1142                   (re-search-forward keyword nil t))
1143         (setq key-point (point))        ;To make sure this is within entry
1144         (re-search-backward "^[ \t]*@" nil t)
1145         (setq start-point (point))
1146         (forward-list 1)
1147         (if (< (point) key-point)       ;And this is that test...
1148             (goto-char key-point)       ;Not within entry, skip it.
1149           (setq the-text
1150                 (cons (concat (buffer-substring start-point (point)) "\n")
1151                       the-text))))
1152       (if (not the-text)
1153           (message "Sorry, no matches found.")
1154         (with-output-to-temp-buffer "*Help*"
1155           (mapc #'princ (nreverse the-text)))
1156         (bib-cite-fontify-help-as-bibtex)
1157         (if bib-novice
1158             (message
1159              (substitute-command-keys
1160               (concat "Use \\[bib-apropos] again in the *help* buffer"
1161                       " to trim the search")))))
1162       (if new-buffer-f
1163           (kill-buffer bib-buffer)))))
1164
1165 (defvar bib-document-citekeys-obarray-warnings nil
1166   "Bib-cite internal variable.")
1167
1168 (defun bib-make-bibliography ()
1169   "Extract citations used in the current document from \bibliography{} file(s).
1170 Put them into a buffer named after the current buffer, with extension .bib.
1171
1172 In an AUCTeX multi-file document, parsing must be on and the citation keys
1173 are extracted from the .aux files.
1174
1175 In a plain LaTeX buffer (not multi-file), the cite keys are extracted from
1176 the text itself.  Therefore the text need not have been previously processed
1177 by LaTeX.
1178
1179 This function is useful when you want to share a LaTeX file, and therefore want
1180 to create a bibtex file containing only the references used in the document."
1181   (interactive)
1182   (let* ((the-keys-obarray (or (bib-document-citekeys-obarray)
1183                                (bib-buffer-citekeys-obarray)))
1184                                         ;1st in case of error
1185          (new-buffer
1186           (create-file-buffer
1187            (concat (substring (buffer-name) 0
1188                               (or (string-match "\\." (buffer-name))
1189                                   (length (buffer-name))))
1190                    "-bib.bib")))
1191          (bib-buffer (bib-get-bibliography nil))
1192          (the-warnings (bib-get-citations the-keys-obarray
1193                                           bib-buffer
1194                                           new-buffer
1195                                           nil)))
1196     (kill-buffer bib-buffer)
1197 ;;; (switch-to-buffer new-buffer)
1198     (funcall bib-switch-to-buffer-function new-buffer)
1199     (bibtex-mode)
1200     (if (or bib-document-citekeys-obarray-warnings
1201             the-warnings)
1202         (progn
1203           (cond
1204            ((and bib-document-citekeys-obarray-warnings the-warnings)
1205             (with-output-to-temp-buffer "*Help*"
1206               (princ bib-document-citekeys-obarray-warnings the-warnings)))
1207            (bib-document-citekeys-obarray-warnings
1208             (with-output-to-temp-buffer "*Help*"
1209               (princ bib-document-citekeys-obarray-warnings)))
1210            (the-warnings
1211             (with-output-to-temp-buffer "*Help*" (princ the-warnings))))
1212           (setq bib-document-citekeys-obarray-warnings nil) ;Reset
1213           (bib-cite-fontify-red)))
1214     (if bib-novice
1215         (message
1216          (substitute-command-keys
1217           "Use \\[save-buffer] to save this buffer to a file.")))))
1218
1219 (defun bib-cite-fontify-red (&optional limit)
1220   "Fontify *Help* buffer in red-bold up to optional LIMIT."
1221   (if (and window-system                ;Not exactly correct for XEmacs
1222            (not (facep 'red-bold)))
1223       (progn
1224         (copy-face 'bold 'red-bold)
1225         (set-face-foreground 'red-bold "red")))
1226   (with-current-buffer "*Help*"
1227     (let ((before-change-functions) (after-change-functions))
1228       (put-text-property (point-min)(or limit (point-max))
1229                          'face 'red-bold))))
1230
1231 (when (featurep 'xemacs)
1232   (defun bib-cite-fontify-help-xemacs (defaults)
1233     (if (fboundp 'font-lock-set-defaults-1) ; >= XEmacs 19.14
1234         (with-current-buffer "*Help*"
1235           (setq font-lock-defaults-computed nil
1236                 font-lock-keywords nil)
1237           (font-lock-set-defaults-1
1238            (and defaults (font-lock-find-font-lock-defaults defaults)))
1239           (font-lock-fontify-buffer)
1240           (setq font-lock-defaults-computed nil
1241                 font-lock-keywords nil)
1242           (font-lock-set-defaults-1)))))
1243
1244 (defun bib-cite--fontify-help ()
1245   ;; FIXME: This looks ugly and incorrect.
1246   (if font-lock-mode
1247       (font-lock-mode -1)
1248     (if (fboundp 'font-lock-unset-defaults) (font-lock-unset-defaults))
1249     (font-lock-unfontify-buffer))
1250   (if (fboundp 'font-lock-ensure)
1251       (font-lock-ensure)
1252     (with-no-warnings (font-lock-fontify-buffer))))
1253
1254 (defun bib-cite-fontify-help-as-bibtex ()
1255   (cond
1256    ((not (featurep 'font-lock))
1257     nil)                                ;No font-lock! Stop here.
1258    ;; font-lock under Emacs and XEmacs
1259    ((featurep 'xemacs)
1260     ;; XEmacs
1261     (bib-cite-fontify-help-xemacs 'bibtex-mode))
1262    (t
1263     ;; Emacs
1264     (with-current-buffer "*Help*"
1265       (let ((font-lock-defaults
1266              '(bib-cite-bibtex-font-lock-keywords
1267                nil t ((?$ . "\"")(?\" . ".")))))
1268         (bib-cite--fontify-help))))))
1269
1270 (defun bib-cite-fontify-help-as-latex ()
1271   (cond
1272    ((not (featurep 'font-lock))
1273     nil)                                ;No font-lock! Stop here.
1274    ;; font-lock under Emacs and XEmacs
1275    ((featurep 'xemacs)
1276     ;; XEmacs, not necessary to do s.th. special for font-latex, we do *not*
1277     ;; want the buffer-local faces!
1278     (bib-cite-fontify-help-xemacs 'latex-mode))
1279    (t
1280     ;; Emacs
1281     (with-current-buffer "*Help*"
1282       ;; Actually, don't want to `permanently' affect *Help* buffer...
1283       ;;(if (featurep 'font-latex)
1284       ;; (font-latex-setup)
1285       ;; Rather I should deal with this in the `let' form:
1286       ;; (make-local-variable 'font-lock-string-face)
1287       ;; (setq font-lock-string-face font-latex-math-face
1288       ;;       font-latex-string-face (default-value 'font-lock-string-face))
1289       (let ((font-lock-defaults
1290              (if (featurep 'font-latex)
1291                  '((font-latex-keywords font-latex-keywords-1
1292                                         font-latex-keywords-2)
1293                    nil nil ((?\( . ".") (?\) . ".") (?$ . "\"")) nil
1294                    (font-lock-comment-start-regexp . "%")
1295                    (font-lock-mark-block-function . mark-paragraph))
1296                '(tex-font-lock-keywords nil nil ((?$ . "\""))))))
1297         (bib-cite--fontify-help))))))
1298
1299 (defvar bib-document-TeX-files-warnings nil
1300   "Bib-cite internal variable.")
1301
1302 (defun bib-etags (&optional masterdir)
1303   "Invoke etags on all tex files of the document in directory MASTERDIR.
1304 Store the TAGS file in the master-directory.
1305 Expect errors if you use this outside of auctex or within a plain
1306 single-file document.  Also makes sure that the TAGS buffer is updated.
1307 See variables bib-etags-command and bib-etags-filename"
1308   (interactive)
1309   (require 'etags)
1310   (let* ((the-file-list (bib-document-TeX-files))
1311          (the-file (car the-file-list))
1312          (dir (or masterdir (bib-master-directory)))
1313          (the-tags-file (expand-file-name bib-etags-filename dir))
1314          (the-tags-buffer (get-file-buffer the-tags-file)))
1315     ;; Create TAGS file with first TeX file (master file)
1316     (shell-command (concat bib-etags-command the-tags-file " " the-file))
1317     (setq the-file-list (cdr the-file-list))
1318     ;; Append to TAGS file for all other TeX files.
1319     (while the-file-list
1320       (setq the-file (car the-file-list))
1321       (shell-command
1322        (concat bib-etags-append-command the-tags-file " " the-file))
1323       (setq the-file-list (cdr the-file-list)))
1324     (if the-tags-buffer                 ;buffer existed; we must refresh it.
1325         (with-current-buffer the-tags-buffer
1326           (revert-buffer t t)))
1327
1328     ;; Check value of tags-file-name against the-tags-file
1329     (or (equal the-tags-file  tags-file-name) ;make sure it's current
1330         (visit-tags-table the-tags-file))
1331
1332     ;(set (make-local-variable 'tags-file-name) the-tags-file))
1333     ;; above should not be needed
1334
1335     ;; Weird Bug:
1336     ;;  (visit-tags-table-buffer) seems to get called twice when called by
1337     ;;  find-tag on an undefined tag. The second time, it's in the TAGS
1338     ;;  buffer and returns an error because TAGS buffer does have
1339     ;;  tags-file-name set.
1340     ;;  To get around this.  I'm setting this variable in the TAGS buffer.
1341     ;; Skip this in XEmacs (Changed by Anders Stenman)
1342     (if (and (not (featurep 'xemacs))
1343              (get-file-buffer the-tags-file))
1344         (with-current-buffer (get-file-buffer the-tags-file)
1345           (set (make-local-variable 'tags-file-name) the-tags-file))))
1346
1347
1348   (if bib-document-TeX-files-warnings   ;free variable loose in emacs!
1349       (progn
1350         (with-output-to-temp-buffer "*Help*"
1351           (princ bib-document-TeX-files-warnings))
1352         (setq bib-document-TeX-files-warnings nil) ;Reset
1353         (bib-cite-fontify-red))))
1354
1355 (defun bib-Is-hidden ()
1356   "Return true is current point is hidden."
1357   (if (not selective-display)
1358       nil                               ;Not hidden if not using this...
1359     (save-excursion
1360       (if (not (re-search-backward "[\n\^M]" nil t))
1361           nil                           ;Play safe
1362         (if (string-equal (match-string 0) "\n")
1363             nil
1364           t)))))
1365
1366 (defun bib-highlight-mouse ()
1367   "Make that nice green highlight when the mouse is over LaTeX commands."
1368   (interactive)
1369   ;;Comment this out.  User should be able to use bib-highlight-mouse
1370   ;;to try it out regardless of bib-highlight-mouse-t.
1371   ;;Check bib-highlight-mouse-t only in automated cases.
1372   ;;
1373   ;;  (if (and bib-highlight-mouse-t
1374   ;;           ;;window-system)        ;Do nothing unless under X
1375   ;;           )
1376   ;; *all of code was here*
1377   ;;      )
1378   (save-excursion
1379     (let ((s)(e)(extent)(local-extent-list bib-ext-list)
1380           (inhibit-read-only t)
1381           (modified (buffer-modified-p))) ;put-text-property changing this?
1382       ;; * peta Wed Nov  8 16:27:29 1995 -- better remove the mouse face
1383       ;;   properties first.
1384       (setq bib-ext-list nil)           ;Reconstructed below...
1385       (if (featurep 'xemacs)
1386           (while local-extent-list
1387             (setq extent (car local-extent-list))
1388             (if (or (extent-detached-p extent)
1389                     (and (<= (point-min)(extent-start-position extent))
1390                          (>= (point-max)(extent-end-position extent))))
1391                 (delete-extent extent)
1392               (setq bib-ext-list (cons extent bib-ext-list)))
1393             (setq local-extent-list (cdr local-extent-list)))
1394         ;; Remove properties for regular emacs
1395         ;; FIXME This detroys all mouse-faces and local-maps!
1396         ;; FIXME Hope no other package is using them in this buffer!
1397         (let ((before-change-functions) (after-change-functions))
1398           (remove-text-properties (point-min) (point-max)
1399                                   '(mouse-face t local-map t))))
1400       (goto-char (point-min))
1401       (while
1402           (re-search-forward
1403            (concat
1404             "\\\\\\(" (substring bib-ref-regexp 2)
1405             "\\|label\\|[A-Za-z]*cite[A-Za-z]*\\(\\[[^]]*\\]\\)*\\){[^}]*}")
1406            nil t)
1407         (setq s (match-beginning 0))
1408         (setq e (match-end 0))
1409         (cond
1410          ((featurep 'xemacs)
1411           (setq extent (make-extent s e))
1412           (setq bib-ext-list (cons extent bib-ext-list))
1413           (set-extent-property extent 'highlight t)
1414           (set-extent-property extent 'start-open t)
1415           (set-extent-property extent 'balloon-help 'bib-label-help)
1416           (set-extent-property extent 'help-echo 'bib-label-help-echo)
1417           (set-extent-property extent 'keymap bib-highlight-mouse-keymap))
1418          (t
1419           (let ((before-change-functions) (after-change-functions)
1420                 ;;(this-overlay (make-overlay s e))
1421                 )
1422 ;;;  Even using overlays doesn't help here.  If bib-highlight-mouse-keymap
1423 ;;;  does not include the AucTeX menus, then these disappear when we click
1424 ;;;  onto a \cite command.  Perhaps using bib-cite as a minor mode will fix
1425 ;;;  this?  For now, bib-cite must be loaded after these menus are built.
1426 ;;;  It must therefore be loaded in a mode-hook.
1427             (put-text-property s e 'local-map bib-highlight-mouse-keymap)
1428             (put-text-property s e 'mouse-face 'highlight)
1429           ;;(overlay-put this-overlay 'local-map bib-highlight-mouse-keymap)
1430           ;;(overlay-put this-overlay 'mouse-face 'highlight)
1431             ))))
1432       (set-buffer-modified-p modified))))
1433
1434 (defun bib-toggle-highlight ()
1435   "Toggle the enabling of bib-cite entries as clickable things."
1436 ;; FIXME: do something about after-change stuff?
1437   (interactive)
1438   (if (setq bib-highlight-mouse-t (not bib-highlight-mouse-t))
1439       (bib-highlight-mouse)
1440     (let ((modified (buffer-modified-p))
1441           (inhibit-read-only t))
1442       (cond
1443        ((featurep 'xemacs)
1444         (while bib-ext-list
1445           (delete-extent (car bib-ext-list))
1446           (setq bib-ext-list (cdr bib-ext-list))))
1447        (t
1448         (let ((before-change-functions) (after-change-functions))
1449           (remove-text-properties (point-min) (point-max)
1450                                   '(mouse-face local-map)))))
1451       (set-buffer-modified-p modified))))
1452
1453 (defun bib-label-help-echo (object)
1454   (if bib-label-help-echo-format
1455       (bib-label-help object bib-label-help-echo-format)))
1456
1457 ;; Balloon-help callback. Anders Stenman <stenman@isy.liu.se>
1458 ;;             Patched by Bruce Ravel <bruce.ravel@nist.gov>
1459 (defun bib-label-help (object &optional format)
1460   (or format (setq format "Use mouse button 2 to find the %s.
1461 Use mouse button 3 to display the %s."))
1462   (save-match-data
1463     (let* ((string (extent-string object))
1464            (type (cond ((string-match "^\\\\[A-Za-z]*cite[A-Za-z]*" string) "citation")
1465                        ((string-match
1466                          (concat "^" bib-ref-regexp) string) "\\label{}")
1467                        ((string-match "^\\\\label" string) "\\ref{}")
1468                        (t "this (unknown) reference"))))
1469       (format format type type))))
1470
1471 ;;----------------------------------------------------------------------------
1472 ;; Routines to display or edit a citation's bibliography
1473
1474 (defun bib-display-citation ()
1475   "Do the displaying of cite info.  Return t if found cite key, nil otherwise.
1476 Example with cursor located over cite command or arguments:
1477 \cite{Wadhams81,Bourke.et.al87,SchneiderBudeus94}
1478    ^Display-all-citations          ^Display-this-citation"
1479   (save-excursion
1480     (let* ((the-keys-obarray (bib-get-citekeys-obarray)) ;1st in case of error
1481            (work-buffer (get-buffer-create "*bibtex-work*"))
1482            (bib-buffer (bib-get-bibliography nil))
1483            (the-warnings (bib-get-citations
1484                           the-keys-obarray
1485                           bib-buffer
1486                           work-buffer
1487                           bib-substitute-string-in-display))
1488            (the-warn-point))
1489       (if the-warnings
1490           (progn
1491             (set-buffer work-buffer)
1492             (goto-char 1)
1493             (insert the-warnings)
1494             (setq the-warn-point (point))))
1495       (with-output-to-temp-buffer
1496           "*Help*"
1497         (set-buffer work-buffer)
1498         (princ (buffer-substring 1 (point-max))))
1499       (bib-cite-fontify-help-as-bibtex)
1500       (if the-warn-point
1501           (bib-cite-fontify-red the-warn-point))
1502       (kill-buffer bib-buffer)
1503       (kill-buffer work-buffer))))
1504
1505 (defun bib-edit-citation ()
1506   "Do the edit of cite info.  Return t if found cite key, nil otherwise.
1507 Find and and put edit point in bib file associated with a BibTeX citation
1508 under cursor from \bibliography input file.
1509 In a multi-entry cite command, the cursor should be on the actual cite key
1510 desired (otherwise a random entry will be selected).
1511 e.g.: \cite{Wadhams81,Bourke.et.al87,SchneiderBudeus94}
1512                         ^Display-this-citation"
1513   (let ((the-keys-obarray (bib-get-citekeys-obarray)) ;1st in case of error
1514         (bib-buffer (bib-get-bibliography t))
1515         (the-key)(the-file))
1516     (save-excursion
1517       (mapatoms                     ;Do this for each cite-key found...
1518        (lambda (cite-key)
1519          (setq the-key (symbol-name cite-key)))
1520        the-keys-obarray)
1521       (set-buffer bib-buffer)
1522       (goto-char (point-min))
1523       (if (not (re-search-forward
1524                 (concat "@[^{(]+[{(][\t ]*" (regexp-quote the-key) "[ ,\n]")
1525                 nil t))
1526           (progn
1527             (kill-buffer bib-buffer)
1528             (error "Sorry, could not find bib entry for %s" the-key))
1529         (re-search-backward "%%%Filename: \\([^\n]*\\)" nil t)
1530         (setq the-file (match-string 1))
1531         (kill-buffer bib-buffer)))
1532 ;;; (find-file the-file)
1533     (funcall bib-switch-to-buffer-function (find-file-noselect the-file))
1534     (goto-char (point-min))             ;V2.19 fix
1535     (re-search-forward (concat "@[^{(]+[{(][\t ]*"
1536                                (regexp-quote the-key)
1537                                "[ ,\n]") nil t)))
1538
1539 ;;--------------------------------------------------------------------------
1540 ;; Function for bib-apropos
1541
1542 (defun bib-apropos-keyword-at-point ()
1543   "Return the keyword under point for initial input to bib-apropos prompt."
1544   (save-excursion
1545     (let ((here (point)))
1546       (cond
1547        ((and (re-search-backward "[\n{, ]" nil t)
1548              (string-equal "{" (buffer-substring (match-beginning 0)
1549                                                  (match-end 0))))
1550         (if (fboundp 'buffer-substring-no-properties)
1551             (buffer-substring-no-properties (1+ (point)) here)
1552         (buffer-substring (1+ (point)) here)))))))
1553
1554 ;;--------------------------------------------------------------------------
1555 ;; Functions for Displaying or moving to matching \ref or \label command
1556
1557 (defun bib-display-label ()
1558 "Display environment or first ref associated with a label.
1559 The label or ref name is extracted from the text under the cursor, or the
1560 user is prompted is nothing suitable is found.  The first prompt is for a
1561 label.  If you answer with an empty string, a second prompt for a ref will
1562 be given."
1563   (let ((the-regexp (bib-guess-or-prompt-for-label)))
1564     (if (not the-regexp)
1565         (message "No name given")
1566       (bib-display-or-find-label the-regexp t))))
1567
1568 (defun bib-find-label ()
1569   "Move to a label, or the first occurance of a ref.
1570 The label or ref name is extracted from the text under the cursor.
1571 If nothing suitable is found, the user is prompted. The first prompt is for a
1572 label. If you answer with an empty string, a second prompt for a ref will be
1573 given.
1574
1575 If within a single file document:
1576   You can move back with C-xC-x as the mark is set before moving.
1577   You can search for next occurrances of a ref command with C-sC-s.
1578
1579 If within a multi-file document (in auctex only)
1580   You can move back with C-xC-x if within the same buffer.  If not, just
1581   select your previous buffer.
1582   You can search for next occurrances of a ref command with tag commands:
1583      C-u M-.     Find next alternate definition of last tag specified.
1584      C-u - M-.   Go back to previous tag found."
1585   (let ((the-regexp (bib-guess-or-prompt-for-label)))
1586     (if (not the-regexp)
1587         (message "No name given")
1588       (bib-display-or-find-label the-regexp nil))))
1589
1590 ;;--------------------------------------------------------------------------
1591 ;; Functions for Displaying or moving to matching \ref or \label command
1592
1593 (defun bib-display-or-find-label (the-regexp displayf)
1594 ;; work horse for bib-find-label and bib-display-label
1595   (let* ((masterfile (bib-master-file))
1596          (masterdir (and masterfile
1597                          (file-name-directory masterfile)))
1598          (new-point)(new-buffer))
1599     (save-excursion
1600       ;; Now we are either in a simple file, or with a multi-file document
1601       (cond
1602        (masterfile                   ;Multi-file document
1603         (cond
1604          (displayf                  ;Display only
1605           (set-buffer (bib-etags-find-noselect the-regexp masterdir))
1606           (re-search-forward the-regexp nil t)
1607           ;; ...because tags puts point on beginning of line
1608           (if (string-match "^\\\\\\\\label" the-regexp)
1609               (bib-display-this-environment) ;display the label's environment
1610             (bib-display-this-ref)))    ;     display the ref's context
1611          (t                         ;Move to it
1612           (setq new-buffer (bib-etags-find-noselect the-regexp masterdir))
1613           (if bib-novice
1614               (message
1615                (substitute-command-keys
1616                 (concat "Use \\[bib-find-next] to find the next occurrence "
1617                         "and C-u \\[bib-find-next] to find previous."))))
1618           (if (equal new-buffer (current-buffer))
1619               (setq new-point (point)))))) ;Moving with the same buffer
1620        (t                           ;Single-file document
1621         (goto-char (point-min))
1622         (cond
1623          ((re-search-forward the-regexp nil t)
1624           (if displayf
1625               (if (string-match "^\\\\label" the-regexp)
1626                   (bib-display-this-environment) ;Display the environment
1627                 (bib-display-this-ref)) ;         display the ref's context
1628             (setq new-point (match-beginning 0))  ;or move there
1629             (if (string-match "{\\(.*\\)}" the-regexp)
1630                 (setq bib-cite-search-ring (match-string 1 the-regexp)))
1631             (if bib-novice
1632                 (message
1633                  (substitute-command-keys
1634                   (concat "Use \\[bib-find-next] to find the next occurrence "
1635                           "and C-u \\[bib-find-next] to find previous."))))))
1636          (t
1637           (message "Sorry, cannot find it (%s)" the-regexp))))))
1638     (if new-point
1639         (progn
1640           (push-mark (point) t nil)   ;We've moving there... push mark
1641           (goto-char new-point))
1642       (if new-buffer                    ;We've changing buffer
1643           ;;(switch-to-buffer new-buffer)
1644           (funcall bib-switch-to-buffer-function new-buffer)))
1645     (if (bib-Is-hidden)
1646         (save-excursion
1647           (beginning-of-line)
1648           (show-entry)))))
1649
1650 (defvar bib-label-prompt-map
1651   (let ((map (make-sparse-keymap)))
1652     (set-keymap-parent map minibuffer-local-completion-map)
1653     (define-key map " " 'self-insert-command)
1654     map))
1655
1656 (defun bib-guess-or-prompt-for-label ()
1657   "Guess from context, or prompt the user for a label command."
1658   (save-excursion
1659     (if (not (looking-at "\\\\"))        ;If not on beginning of a command
1660              (re-search-backward "[\\]"
1661                                  (save-excursion (beginning-of-line)(point))
1662                                  t))
1663     (cond
1664      ((looking-at bib-ref-regexpc)   ;On \ref, looking for matching \label
1665       (let ((b (progn (search-forward "{" nil t)(forward-char -1)(point)))
1666             (e (progn (forward-sexp 1)(point))))
1667         (concat "\\\\label" (regexp-quote (buffer-substring b e)))))
1668      ((looking-at "\\\\label{")         ;On \label, looking for matching \ref
1669       (let ((b (progn (search-forward "{" nil t)(forward-char -1)(point)))
1670             (e (progn (forward-sexp 1)(point))))
1671         (concat  bib-ref-regexp (regexp-quote (buffer-substring b e)))))
1672      (t                                 ;Prompt the user
1673       (let* ((minibuffer-local-completion-map bib-label-prompt-map)
1674              (the-alist (create-alist-from-list
1675                          (cdr (reverse LaTeX-label-list))))
1676         ;;; LaTeX-label-list example:
1677         ;;;  '(("label3" "label4")("label1" "label2") nil)
1678         ;; so let's get rid of that nil part in embedded list.
1679              (the-name
1680               (if (string-equal "18" (substring emacs-version 0 2))
1681                   (completing-read "Label: " the-alist nil nil nil)
1682                 (completing-read "Label: " the-alist nil nil nil
1683                                  'LaTeX-find-label-hist-alist))))
1684         (if (not (equal the-name ""))
1685             (concat "\\\\label{" (regexp-quote the-name) "}")
1686           ;; else try to get a \ref
1687           (if (string-equal "18" (substring emacs-version 0 2))
1688               (setq the-name (completing-read "Ref: " the-alist nil nil nil))
1689             (setq the-name (completing-read "Ref: " the-alist nil nil nil
1690                                             'LaTeX-find-label-hist-alist)))
1691           (if (not (equal the-name ""))
1692               (concat bib-ref-regexpc (regexp-quote the-name) "}")
1693             nil)))))))
1694
1695 (defun bib-display-this-ref ()
1696   "Display a few lines around current point."
1697   (cond
1698    ((bib-Is-hidden)
1699     (with-output-to-temp-buffer "*BiBTemp*"
1700       (princ
1701        (buffer-substring
1702         (save-excursion
1703           (let ((i 3))
1704             (while (and (> i 0)
1705                         (re-search-backward "[\n\^M]" nil t)
1706                         (setq i (1- i)))))
1707           (point))
1708         (save-excursion
1709           (let ((i 3))
1710             (while (and (> i 0)
1711                         (re-search-forward "[\n\^M]" nil t)
1712                         (setq i (1- i)))))
1713           (point)))))
1714     (set-buffer "*BiBTemp*")
1715     (while (search-forward "\^M" nil t)
1716       (replace-match "\n" nil t))
1717     (goto-char 1)
1718     (if (looking-at "\n")  ;Remove first empty line...
1719         (delete-char 1))
1720     (with-output-to-temp-buffer "*Help*"
1721       (princ (buffer-substring (point-min) (point-max))))
1722     (bib-cite-fontify-help-as-latex)
1723     (kill-buffer "*BiBTemp*"))
1724    (t
1725     (with-output-to-temp-buffer ;     display the ref's context
1726         "*Help*"
1727       (princ
1728        (buffer-substring (save-excursion (forward-line -2)(point))
1729                          (save-excursion (forward-line 3)(point)))))
1730     (bib-cite-fontify-help-as-latex))))
1731
1732 (defun bib-display-this-environment ()
1733   "Display the environment associated with a label, or its section name.
1734 Assumes point is already on the label.
1735 Does not save excursion."
1736 ;; Bugs:  The method used here to detect the environment is *not* foolproof.
1737 ;;        It will get confused, for example, between two figure environments,
1738 ;;        picking out both instead of the section label above them.  But since
1739 ;;        users typically puts their labels next to the section declaration,
1740 ;;        I'm satisfied with this... for now.
1741 ;; I could have used the following AUCTeX functions:
1742 ;;  LaTeX-current-environment
1743 ;;    Function: Return the name (a string) of the enclosing LaTeX environment.
1744 ;;  LaTeX-current-section
1745 ;;    Function: Return the level of the section that contain point.
1746 ;; but then this code would only work as part of AUCTeX...
1747   (let ((the-point (point))
1748         (end-point (point))
1749         (the-environment)(foundf))
1750     (while (and (not foundf)
1751                 (goto-char end-point) ;Past end of last search
1752                 (re-search-forward "\\(^\\|\^M\\)[ \t]*\\\\end{\\([^}]*\\)}"
1753                                    nil t))
1754       (setq end-point (point))
1755       (setq the-environment (match-string 2))
1756       (and (not (string-match "document" the-environment))
1757            (re-search-backward (concat "\\(^\\|\^M\\)[ \t]*\\\\begin{"
1758                                        (regexp-quote the-environment) "}"))
1759            (<= (point) the-point)
1760            (setq foundf t)))
1761     (if foundf                          ;A good environment
1762         (progn
1763           (cond ((bib-Is-hidden)        ;Better way is: replace-within-string
1764                  (with-output-to-temp-buffer "*BiBTemp*"
1765                    (princ (buffer-substring (point) end-point)))
1766                  (set-buffer "*BiBTemp*")
1767                  (while (search-forward "\^M" nil t)
1768                    (replace-match "\n" nil t))
1769                  (goto-char 1)
1770                  (if (looking-at "\n")  ;Remove first empty line...
1771                      (delete-char 1))
1772                  (with-output-to-temp-buffer "*Help*"
1773                    (princ (buffer-substring 1 (point-max))))
1774                  (kill-buffer "*BiBTemp*"))
1775                 (t
1776                  (with-output-to-temp-buffer "*Help*"
1777                    (princ (buffer-substring (point) end-point)))))
1778           (bib-cite-fontify-help-as-latex))
1779       ;; Just find the section declaration
1780       (goto-char the-point)
1781       (if (re-search-backward
1782 ;;;        "\\(^\\|\^M\\)[ \t]*\\\\\\(sub\\)*section{\\([^}]*\\)}" nil t)
1783 ;;;  Michael Steiner <steiner@cs.uni-sb.de> patch
1784            "\\(^\\|\^M\\)[ \t]*\\\\\\(\\(sub\\)*section\\|chapter\\|part\\)\\*?\
1785 {\\([^}]*\\)}"
1786            nil t)
1787           (message (match-string 0))
1788         (error
1789          "Sorry, could not find an environment or section declaration")))))
1790
1791 (defvar LaTeX-find-label-hist-alist nil "History list for LaTeX-find-label.")
1792 (defvar LaTeX-label-list nil "Used by AUCTeX to store label names.")
1793
1794
1795 (defun create-alist-from-list (the-list)
1796   "Return a single list from a THE-LIST that may contain either items or lists.
1797 e.g. turns
1798 '((\"label3\" \"label4\")(\"label1\" \"label2\") \"label\")
1799 into
1800 '((\"label3\") (\"label4\") (\"label1\") (\"label2\") (\"label\"))"
1801   (mapcar 'list (bib-cite-mh-list-to-string the-list)))
1802
1803 ;;
1804 ;; Following two functions from mh-utils.el (part of GNU emacs)
1805 ;; I have changed the names in case these functions change what they do.
1806 ;;
1807
1808 (defun bib-cite-mh-list-to-string (l)
1809   "Flattens the list L and make every element of the new list into a string."
1810   (nreverse (bib-cite-mh-list-to-string-1 l)))
1811
1812 (defun bib-cite-mh-list-to-string-1 (l)
1813   (let ((new-list nil))
1814     (while l
1815       (cond ((null (car l)))
1816             ((symbolp (car l))
1817              (setq new-list (cons (symbol-name (car l)) new-list)))
1818             ((numberp (car l))
1819              (setq new-list (cons (int-to-string (car l)) new-list)))
1820             ((equal (car l) ""))
1821             ((stringp (car l)) (setq new-list (cons (car l) new-list)))
1822             ((listp (car l))
1823              (setq new-list (nconc (bib-cite-mh-list-to-string-1 (car l))
1824                                    new-list)))
1825             (t (error "Bad element in mh-list-to-string: %s" (car l))))
1826       (setq l (cdr l)))
1827     new-list))
1828
1829 ;; -------------------------------------------------------------------------
1830 ;; Routines to extract cite keys from text
1831
1832 ;;    ... is truly remarkable, as shown in \citeN{Thomson77,Test56}. Every
1833 ;; \cite[{\it e.g.}]{Thomson77,Test56}
1834
1835 (defun bib-get-citations (keys-obarray bib-buffer new-buffer substitute)
1836   "Put citations of KEYS-OBARRAY from BIB-BUFFER into NEW-BUFFER.
1837 Substitute strings if SUBSTITUTE is t
1838 Return the-warnings as text."
1839   (let ((the-warnings)                  ;The only variable to remember...
1840         (case-fold-search t))           ;All other results go into new-buffer
1841     ;; bibtex is not case-sensitive for keys.
1842     (save-excursion
1843       (let ((the-text))
1844         (set-buffer bib-buffer)
1845         (mapatoms                         ;Do this for each cite-key found...
1846          (lambda (cite-key)
1847            (goto-char (point-min))
1848            (if (re-search-forward
1849                 (concat "@[^{(]+[{(][\t ]*"
1850                         (regexp-quote (symbol-name cite-key))
1851                         "\\([, ]\\\|$\\)")
1852                 ;;           ^^     ^  comma, space or end-of-line
1853                 nil t)
1854                (setq the-text (concat the-text
1855                                       (buffer-substring
1856                                        (progn (beginning-of-line)(point))
1857                                        (progn (forward-sexp 2)(point)))
1858                                       "\n\n"))
1859              (setq the-warnings (concat the-warnings
1860                                         "Cannot find entry for: "
1861                                         (symbol-name cite-key) "\n"))))
1862          keys-obarray)
1863         (if (not the-text)
1864             (error "Sorry, could not find any of the references"))
1865         ;; Insert the citations in the new buffer
1866         (set-buffer new-buffer)
1867         (insert the-text)
1868         (goto-char 1))
1869
1870       ;; We are at beginning of new-buffer.
1871       ;; Now handle crossrefs
1872       (let ((crossref-obarray (make-vector 201 0)))
1873         (while (re-search-forward
1874                 "[, \t]*crossref[ \t]*=[ \t]*\\(\"\\|\{\\)" nil t)
1875           ;;handle {text} or "text" cases
1876           (if (string-equal "{" (match-string 1))
1877               (re-search-forward "[^\}]+" nil t)
1878             (re-search-forward "[^\"]+" nil t))
1879           (intern (match-string 0) crossref-obarray))
1880         ;; Now find the corresponding keys,
1881         ;; but add them only if not already in `keys-obarray'
1882         (set-buffer bib-buffer)
1883         (goto-char 1)
1884         (let ((the-text))
1885           (mapatoms                     ;Do this for each crossref key found...
1886            (lambda (crossref-key)
1887              (if (not (intern-soft (symbol-name crossref-key) keys-obarray))
1888                  (progn
1889                    ;; Not in keys-obarray, so not yet displayed.
1890                    (goto-char (point-min))
1891                    (if (re-search-forward
1892                         (concat "@[^{(]+[{(][\t ]*"
1893                                 (regexp-quote (symbol-name crossref-key))
1894                                 "\\(,\\|$\\)")
1895                         nil t)
1896                        (setq the-text
1897                              (concat the-text
1898                                      (buffer-substring
1899                                       (progn (beginning-of-line)(point))
1900                                       (progn (forward-sexp 2)(point)))
1901                                      "\n\n"))
1902                      (setq the-warnings
1903                            (concat the-warnings
1904                                    "Cannot find crossref entry for: "
1905                                    (symbol-name crossref-key) "\n"))))))
1906            crossref-obarray)
1907           ;; Insert the citations in the new buffer
1908           (set-buffer new-buffer)
1909           (goto-char (point-max))
1910           (if the-text
1911               (insert the-text)))
1912         (goto-char 1))
1913
1914       ;; Now we have all citations in new-buffer, collect all used @String keys
1915       ;; Ex:  journal =      JPO,
1916       (let ((strings-obarray (make-vector 201 0)))
1917         (while (re-search-forward bib-string-regexp nil t)
1918           (intern (match-string 1) strings-obarray))
1919         ;; Now find the corresponding @String commands
1920         ;; Collect either the @string commands, or the string to substitute
1921         (set-buffer bib-buffer)
1922         (goto-char 1)
1923         (let ((string-alist)
1924               (the-text))
1925           (mapatoms                     ;Do this for each string-key found...
1926            (lambda (string-key)
1927              (goto-char (point-min))
1928              ;; search for @string{ key = {text}} or @string{ key = "text"}
1929              (if (re-search-forward
1930                   (concat "^[ \t]*@string[{(]"
1931                           (regexp-quote (symbol-name string-key))
1932                           "[\t ]*=[\t ]*\\(\"\\|\{\\)")
1933                   nil t)
1934                  (let ((the-string-start (1- (match-end 1))) ;catch bracket
1935                        ;;handle {text} or "text" cases
1936                        (the-string-end
1937                         (cond
1938                          ((string-equal "\"" (match-string 1))
1939                           (re-search-forward "[^\\]\"" nil t)
1940                           (point))
1941                          (t
1942                           (forward-char -1)
1943                           (forward-list 1)
1944                           (point)))))
1945                    (if substitute      ;Collect substitutions
1946                        (setq string-alist
1947                              (append
1948                               string-alist
1949                               (list
1950                                (cons (symbol-name string-key)
1951                                         ;(regexp-quote
1952                                      (buffer-substring the-string-start
1953                                                        the-string-end)))));)
1954                      ;;Collect the strings command themseves
1955                      (setq the-text
1956                            (concat the-text
1957                                    (buffer-substring
1958                                     (progn (forward-char 1)(point))
1959                                     (re-search-backward "^[ \t]*@string[{(]"
1960                                                         nil t))
1961                                    "\n"))))
1962                ;; @string entry not found
1963                (if (not (member-cis (symbol-name string-key)
1964                                     bib-string-ignored-warning))
1965                    (setq the-warnings
1966                          (concat the-warnings
1967                                  "Cannot find @String entry for: "
1968                                  (symbol-name string-key) "\n")))))
1969            strings-obarray)
1970           ;; Now we have `the-text' of @string commands,
1971           ;; or the `string-alist' to substitute.
1972           (set-buffer new-buffer)
1973           (if substitute
1974               (while string-alist
1975                 (goto-char 1)
1976                 (let* ((the-key (car (car string-alist)))
1977                        (the-string (cdr (car string-alist)))
1978                        (slashed-string  ; "J. of Geo.\" -> "J. of Geo.\\\\"
1979                         (dired-replace-in-string
1980                          "\\\\" "\\\\" the-string)))
1981
1982                   (while (re-search-forward
1983                           (concat "\\(^[, \t]*[a-zA-Z]+[ \t]*=[ \t]*\\)"
1984                                   (regexp-quote the-key)
1985                                   "\\([, \t\n]\\)")
1986                           nil t)
1987                     (replace-match (concat "\\1" slashed-string "\\2") t nil)))
1988                 (setq string-alist (cdr string-alist)))
1989             ;; substitute is nil; Simply insert text of @string commands
1990             (goto-char 1)
1991             (if the-text
1992                 (insert the-text "\n")))
1993           (goto-char 1))))
1994
1995     ;; We are done!
1996     ;; Return the warnings...
1997     the-warnings))
1998
1999 ;; Following contributed by Michael Steiner <steiner@cs.uni-sb.de> The
2000 ;;  @string abbreviation are not case-sensitive, so we replaced the `member'
2001 ;;  test above with `member-cis' defined here:
2002 (defun member-cis (ELT LIST)
2003   "Return non-nil if ELT is an element of LIST.
2004 All elements should be strings.
2005 Comparison is case-insensitive."
2006   ;; If list is exhausted,
2007   (if (null LIST)
2008       nil ;; if null then we haven't found the element ...
2009     ;; else split list and ...
2010     (let((listelt (car LIST))(listrest (cdr LIST)))
2011       ;; see if car is equal to ELT
2012       (if (string-equal (downcase ELT) (downcase listelt))
2013           t ;; if so return true
2014         ;; else recurse for rest of list
2015         (member-cis ELT listrest)))))
2016
2017 (defun bib-get-citekeys-obarray ()
2018   "Return obarray of citation key (within curly brackets) under cursor."
2019   (save-excursion
2020     ;; First find *only* a key *within a cite command
2021     (let ((the-point (point))
2022           (keys-obarray (make-vector 201 0)))
2023       ;; First try to match a cite command
2024       (if (and (skip-chars-backward "a-zA-Z") ;Stops on \ or {
2025                (looking-at "[a-zA-Z]*cite[a-zA-Z]*"))
2026           (progn
2027             ;;skip over any optional arguments to \cite[][]{key} command
2028             (skip-chars-forward "a-zA-Z")
2029             (while (looking-at "\\[")
2030               (forward-list 1))
2031             (re-search-forward "{[ \n]*\\([^,} \n]+\\)" nil t)
2032             (intern (match-string 1) keys-obarray)
2033             (while (and (skip-chars-forward " \n") ;no effect on while
2034                         (looking-at ","))
2035               (forward-char 1)
2036               ;;The following re-search skips over leading spaces
2037               (re-search-forward "\\([^,} \n]+\\)" nil t)
2038               (intern (match-string 1) keys-obarray)))
2039         ;; Assume we are on the keyword
2040         (goto-char the-point)
2041         (let ((the-start (re-search-backward "[\n{, ]" nil t))
2042               (the-end (progn (goto-char the-point)
2043                               (re-search-forward "[\n}, ]" nil t))))
2044           (if (and the-start the-end)
2045               (intern (buffer-substring (1+ the-start) (1- the-end))
2046                       keys-obarray)
2047             ;; Neither...
2048             (error "Sorry, can't find a reference here"))))
2049       keys-obarray)))
2050
2051 (defun bib-buffer-citekeys-obarray ()
2052   "Extract citations keys used in the current buffer."
2053   (let ((keys-obarray (make-vector 201 0)))
2054     (save-excursion
2055       (goto-char (point-min))
2056       ;; Following must allow for \cite[e.g.][]{key} !!!
2057       ;; regexp for \cite{key1,key2} was "\\\\[a-Z]*cite[a-Z]*{\\([^,}]+\\)"
2058       (while (re-search-forward "\\\\[a-zA-Z]*cite[a-zA-Z]*\\(\\[\\|{\\)"
2059                                 nil t)
2060         (backward-char 1)
2061         (while (looking-at "\\[")       ; ...so skip all bracketted options
2062           (forward-sexp 1))
2063         ;; then lookup first key
2064         (if (looking-at "{[ \n]*\\([^,} \n]+\\)")
2065             (progn
2066               (intern (match-string 1) keys-obarray)
2067               (goto-char (match-end 1))
2068               (while (and (skip-chars-forward " \n")
2069                           (looking-at ","))
2070                 (forward-char 1)
2071                 (re-search-forward "\\([^,} \n]+\\)" nil t)
2072                 (intern (match-string 1) keys-obarray)))))
2073       (if keys-obarray
2074           keys-obarray
2075         (error "Sorry, could not find any citation keys in this buffer")))))
2076
2077 ;;---------------------------------------------------------------------------
2078 ;; Multi-file document programming requirements:
2079 ;; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2080 ;; bib-make-bibliography
2081 ;;    bib-document-citekeys-obarray needs the master .aux file to extract
2082 ;;   citation keys.
2083 ;;    Included .aux files (corresponding to \include'd LaTeX files) are
2084 ;;   then specified relative to the master-file-directory.
2085 ;;
2086 ;; bib-get-bibliography (used by interactive commands to extract bib sources)
2087 ;;
2088 ;;    bibtex source filenames are returned from (LaTeX-bibliography-list)
2089 ;;   unformatted.  Since only a single \bibliogragrphy command is allowed
2090 ;;   by BiBTeX in a document, it is safe to assume that their path is
2091 ;;   relative to the master file's directory (since the path is relative
2092 ;;   to where the BiBTeX program is actually ran).
2093 ;;
2094
2095 ;; (See TeX-check-files, used in TeX-save-document.  All documents related
2096 ;;  files are returned by (TeX-style-list) and stored in TeX-active-styles.
2097 ;;  Original idea was to search TeX-check-path for files listed in
2098 ;;  TeX-active-styles (with possible relative or full paths) that end in .tex.)
2099
2100 (defun bib-master-directory ()
2101   "Return the directory associated with the master file.
2102 If no master file, then return current default."
2103   (let ((masterfile (bib-master-file)))
2104     (if masterfile
2105         (file-name-directory (expand-file-name (TeX-master-file)))
2106       default-directory)))
2107
2108 (defun bib-master-file ()
2109   "Return master file full path, or nil if not a multi-file document."
2110 ;; I wish there were a better way to tell about non multi-file documents...
2111   (let ((master
2112          (cond
2113           ((not (boundp 'TeX-master))
2114            ;; This buffer doesn't know what a master file is, so return now.
2115            nil)
2116           ((and TeX-master              ;Set, but not to t
2117                 (not (symbolp TeX-master))) ; then we have an actual name
2118            (expand-file-name TeX-master))
2119           ((and (eq TeX-master 't)      ;Test if master file itself
2120                 (progn                  ;But also require at least one \include
2121                   (save-excursion
2122                     (goto-char 1)       ;Too bad I have to do this search...
2123                     ;; Require that user uses \input{file}
2124                     ;; rather than            \input file
2125                     (re-search-forward "^[ \t]*\\\\\\(include\\|input\\){"
2126                                        nil t))))
2127            (buffer-file-name))
2128           (t
2129            nil))))
2130     (cond
2131      ((not master)
2132       nil)
2133      ((string-match ".\\(tex\\|ltx\\)$" master)
2134       master)
2135      ((file-readable-p (concat master ".ltx"))
2136       (concat master ".ltx"))
2137      (t
2138       (concat master ".tex")))))
2139
2140 ;; I don't use this one because files are not returned in order...
2141 ;; (defun bib-document-TeX-files ()
2142 ;; ;; Return all tex input files associated with a known multi-file document.
2143 ;;   (let ((master-directory (bib-master-directory))
2144 ;;         (the-list (cons (file-name-nondirectory (TeX-master-file))
2145 ;;                         (TeX-style-list)))
2146 ;;      ;; TeX-style-list returns "../master" for the main file if TeX-master
2147 ;;      ;; was set like that.  "../master" would not be found relative
2148 ;;      ;; to the master-directory!  So let's add it to the list w/o directory.
2149 ;;         (the-result)
2150 ;;         (the-file))
2151 ;;     (while the-list
2152 ;;       (setq the-file (expand-file-name (car the-list) master-directory))
2153 ;;       (setq the-list (cdr the-list))
2154 ;;       (and (not (string-match ".tex$" the-file))
2155 ;;            (setq the-file (concat the-file ".tex")))
2156 ;;       (and (file-readable-p the-file)
2157 ;;            (not (member the-file the-result)) ;listed already?
2158 ;;            (setq the-result (cons the-file the-result))))
2159 ;;     the-result))
2160
2161 (defun bib-document-TeX-files ()
2162   "Return all tex input files associated with a *known* multi-file document.
2163 For a multi-file document in auctex only.
2164 No checking is done that this is a real multi-file document.
2165 Sets global variable bib-document-TeX-files-warnings."
2166   (setq bib-document-TeX-files-warnings nil)
2167   (let* ((masterfile (bib-master-file))
2168          (dir (and masterfile (file-name-directory masterfile)))
2169          (tex-buffer (get-buffer-create "*tex-document*"))
2170          (the-list (list masterfile)))
2171     (if (not masterfile)
2172         (progn
2173           (kill-buffer tex-buffer)
2174           (error
2175            "Sorry, but this is not a multi-file document (Try C-u C-c C-n if using auctex)")))
2176     (with-current-buffer tex-buffer
2177       ;; set its directory so relative includes work without expanding
2178       (setq default-directory dir)
2179       (insert-file-contents masterfile)
2180       (goto-char (point-min))
2181       (while (re-search-forward "^[ \t]*\\\\\\(input\\|include\\){\\(.*\\)}"
2182                                 nil t)
2183         (let ((the-file (match-string 2)))
2184           (if (string-match ".sty$" the-file) ;Skip over style files!
2185               nil
2186             (if (and (not (file-readable-p (expand-file-name the-file dir)))
2187                      (not (string-match ".ltx$" the-file))
2188                      (file-readable-p
2189                       (expand-file-name (concat the-file ".ltx") dir)))
2190                 (setq the-file (concat the-file ".ltx")))
2191             (if (and (not (file-readable-p (expand-file-name the-file dir)))
2192                      (not (string-match ".tex$" the-file)))
2193                 (setq the-file (concat the-file ".tex")))
2194             (setq the-file (expand-file-name the-file dir))
2195             (if (not (file-readable-p the-file))
2196                 (setq bib-document-TeX-files-warnings
2197                       (concat
2198                        bib-document-TeX-files-warnings
2199                        (format "Warning: File not found: %s" the-file)))
2200               (setq the-list (cons (expand-file-name the-file dir) the-list))
2201               (end-of-line)(insert "\n")
2202               (insert-file-contents the-file))))))
2203     (kill-buffer tex-buffer)
2204     (nreverse the-list)))
2205
2206 (defun bib-document-citekeys-obarray ()
2207   "Return cite keys obarray for multi-file document.
2208 Return nil if not a multi-file document.
2209 This is a AUCTeX supported feature only.
2210 Also, see bib-buffer-citekeys-obarray.
2211 Sets global variable bib-document-citekeys-obarray-warnings."
2212   (setq bib-document-citekeys-obarray-warnings nil)
2213   (let ((master-tex (bib-master-file))
2214         (master-aux))
2215     (if (not master-tex)
2216         nil                             ;Not a multifile document.  No need...
2217       (setq master-aux (bib-return-aux-file-from-tex master-tex "aux"))
2218       (or (file-readable-p master-aux)
2219           (error "Sorry, cannot read file %s" master-aux))
2220       (and (file-newer-than-file-p master-tex master-aux)
2221            (setq bib-document-citekeys-obarray-warnings
2222                  (format "Warning: %s is out of date relative to %s.\n"
2223                          master-aux master-tex)))
2224       (let ((work-buffer (get-buffer-create "*bib-cite-work*"))
2225             (keys-obarray (make-vector 201 0)))
2226         (with-current-buffer work-buffer
2227           (insert-file-contents master-aux)
2228           ;; Because we will be looking for \input statements, we need to set
2229           ;; the default directory to that of the master file.
2230           (setq default-directory (file-name-directory master-tex))
2231           ;; bib-make-bibliography will need this also to find .bib files
2232           ;; look for \@input{chap1/part1.aux}
2233           (while (re-search-forward "^\\\\@input{\\(.*\\)}$" nil t)
2234             (let* ((auxfile (match-string 1))
2235                    (texfile (bib-return-aux-file-from-tex auxfile "tex")))
2236               (if (not (file-readable-p auxfile))
2237                   (setq bib-document-citekeys-obarray-warnings
2238                         (concat
2239                          bib-document-citekeys-obarray-warnings
2240                          (format "Warning: %s is not found or readable.\n"
2241                                  auxfile)))
2242                 (if (file-newer-than-file-p texfile auxfile)
2243                     (setq bib-document-citekeys-obarray-warnings
2244                           (concat
2245                            bib-document-citekeys-obarray-warnings
2246                            (format
2247                             "Warning: %s is out of date relative to %s.\n"
2248                             auxfile texfile))))
2249                 (end-of-line)(insert "\n")
2250                 (insert-file-contents auxfile))))
2251           (goto-char 1)
2252
2253 ;;;  Patched by calvanes@dis.uniroma1.it (Diego Calvanese)
2254 ;;;      ;; look for \citation{gertsenshtein59}
2255 ;;;       (while (re-search-forward "^\\\\citation{\\(.*\\)}$" nil t)
2256 ;;;         (intern (buffer-substring (match-beginning 1)(match-end 1))
2257 ;;;                 keys-obarray))
2258           ;; look for \citation{gertsenshtein59,vardi88,...,ullmann90}
2259           ;; comma-separation generated by certain LaTeX styles.
2260           (while (re-search-forward "^\\\\citation{\\(.*\\)}$" nil t)
2261             (let ((string (match-string 1))
2262                   (start 0))
2263               (while (string-match "\\([^,\n]+\\)" string start)
2264                 (intern (substring string (match-beginning 1) (match-end 1))
2265                         keys-obarray)
2266                 (setq start (match-end 0))))))
2267         (kill-buffer work-buffer)
2268         keys-obarray))))
2269
2270 (defun bib-return-aux-file-from-tex (texname ext)
2271   "Given name.name.XXX in TEXNAME return name.name.EXT."
2272 ;; FIXME: Check if in ./, else search
2273   (let* ((filename (if (string-match "\\(.*\\)\\.[^\\.]+" texname)
2274                        (concat (match-string 1 texname) "." ext)
2275                      (concat texname "." ext)))
2276          (sansdir (file-name-nondirectory filename)))
2277     (if (file-exists-p filename)
2278         filename
2279       ;; Search bib-cite-aux-inputs path
2280       (let ((filename (psg-checkfor-file-list sansdir bib-cite-aux-inputs)))
2281         (if (and filename (file-exists-p filename))
2282             filename
2283           (error "Could not find file %s" sansdir))))))
2284
2285 (defun bib-etags-find-noselect (tag &optional masterdir)
2286   "Returns a buffer with point on TAG.
2287 Buffer is not selected.
2288 Makes sure TAGS file exists, etc."
2289   (require 'etags)
2290   (let* ((master (or masterdir (bib-master-directory)))
2291          (the-buffer (current-buffer))
2292          (new-buffer)
2293          (the-tags-file-name (expand-file-name bib-etags-filename master)))
2294     (or (file-exists-p the-tags-file-name) ;make sure TAGS exists
2295         (bib-etags master))
2296     (or (equal the-tags-file-name tags-file-name) ;make sure it's current
2297         (visit-tags-table the-tags-file-name))
2298     ;; find-tag-noselect should set the TAGS file for the new buffer
2299     ;; that's what C-h f visit-tags-table says...
2300     (cond
2301      ((featurep 'xemacs)
2302       (find-tag tag)
2303       (setq new-buffer (current-buffer))
2304       (set-buffer the-buffer))
2305      (t
2306       (setq new-buffer (find-tag-noselect tag nil t))
2307                                         ; -> Seems to set buffer to TAGS
2308       (set-buffer the-buffer)))
2309     new-buffer))
2310
2311 ;; --------------------------------------------------------------------------
2312 ;; The following routines make a temporary bibliography buffer
2313 ;; holding all bibtex files found.
2314
2315 (defun bib-get-bibliography (include-filenames-f)
2316   "Returns a new bibliography buffer holding all bibtex files in the document.
2317
2318 If using AUCTeX, and either TeX-parse-self is set or C-c C-n is used to
2319 parse the document, then the entire multifile document will be searched
2320 for \bibliography commands.
2321
2322 If this fails, the current buffer is searched for the first \bibliography
2323 command.
2324
2325 If include-filenames-f is true, include as a special header the filename
2326 of each bib file.
2327
2328 Puts the buffer in text-mode such that forward-sexp works with german \"
2329 accents embeded in bibtex entries."
2330   (let ((bib-list (or (and (fboundp 'LaTeX-bibliography-list)
2331                            (boundp 'TeX-auto-update)
2332                            (LaTeX-bibliography-list))
2333 ;; LaTeX-bibliography-list (if bound) returns an unformatted list of
2334 ;; bib files used in the document, but only if parsing is turned on
2335 ;; or C-c C-n was used.
2336                       (bib-bibliography-list)))
2337         (bib-buffer (get-buffer-create "*bibtex-bibliography*"))
2338         ;; Path is relative to the master directory
2339         (default-directory (bib-master-directory))
2340         (the-name)(the-warnings)(the-file))
2341     (with-current-buffer bib-buffer
2342       ;; such that forward-sexp works with embeeded \" in german,
2343       ;; and unbalanced ()
2344       (erase-buffer)
2345       (set-syntax-table text-mode-syntax-table)
2346 ;;      (if (boundp 'bibtex-mode-syntax-table)
2347 ;;          (set-syntax-table bibtex-mode-syntax-table)
2348 ;;        (text-mode))
2349       )
2350     ;;We have a list of bib files
2351     ;;Search for them, include them, list those not readable
2352     (while bib-list
2353       (setq the-name (car (car bib-list))) ;Extract the string only
2354       (setq bib-list (cdr bib-list))
2355       (setq the-name
2356             (substring the-name
2357                        (string-match "[^ ]+" the-name) ;remove leading spaces
2358                        (string-match "[ ]+$" the-name))) ;remove trailing space
2359       (if (not (string-match "\\.bib$" the-name))
2360           (setq the-name (concat the-name ".bib")))
2361       (setq the-file
2362             (or (and (file-readable-p the-name) the-name)
2363                 (psg-checkfor-file-list
2364                  the-name (psg-list-env bib-bibtex-env-variable))
2365                 ;; Check for BIBINPUT env variable as well (by popular demand!)
2366                 (psg-checkfor-file-list the-name (psg-list-env "BIBINPUT"))
2367                 (and bib-cite-inputs
2368                      (psg-checkfor-file-list the-name bib-cite-inputs))
2369                 (and (boundp 'TeX-check-path)
2370                      (psg-checkfor-file-list the-name TeX-check-path))))
2371       (if the-file
2372           (with-current-buffer bib-buffer
2373             (goto-char (point-max))
2374             (if include-filenames-f
2375                 (insert "%%%Filename: " the-file "\n"))
2376             (insert-file-contents the-file nil)
2377             (goto-char 1))
2378         (setq the-warnings
2379               (concat the-warnings "Could not read file: " the-name "\n"))))
2380     (if the-warnings
2381         (progn
2382           (with-output-to-temp-buffer "*Help*"
2383             (princ the-warnings))
2384           (kill-buffer bib-buffer)
2385           (error
2386            "Sorry, can't find all bibtex files in \\bibliography command"))
2387       bib-buffer)))
2388
2389 (defun bib-bibliography-list ()
2390   "Return list of bib files listed in first \\bibliography command in buffer.
2391 Similar output to AUCTeX's LaTeX-bibliography-list
2392 The first element may contain trailing whitespace (if there was any in input)
2393 although BiBTeX doesn't allow it!"
2394   (save-excursion
2395     (goto-char 1)
2396     (if (not (re-search-forward "^[ \t]*\\\\bibliography{[ \t]*\\([^},]+\\)"
2397                                 nil t))
2398         (error "Sorry, can't find \\bibliography command anywhere")
2399       (let ((the-list (list (match-string 1)))
2400             (doNext t))
2401         (while doNext
2402           (if (looking-at ",")
2403               (setq the-list
2404                     (append the-list
2405                             (list (buffer-substring
2406                                    (progn (skip-chars-forward ", ")(point))
2407                                    (progn (re-search-forward "[,}]" nil t)
2408                                           (backward-char 1)
2409                                           (skip-chars-backward ", ")
2410                                           (point))))))
2411             (setq doNext nil)))
2412         (mapcar 'list the-list)))))
2413
2414 (defvar TeX-auto-save)
2415 (defvar TeX-auto-update)
2416 (defvar TeX-auto-regexp-list)
2417
2418 ;; BibTeX-mode key def to create AUCTeX's parsing file.
2419 (defun bib-create-auto-file ()
2420   "Force the creation of the AUCTeX auto file for a bibtex buffer."
2421   (interactive)
2422   (if (not (require 'latex))
2423       (error "Sorry, This is only useful if you have AUCTeX"))
2424   (let ((TeX-auto-save t)
2425         (TeX-auto-update t)
2426         (TeX-auto-regexp-list BibTeX-auto-regexp-list))
2427     ;; TeX-auto-write
2428     ;; -> calls TeX-auto-store
2429     ;;    -> calls TeX-auto-parse
2430     ;;       clears LaTeX-auto-bibtem (temporary holding space for bibitems)
2431     ;;       searches buffer using regexp in TeX-auto-regexp-list
2432     ;;    -> if LaTeX-auto-bibtem (the temporary holding space for bibitems)
2433     ;;       holds stuffs like
2434     ;;         ("Zimmermann:1991" "Anger_et_al:1993")
2435     ;;       as determined by
2436     ;;         (member nil (mapcar 'TeX-auto-entry-clear-p TeX-auto-parser))
2437     ;;       then it creates the auto file.
2438
2439     ;; TeX-auto-write may call TeX-master-file which may fail if
2440     ;; TeX-header-end is unset (by LaTeX-common-initialization in latex-mode)
2441     (if (not TeX-header-end)
2442         (setq TeX-header-end LaTeX-header-end))
2443
2444     (TeX-auto-write)))
2445
2446 ;; --------------------------------------------------------------------------
2447 ;; The following routines are also defined in other packages...
2448
2449 (defun psg-checkfor-file-list (filename list)
2450   "Check for presence of FILENAME in directory LIST.  Return 1st found path."
2451   ;;USAGE: (psg-checkfor-file-list "gri" (psg-list-env "PATH"))
2452   ;;USAGE: (psg-checkfor-file-list "gri-mode.el" load-path)
2453   ;;USAGE: (psg-checkfor-file-list "gri.cmd" (psg-translate-ff-list "gri.tmp"))
2454   (let ((the-list list)
2455         (filespec))
2456     (while the-list
2457       (if (not (car the-list))          ; it is nil
2458           (setq filespec (expand-file-name filename))
2459         (setq filespec
2460               (concat
2461                (expand-file-name (file-name-as-directory (car the-list)))
2462                filename)))
2463       (if (file-exists-p filespec)
2464             (setq the-list nil)
2465         (setq filespec nil)
2466         (setq the-list (cdr the-list))))
2467     (if filespec
2468         filespec
2469       ;; If I have not found a file yet, then check if some directories
2470       ;; ended in // and recurse through them.
2471       (let ((the-list list))
2472         (while the-list
2473           (if (not (string-match "//$" (car the-list))) nil
2474             (setq filespec (car
2475                             (search-directory-tree
2476                              (substring (car the-list) 0 (match-beginning 0))
2477                              (concat "^" filename "$")
2478                              t
2479                              t)))
2480             (if filespec                ;Success!
2481                 (setq the-list nil)))
2482           (setq the-list (cdr the-list)))
2483         filespec))))
2484
2485
2486 (defun search-directory-tree (directories extension-regexp recurse first-file)
2487   "Return a list of all reachable files in DIRECTORIES ending with EXTENSION.
2488 DIRECTORIES is a list or a single-directory string
2489 EXTENSION-REGEXP is actually (any) regexp, usually \\\\.bib$
2490 If RECURSE is t, then we will recurse into the directory tree,
2491               nil, we will only search the list given.
2492 If FIRST-FILE is t, stop after first file is found."
2493   (or (listp directories)
2494       (setq directories (list directories)))
2495
2496   (let (match)
2497     (while directories
2498       (let* ((directory (file-name-as-directory  (car directories)))
2499              (content (and directory
2500                            (file-readable-p directory)
2501                            (file-directory-p directory)
2502                            (directory-files directory))))
2503         (setq directories (cdr directories))
2504         (while content
2505           (let ((file (expand-file-name (car content) directory)))
2506             (cond ((string-match "[.]+$" (car content))) ;This or parent dir
2507                   ((not (file-readable-p file)))
2508                   ((and recurse
2509                         (file-directory-p file))
2510                    (setq directories
2511                          (cons (file-name-as-directory file) directories)))
2512                   ((string-match extension-regexp
2513                                  (file-name-nondirectory file))
2514                    (and first-file
2515                         (setq content nil
2516                               directories nil))
2517                    (setq match (cons file match)))))
2518           (setq content (cdr content)))))
2519
2520     match))
2521
2522 ;; (defun psg-checkfor-file-list (filename list)
2523 ;;   (let ((the-list list)
2524 ;;         (filespec))
2525 ;;     (while the-list
2526 ;;       (if (not (car the-list))          ; it is nil
2527 ;;           (setq filespec (concat "~/" filename))
2528 ;;         (setq filespec
2529 ;;               (concat (file-name-as-directory (car the-list)) filename)))
2530 ;;       (if (file-exists-p filespec)
2531 ;;             (setq the-list nil)
2532 ;;         (setq filespec nil)
2533 ;;         (setq the-list (cdr the-list))))
2534 ;;     filespec))
2535
2536 (or (fboundp 'dired-replace-in-string)
2537     ;; This code is part of GNU emacs
2538     (defun dired-replace-in-string (regexp newtext string)
2539       ;; Replace REGEXP with NEWTEXT everywhere in STRING and return result.
2540       ;; NEWTEXT is taken literally---no \\DIGIT escapes will be recognized.
2541       (let ((result "") (start 0) mb me)
2542         (while (string-match regexp string start)
2543           (setq mb (match-beginning 0)
2544                 me (match-end 0)
2545                 result (concat result (substring string start mb) newtext)
2546                 start me))
2547         (concat result (substring string start)))))
2548
2549
2550 ;; Could use fset here to equal TeX-split-string to dired-split if only
2551 ;; dired-split is defined.  That would eliminate a check in psg-list-env.
2552 (and (not (fboundp 'TeX-split-string))
2553      (not (fboundp 'dired-split))
2554      ;; This code is part of AUCTeX
2555      (defun TeX-split-string (char string)
2556        "Returns a list of strings. given REGEXP the STRING is split into
2557 sections which in string was seperated by REGEXP.
2558
2559 Examples:
2560
2561       (TeX-split-string \"\:\" \"abc:def:ghi\")
2562           -> (\"abc\" \"def\" \"ghi\")
2563
2564       (TeX-split-string \" *\" \"dvips -Plw -p3 -c4 testfile.dvi\")
2565
2566           -> (\"dvips\" \"-Plw\" \"-p3\" \"-c4\" \"testfile.dvi\")
2567
2568 If CHAR is nil, or \"\", an error will occur."
2569
2570        (let ((regexp char)
2571              (start 0)
2572              (result '()))
2573          (while (string-match regexp string start)
2574            (let ((match (string-match regexp string start)))
2575              (setq result (cons (substring string start match) result))
2576              (setq start (match-end 0))))
2577          (setq result (cons (substring string start nil) result))
2578          (nreverse result))))
2579
2580 (defun bib-cite-file-directory-p (file)
2581   "Like default `file-directory-p' but allow FILE to end in // for ms-windows."
2582   (save-match-data
2583     (if (string-match "\\(.*\\)//$" file)
2584         (file-directory-p (match-string 1 file))
2585       (file-directory-p file))))
2586
2587 (defun psg-list-env (env)
2588   "Return a list of directory elements in ENV variable (w/o leading $)
2589 argument may consist of environment variable plus a trailing directory, e.g.
2590 HOME or HOME/bin (trailing directory not supported in dos or OS/2).
2591
2592 bib-dos-or-os2-variable affects:
2593   path separator used (: or ;)
2594   whether backslashes are converted to slashes"
2595   (if (not (getenv env))
2596       nil                               ;Because dired-replace-in-string fails
2597     (let* ((value (if bib-dos-or-os2-variable
2598                       (dired-replace-in-string "\\\\" "/" (getenv env))
2599                     (getenv env)))
2600            (sep-char (or (and bib-dos-or-os2-variable ";") ":"))
2601            (entries (and value
2602                          (or (and (fboundp 'TeX-split-string)
2603                                   (TeX-split-string sep-char value))
2604                              (dired-split sep-char value)))))
2605       (loop for x in entries if (bib-cite-file-directory-p x) collect x))))
2606
2607 (provide 'bib-cite)
2608 ;;; bib-cite.el ends here