]> git.donarmstrong.com Git - lib.git/blob - emacs_el/bibtex.el
Initial user home directory commit
[lib.git] / emacs_el / bibtex.el
1 ;;; bibtex.el --- BibTeX mode for GNU Emacs
2
3 ;; Copyright (C) 1992, 1994, 1995, 1996, 1997, 1998, 1999 Free Software Foundation, Inc.
4
5 ;; Author: Stefan Schoef <schoef@offis.uni-oldenburg.de>
6 ;;      Bengt Martensson <bengt@mathematik.uni-Bremen.de>
7 ;;      Mark Shapiro <shapiro@corto.inria.fr>
8 ;;      Mike Newton <newton@gumby.cs.caltech.edu>
9 ;;      Aaron Larson <alarson@src.honeywell.com>
10 ;; Maintainer: none
11 ;; Keywords: BibTeX, LaTeX, TeX
12
13 ;; This file is part of GNU Emacs.
14
15 ;; GNU Emacs is free software; you can redistribute it and/or modify
16 ;; it under the terms of the GNU General Public License as published by
17 ;; the Free Software Foundation; either version 2, or (at your option)
18 ;; any later version.
19
20 ;; GNU Emacs is distributed in the hope that it will be useful,
21 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
22 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 ;; GNU General Public License for more details.
24
25 ;; You should have received a copy of the GNU General Public License
26 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
27 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
28 ;; Boston, MA 02111-1307, USA.
29
30 ;;; Commentary:
31
32 ;;  Major mode for editing and validating BibTeX files.
33
34 ;;  Usage:
35 ;;  See documentation for function bibtex-mode (or type "\M-x describe-mode"
36 ;;  when you are in BibTeX mode).
37
38 ;;  Todo:
39 ;;  Distribute texinfo file.
40
41 ;;; Code:
42
43 (eval-when-compile
44   (require 'compile))
45
46 \f
47 ;; Bug Reporting
48
49 (defconst
50   bibtex-maintainer-address "Dirk Herrmann <D.Herrmann@tu-bs.de>")
51 ;; current maintainer
52
53 (defconst
54   bibtex-maintainer-salutation "Hallo Dirk,")
55 ;; current maintainer
56
57 (defconst
58   bibtex-version "(emacs 20.4)")
59 ;; current version of the bibtex.el file
60
61 \f
62 ;; User Options:
63
64 (defgroup bibtex nil
65   "BibTeX mode."
66   :group 'tex
67   :prefix "bibtex-")
68
69 (defgroup bibtex-autokey nil
70   "Generates automatically a key from the author/editor and the title field"
71   :group 'bibtex
72   :prefix "bibtex-autokey-")
73
74 (defcustom bibtex-mode-hook nil
75   "List of functions to call on entry to BibTeX mode."
76   :group 'bibtex
77   :type 'hook)
78
79 (defcustom bibtex-field-delimiters 'braces
80   "*Controls type of field delimiters used.
81 Set this to `braces' or `double-quotes' according to your personal
82 preferences.  This variable is buffer-local."
83   :group 'bibtex
84   :type '(choice (const braces)
85                  (const double-quotes)))
86 (make-variable-buffer-local 'bibtex-field-delimiters)
87
88 (defcustom bibtex-entry-delimiters 'braces
89   "*Controls type of entry delimiters used.
90 Set this to `braces' or `parentheses' according to your personal
91 preferences.  This variable is buffer-local."
92   :group 'bibtex
93   :type '(choice (const braces)
94                  (const parentheses)))
95 (make-variable-buffer-local 'bibtex-entry-delimiters)
96
97 (defcustom bibtex-include-OPTcrossref '("InProceedings" "InCollection")
98   "*All entries listed here will have an OPTcrossref field."
99   :group 'bibtex
100   :type '(repeat string))
101
102 (defcustom bibtex-include-OPTkey t
103   "*If non-nil, all entries will have an OPTkey field.
104 If this is a string, it will be used as the initial field text.
105 If this is a function, it will be called to generate the initial field text."
106   :group 'bibtex
107   :type '(choice (const :tag "None" nil)
108                  (string :tag "Initial text")
109                  (function :tag "Initialize Function" :value fun)
110                  (other :tag "Default" t)))
111
112 (defcustom bibtex-user-optional-fields
113   '(("annote" "Personal annotation (ignored)"))
114   "*List of optional fields the user wants to have always present.
115 Entries should be of the same form as the OPTIONAL and
116 CROSSREF-OPTIONAL lists in `bibtex-entry-field-alist' (see documentation
117 of this variable for details)."
118   :group 'bibtex
119   :type '(repeat
120           (group (string :tag "Field")
121                  (string :tag "Comment")
122                  (option (group :inline t
123                                 :extra-offset -4
124                                 (choice :tag "Init" :value ""
125                                         string
126                                         function))))))
127
128 (defcustom bibtex-entry-format '(opts-or-alts numerical-fields)
129   "*Controls type of formatting performed by `bibtex-clean-entry'.
130 It may be t, nil, or a list of symbols out of the following:
131 opts-or-alts        Delete empty optional and alternative fields and
132                       remove OPT and ALT prefixes from used fields.
133 numerical-fields    Delete delimiters around numeral fields.
134 page-dashes         Change double dashes in page field to single dash
135                       (for scribe compatibility).
136 inherit-booktitle   If entry contains a crossref field and booktitle
137                       field is empty, it is set to the contents of the
138                       title field of the crossreferenced entry.
139                       Caution: this will work only if buffer is
140                        correctly sorted.
141 realign             Realign entries, so that field texts and perhaps equal
142                       signs (depending on the value of
143                       `bibtex-align-at-equal-sign') begin in the same column.
144 last-comma          Add or delete comma on end of last field in entry,
145                       according to value of `bibtex-comma-after-last-field'.
146 delimiters          Change delimiters according to variables
147                       `bibtex-field-delimiters' and `bibtex-entry-delimiters'.
148 unify-case          Change case of entry and field names.
149
150 The value t means do all of the above formatting actions.
151 The value nil means do no formatting at all."
152   :group 'bibtex
153   :type '(choice (const :tag "None" nil)
154                  (const :tag "All" t)
155                  (set :menu-tag "Some"
156                       (const opts-or-alts)
157                       (const numerical-fields)
158                       (const page-dashes)
159                       (const inherit-booktitle)
160                       (const realign)
161                       (const last-comma)
162                       (const delimiters)
163                       (const unify-case))))
164
165 (defcustom bibtex-clean-entry-hook nil
166   "*List of functions to call when entry has been cleaned.
167 Functions are called with point inside the cleaned entry, and the buffer
168 narrowed to just the entry."
169   :group 'bibtex
170   :type 'hook)
171
172 (defcustom bibtex-sort-ignore-string-entries t
173   "*If non-nil, BibTeX @String entries are not sort-significant.
174 That means they are ignored when determining ordering of the buffer
175 (e.g., sorting, locating alphabetical position for new entries, etc.).
176 This variable is buffer-local."
177   :group 'bibtex
178   :type 'boolean)
179 (make-variable-buffer-local 'bibtex-sort-ignore-string-entries)
180
181 (defcustom bibtex-maintain-sorted-entries nil
182   "*If non-nil, BibTeX mode maintains all BibTeX entries in sorted order.
183 Setting this variable to nil will strip off some comfort (e.g., TAB
184 completion for reference keys in minibuffer, automatic detection of
185 duplicates) from BibTeX mode.  See also `bibtex-sort-ignore-string-entries'.
186 This variable is buffer-local."
187   :group 'bibtex
188   :type 'boolean)
189 (make-variable-buffer-local 'bibtex-maintain-sorted-entries)
190
191 (defcustom bibtex-field-kill-ring-max 20
192   "*Max length of `bibtex-field-kill-ring' before discarding oldest elements."
193   :group 'bibtex
194   :type 'integer)
195
196 (defcustom bibtex-entry-kill-ring-max 20
197   "*Max length of `bibtex-entry-kill-ring' before discarding oldest elements."
198   :group 'bibtex
199   :type 'integer)
200
201 (defcustom bibtex-parse-keys-timeout 60
202   "*Specifies interval for parsing buffers.
203 All BibTeX buffers in Emacs are parsed if Emacs has been idle
204 `bibtex-parse-keys-timeout' seconds.  Only buffers which were modified
205 after last parsing and which are maintained in sorted order are parsed."
206   :group 'bibtex
207   :type 'integer)
208
209 (defvar bibtex-entry-field-alist
210   '(
211     ("Article" . (((("author" "Author1 [and Author2 ...] [and others]")
212                     ("title" "Title of the article (BibTeX converts it to lowercase)")
213                     ("journal" "Name of the journal (use string, remove braces)")
214                     ("year" "Year of publication"))
215                    (("volume" "Volume of the journal")
216                     ("number" "Number of the journal (only allowed if entry contains volume)")
217                     ("pages" "Pages in the journal")
218                     ("month" "Month of the publication as a string (remove braces)")
219                     ("note" "Remarks to be put at the end of the \\bibitem")
220                     ("abstract" "Abstract of the publication")))
221                   ((("author" "Author1 [and Author2 ...] [and others]")
222                     ("title" "Title of the article (BibTeX converts it to lowercase)"))
223                    (("pages" "Pages in the journal")
224                     ("journal" "Name of the journal (use string, remove braces)")
225                     ("year" "Year of publication")
226                     ("volume" "Volume of the journal")
227                     ("number" "Number of the journal")
228                     ("month" "Month of the publication as a string (remove braces)")
229                     ("note" "Remarks to be put at the end of the \\bibitem")
230                     ("abstract" "Abstract of the publication")))))
231     ("Book" . (((("author" "Author1 [and Author2 ...] [and others]" "" t)
232                  ("editor" "Editor1 [and Editor2 ...] [and others]" "" t)
233                  ("title" "Title of the book")
234                  ("publisher" "Publishing company")
235                  ("year" "Year of publication"))
236                 (("volume" "Volume of the book in the series")
237                  ("number" "Number of the book in a small series (overwritten by volume)")
238                  ("series" "Series in which the book appeared")
239                  ("address" "Address of the publisher")
240                  ("edition" "Edition of the book as a capitalized English word")
241                  ("month" "Month of the publication as a string (remove braces)")
242                  ("note" "Remarks to be put at the end of the \\bibitem")))
243                ((("author" "Author1 [and Author2 ...] [and others]" "" t)
244                  ("editor" "Editor1 [and Editor2 ...] [and others]" "" t)
245                  ("title" "Title of the book"))
246                 (("publisher" "Publishing company")
247                  ("year" "Year of publication")
248                  ("volume" "Volume of the book in the series")
249                  ("number" "Number of the book in a small series (overwritten by volume)")
250                  ("series" "Series in which the book appeared")
251                  ("address" "Address of the publisher")
252                  ("edition" "Edition of the book as a capitalized English word")
253                  ("month" "Month of the publication as a string (remove braces)")
254                  ("note" "Remarks to be put at the end of the \\bibitem")))))
255     ("Booklet" . (((("title" "Title of the booklet (BibTeX converts it to lowercase)"))
256                    (("author" "Author1 [and Author2 ...] [and others]")
257                     ("howpublished" "The way in which the booklet was published")
258                     ("address" "Address of the publisher")
259                     ("month" "Month of the publication as a string (remove braces)")
260                     ("year" "Year of publication")
261                     ("note" "Remarks to be put at the end of the \\bibitem")))))
262     ("InBook" . (((("author" "Author1 [and Author2 ...] [and others]" "" t)
263                    ("editor" "Editor1 [and Editor2 ...] [and others]" "" t)
264                    ("title" "Title of the book")
265                    ("chapter" "Chapter in the book")
266                    ("publisher" "Publishing company")
267                    ("year" "Year of publication"))
268                   (("volume" "Volume of the book in the series")
269                    ("number" "Number of the book in a small series (overwritten by volume)")
270                    ("series" "Series in which the book appeared")
271                    ("type" "Word to use instead of \"chapter\"")
272                    ("address" "Address of the publisher")
273                    ("edition" "Edition of the book as a capitalized English word")
274                    ("month" "Month of the publication as a string (remove braces)")
275                    ("pages" "Pages in the book")
276                    ("note" "Remarks to be put at the end of the \\bibitem")))
277                  ((("author" "Author1 [and Author2 ...] [and others]" "" t)
278                    ("editor" "Editor1 [and Editor2 ...] [and others]" "" t)
279                    ("title" "Title of the book")
280                    ("chapter" "Chapter in the book"))
281                   (("pages" "Pages in the book")
282                    ("publisher" "Publishing company")
283                    ("year" "Year of publication")
284                    ("volume" "Volume of the book in the series")
285                    ("number" "Number of the book in a small series (overwritten by volume)")
286                    ("series" "Series in which the book appeared")
287                    ("type" "Word to use instead of \"chapter\"")
288                    ("address" "Address of the publisher")
289                    ("edition" "Edition of the book as a capitalized English word")
290                    ("month" "Month of the publication as a string (remove braces)")
291                    ("note" "Remarks to be put at the end of the \\bibitem")))))
292     ("InCollection" . (((("author" "Author1 [and Author2 ...] [and others]")
293                          ("title" "Title of the article in book (BibTeX converts it to lowercase)")
294                          ("booktitle" "Name of the book")
295                          ("publisher" "Publishing company")
296                          ("year" "Year of publication"))
297                         (("editor" "Editor1 [and Editor2 ...] [and others]")
298                          ("volume" "Volume of the book in the series")
299                          ("number" "Number of the book in a small series (overwritten by volume)")
300                          ("series" "Series in which the book appeared")
301                          ("type" "Word to use instead of \"chapter\"")
302                          ("chapter" "Chapter in the book")
303                          ("pages" "Pages in the book")
304                          ("address" "Address of the publisher")
305                          ("edition" "Edition of the book as a capitalized English word")
306                          ("month" "Month of the publication as a string (remove braces)")
307                          ("note" "Remarks to be put at the end of the \\bibitem")))
308                        ((("author" "Author1 [and Author2 ...] [and others]")
309                          ("title" "Title of the article in book (BibTeX converts it to lowercase)")
310                          ("booktitle" "Name of the book"))
311                         (("pages" "Pages in the book")
312                          ("publisher" "Publishing company")
313                          ("year" "Year of publication")
314                          ("editor" "Editor1 [and Editor2 ...] [and others]")
315                          ("volume" "Volume of the book in the series")
316                          ("number" "Number of the book in a small series (overwritten by volume)")
317                          ("series" "Series in which the book appeared")
318                          ("type" "Word to use instead of \"chapter\"")
319                          ("chapter" "Chapter in the book")
320                          ("address" "Address of the publisher")
321                          ("edition" "Edition of the book as a capitalized English word")
322                          ("month" "Month of the publication as a string (remove braces)")
323                          ("note" "Remarks to be put at the end of the \\bibitem")))))
324     ("InProceedings" . (((("author" "Author1 [and Author2 ...] [and others]")
325                           ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)")
326                           ("booktitle" "Name of the conference proceedings")
327                           ("year" "Year of publication"))
328                          (("editor" "Editor1 [and Editor2 ...] [and others]")
329                           ("volume" "Volume of the conference proceedings in the series")
330                           ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
331                           ("series" "Series in which the conference proceedings appeared")
332                           ("pages" "Pages in the conference proceedings")
333                           ("address" "Location of the Proceedings")
334                           ("month" "Month of the publication as a string (remove braces)")
335                           ("organization" "Sponsoring organization of the conference")
336                           ("publisher" "Publishing company, its location")
337                           ("note" "Remarks to be put at the end of the \\bibitem")))
338                         ((("author" "Author1 [and Author2 ...] [and others]")
339                           ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)"))
340                          (("booktitle" "Name of the conference proceedings")
341                           ("pages" "Pages in the conference proceedings")
342                           ("year" "Year of publication")
343                           ("editor" "Editor1 [and Editor2 ...] [and others]")
344                           ("volume" "Volume of the conference proceedings in the series")
345                           ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
346                           ("series" "Series in which the conference proceedings appeared")
347                           ("address" "Location of the Proceedings")
348                           ("month" "Month of the publication as a string (remove braces)")
349                           ("organization" "Sponsoring organization of the conference")
350                           ("publisher" "Publishing company, its location")
351                           ("note" "Remarks to be put at the end of the \\bibitem")))))
352     ("Manual" . (((("title" "Title of the manual"))
353                   (("author" "Author1 [and Author2 ...] [and others]")
354                    ("organization" "Publishing organization of the manual")
355                    ("address" "Address of the organization")
356                    ("edition" "Edition of the manual as a capitalized English word")
357                    ("month" "Month of the publication as a string (remove braces)")
358                    ("year" "Year of publication")
359                    ("note" "Remarks to be put at the end of the \\bibitem")))))
360     ("MastersThesis" . (((("author" "Author1 [and Author2 ...] [and others]")
361                           ("title" "Title of the master\'s thesis (BibTeX converts it to lowercase)")
362                           ("school" "School where the master\'s thesis was written")
363                           ("year" "Year of publication"))
364                          (("type" "Type of the master\'s thesis (if other than \"Master\'s thesis\")")
365                           ("address" "Address of the school (if not part of field \"school\") or country")
366                           ("month" "Month of the publication as a string (remove braces)")
367                           ("note" "Remarks to be put at the end of the \\bibitem")))))
368     ("Misc" . ((()
369                 (("author" "Author1 [and Author2 ...] [and others]")
370                  ("title" "Title of the work (BibTeX converts it to lowercase)")
371                  ("howpublished" "The way in which the work was published")
372                  ("month" "Month of the publication as a string (remove braces)")
373                  ("year" "Year of publication")
374                  ("note" "Remarks to be put at the end of the \\bibitem")))))
375     ("PhdThesis" . (((("author" "Author1 [and Author2 ...] [and others]")
376                       ("title" "Title of the PhD. thesis")
377                       ("school" "School where the PhD. thesis was written")
378                       ("year" "Year of publication"))
379                      (("type" "Type of the PhD. thesis")
380                       ("address" "Address of the school (if not part of field \"school\") or country")
381                       ("month" "Month of the publication as a string (remove braces)")
382                       ("note" "Remarks to be put at the end of the \\bibitem")))))
383     ("Proceedings" . (((("title" "Title of the conference proceedings")
384                         ("year" "Year of publication"))
385                        (("booktitle" "Title of the proceedings for cross references")
386                         ("editor" "Editor1 [and Editor2 ...] [and others]")
387                         ("volume" "Volume of the conference proceedings in the series")
388                         ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
389                         ("series" "Series in which the conference proceedings appeared")
390                         ("address" "Location of the Proceedings")
391                         ("month" "Month of the publication as a string (remove braces)")
392                         ("organization" "Sponsoring organization of the conference")
393                         ("publisher" "Publishing company, its location")
394                         ("note" "Remarks to be put at the end of the \\bibitem")))))
395     ("TechReport" . (((("author" "Author1 [and Author2 ...] [and others]")
396                        ("title" "Title of the technical report (BibTeX converts it to lowercase)")
397                        ("institution" "Sponsoring institution of the report")
398                        ("year" "Year of publication"))
399                       (("type" "Type of the report (if other than \"technical report\")")
400                        ("number" "Number of the technical report")
401                        ("address" "Address of the institution (if not part of field \"institution\") or country")
402                        ("month" "Month of the publication as a string (remove braces)")
403                        ("note" "Remarks to be put at the end of the \\bibitem")))))
404     ("Unpublished" . (((("author" "Author1 [and Author2 ...] [and others]")
405                         ("title" "Title of the unpublished work (BibTeX converts it to lowercase)")
406                         ("note" "Remarks to be put at the end of the \\bibitem"))
407                        (("month" "Month of the publication as a string (remove braces)")
408                         ("year" "Year of publication")))))
409     )
410
411   "Defines entry types and their associated fields.
412 List of
413 (ENTRY-NAME (REQUIRED OPTIONAL) (CROSSREF-REQUIRED CROSSREF-OPTIONAL))
414 triples.
415 If the third element is nil, the first pair is always used.
416 If not, the second pair is used in the case of presence of a crossref
417 field and the third in the case of absence.
418 REQUIRED, OPTIONAL, CROSSREF-REQUIRED and CROSSREF-OPTIONAL are lists.
419 Each element of these lists is a list of the form
420 (FIELD-NAME COMMENT-STRING INIT ALTERNATIVE-FLAG).
421 COMMENT-STRING, INIT, and ALTERNATIVE-FLAG are optional.
422 FIELD-NAME is the name of the field, COMMENT-STRING the comment to
423 appear in the echo area, INIT is either the initial content of the
424 field or a function, which is called to determine the initial content
425 of the field, and ALTERNATIVE-FLAG (either nil or t) marks if the
426 field is an alternative.  ALTERNATIVE-FLAG may be t only in the
427 REQUIRED or CROSSREF-REQUIRED lists.")
428
429 (defvar bibtex-comment-start "@Comment ")
430
431 (defcustom bibtex-add-entry-hook nil
432   "List of functions to call when entry has been inserted."
433   :group 'bibtex
434   :type 'hook)
435
436 (defcustom bibtex-predefined-month-strings
437   '(
438     ("jan") ("feb") ("mar") ("apr") ("may") ("jun")
439     ("jul") ("aug") ("sep") ("oct") ("nov") ("dec")
440     )
441   "Alist of month string definitions.
442 Should contain all strings used for months in the BibTeX style files.
443 Each element is a list with just one element: the string."
444   :group 'bibtex
445   :type '(repeat
446           (list string)))
447
448 (defcustom bibtex-predefined-strings
449   (append
450    bibtex-predefined-month-strings
451    '(
452      ("acmcs") ("acta") ("cacm") ("ibmjrd") ("ibmsj") ("ieeese")
453      ("ieeetc") ("ieeetcad") ("ipl") ("jacm") ("jcss") ("scp")
454      ("sicomp") ("tcs") ("tocs") ("tods") ("tog") ("toms") ("toois")
455      ("toplas")
456      ))
457   "Alist of string definitions.
458 Should contain the strings defined in the BibTeX style files.  Each
459 element is a list with just one element: the string."
460   :group 'bibtex
461   :type '(repeat
462           (list string)))
463
464 (defcustom bibtex-string-files nil
465   "*List of BibTeX files containing string definitions.
466 Those files must be specified using pathnames relative to the
467 directories specified in `bibtex-string-file-path'.  This variable is only
468 evaluated when BibTeX mode is entered (i.e., when loading the BibTeX
469 file)."
470   :group 'bibtex
471   :type '(repeat file))
472
473 (defvar bibtex-string-file-path (getenv "BIBINPUTS")
474   "*Colon separated list of paths to search for `bibtex-string-files'.")
475
476 (defcustom bibtex-help-message t
477   "*If not nil print help messages in the echo area on entering a new field."
478   :group 'bibtex
479   :type 'boolean)
480
481 (defcustom bibtex-autokey-prefix-string ""
482   "*String to use as a prefix for all generated keys.
483 See the documentation of function `bibtex-generate-autokey' for more detail."
484   :group 'bibtex-autokey
485   :type 'string)
486
487 (defcustom bibtex-autokey-names 1
488   "*Number of names to use for the automatically generated reference key.
489 If this is variable is nil, all names are used.
490 Possibly more names are used according to `bibtex-autokey-names-stretch'.
491 See the documentation of function `bibtex-generate-autokey' for more detail."
492   :group 'bibtex-autokey
493   :type '(choice (const :tag "All" infty)
494                  integer))
495
496 (defcustom bibtex-autokey-names-stretch 0
497   "*Number of names that can additionally be used.
498 These names are used only, if all names are used then.
499 See the documentation of function `bibtex-generate-autokey' for details."
500   :group 'bibtex-autokey
501   :type 'integer)
502
503 (defcustom bibtex-autokey-additional-names ""
504   "*String to prepend to the generated key if not all names could be used.
505 See the documentation of function `bibtex-generate-autokey' for details."
506   :group 'bibtex-autokey
507   :type 'string)
508
509 (defvar bibtex-autokey-transcriptions
510   '(
511     ;; language specific characters
512     ("\\\\aa" "a")
513     ("\\\\AA" "A")
514     ("\\\"a\\|\\\\\\\"a\\|\\\\ae" "ae")
515     ("\\\"A\\|\\\\\\\"A\\|\\\\AE" "Ae")
516     ("\\\\i" "i")
517     ("\\\\j" "j")
518     ("\\\\l" "l")
519     ("\\\\L" "L")
520     ("\\\"o\\|\\\\\\\"o\\|\\\\o\\|\\\\oe" "oe")
521     ("\\\"O\\|\\\\\\\"O\\|\\\\O\\|\\\\OE" "Oe")
522     ("\\\"s\\|\\\\\\\"s" "ss")
523     ("\\\"u\\|\\\\\\\"u" "ue")
524     ("\\\"U\\|\\\\\\\"U" "Ue")
525     ;; accents
526     ("\\\\`\\|\\\\'\\|\\\\\\^\\|\\\\~\\|\\\\=\\|\\\\\\.\\|\\\\u\\|\\\\v\\|\\\\H\\|\\\\t\\|\\\\c\\|\\\\d\\|\\\\b" "")
527     ;; braces
528     ("{" "") ("}" ""))
529   "Alist of (old-regexp new-string) pairs.
530 Used by the default values of `bibtex-autokey-name-change-strings' and
531 `bibtex-autokey-titleword-change-strings'.  Defaults to translating some
532 language specific characters to their ASCII transcriptions, and
533 removing any character accents.")
534
535 (defcustom bibtex-autokey-name-change-strings
536   bibtex-autokey-transcriptions
537   "Alist of (OLD-REGEXP NEW-STRING) pairs.
538 Any part of name matching a OLD-REGEXP is replaced by NEW-STRING.
539 Case is significant in OLD-REGEXP.  All regexps are tried in the
540 order in which they appear in the list, so be sure to avoid inifinite
541 loops here.
542 See the documentation of function `bibtex-generate-autokey' for details."
543   :group 'bibtex-autokey
544   :type '(repeat
545           (list (regexp :tag "Old")
546                 (string :tag "New"))))
547
548 (defcustom bibtex-autokey-name-case-convert 'downcase
549   "*Function called for each name to perform case conversion.
550 See the documentation of function `bibtex-generate-autokey' for more detail."
551   :group 'bibtex-autokey
552   :type '(choice (const :tag "Preserve case" identity)
553                  (const :tag "Downcase" downcase)
554                  (const :tag "Capitalize" capitalize)
555                  (const :tag "Upcase" upcase)
556                  (function :tag "Conversion function")))
557
558 (defcustom bibtex-autokey-name-length 'infty
559   "*Number of characters from name to incorporate into key.
560 If this is set to anything but a number, all characters are used.
561 See the documentation of function `bibtex-generate-autokey' for details."
562   :group 'bibtex-autokey
563   :type '(choice (const :tag "All" infty)
564                  integer))
565
566 (defcustom bibtex-autokey-name-separator ""
567   "*String that comes between any two names in the key.
568 See the documentation of function `bibtex-generate-autokey' for details."
569   :group 'bibtex-autokey
570   :type 'string)
571
572 (defcustom bibtex-autokey-year-length 2
573   "*Number of rightmost digits from the year field to incorporate into key.
574 See the documentation of function `bibtex-generate-autokey' for details."
575   :group 'bibtex-autokey
576   :type 'integer)
577
578 (defcustom bibtex-autokey-year-use-crossref-entry t
579   "*If non-nil use year field from crossreferenced entry if necessary.
580 If this variable is non-nil and the current entry has no year, but a
581 valid crossref entry, the year field from the crossreferenced entry is
582 used.
583 See the documentation of function `bibtex-generate-autokey' for details."
584   :group 'bibtex-autokey
585   :type 'boolean)
586
587 (defcustom bibtex-autokey-titlewords 5
588   "*Number of title words to use for the automatically generated reference key.
589 If this is set to anything but a number, all title words are used.
590 Possibly more words from the title are used according to
591 `bibtex-autokey-titlewords-stretch'.
592 See the documentation of function `bibtex-generate-autokey' for details."
593   :group 'bibtex-autokey
594   :type '(choice (const :tag "All" infty)
595                  integer))
596
597 (defcustom bibtex-autokey-title-terminators
598   '("\\." "!"  "\\?" ":" ";" "--")
599   "*Regexp list defining the termination of the main part of the title.
600 Case of the regexps is ignored.
601 See the documentation of function `bibtex-generate-autokey' for details."
602   :group 'bibtex-autokey
603   :type '(repeat regexp))
604
605 (defcustom bibtex-autokey-titlewords-stretch 2
606   "*Number of words that can additionally be used from the title.
607 These words are used only, if a sentence from the title can be ended then.
608 See the documentation of function `bibtex-generate-autokey' for details."
609   :group 'bibtex-autokey
610   :type 'integer)
611
612 (defcustom bibtex-autokey-titleword-ignore
613   '("A" "An" "On" "The" "Eine?" "Der" "Die" "Das"
614     "[^A-Z].*" ".*[^a-zA-Z0-9].*")
615   "*Determines words from the title that are not to be used in the key.
616 Each item of the list is a regexp.  If a word of the title matchs a
617 regexp from that list, it is not included in the title part of the key.
618 See the documentation of function `bibtex-generate-autokey' for details."
619   :group 'bibtex-autokey
620   :type '(repeat regexp))
621
622 (defcustom bibtex-autokey-titleword-case-convert 'downcase
623   "*Function called for each titleword to perform case conversion.
624 See the documentation of function `bibtex-generate-autokey' for more detail."
625   :group 'bibtex-autokey
626   :type '(choice (const :tag "Preserve case" identity)
627                  (const :tag "Downcase" downcase)
628                  (const :tag "Capitalize" capitalize)
629                  (const :tag "Upcase" upcase)
630                  (function :tag "Conversion function")))
631
632 (defcustom bibtex-autokey-titleword-abbrevs nil
633   "*Determines exceptions to the usual abbreviation mechanism.
634 An alist of (OLD-REGEXP NEW-STRING) pairs.  Case is ignored
635 in matching against OLD-REGEXP, and the first matching pair is used.
636 See the documentation of function `bibtex-generate-autokey' for details.")
637
638 (defcustom bibtex-autokey-titleword-change-strings
639   bibtex-autokey-transcriptions
640   "Alist of (OLD-REGEXP NEW-STRING) pairs.
641 Any part of title word matching a OLD-REGEXP is replaced by NEW-STRING.
642 Case is significant in OLD-REGEXP.  All regexps are tried in the
643 order in which they appear in the list, so be sure to avoid inifinite
644 loops here.
645 See the documentation of function `bibtex-generate-autokey' for details."
646   :group 'bibtex-autokey
647   :type '(repeat
648           (list (regexp :tag "Old")
649                 (string :tag "New"))))
650
651 (defcustom bibtex-autokey-titleword-length 5
652   "*Number of characters from title words to incorporate into key.
653 If this is set to anything but a number, all characters are used.
654 See the documentation of function `bibtex-generate-autokey' for details."
655   :group 'bibtex-autokey
656   :type '(choice (const :tag "All" infty)
657                  integer))
658
659 (defcustom bibtex-autokey-titleword-separator "_"
660   "*String to be put between the title words.
661 See the documentation of function `bibtex-generate-autokey' for details."
662   :group 'bibtex-autokey
663   :type 'string)
664
665 (defcustom bibtex-autokey-name-year-separator ""
666   "*String to be put between name part and year part of key.
667 See the documentation of function `bibtex-generate-autokey' for details."
668   :group 'bibtex-autokey
669   :type 'string)
670
671 (defcustom bibtex-autokey-year-title-separator ":_"
672   "*String to be put between name part and year part of key.
673 See the documentation of function `bibtex-generate-autokey' for details."
674   :group 'bibtex-autokey
675   :type 'string)
676
677 (defcustom bibtex-autokey-edit-before-use t
678   "*If non-nil, user is allowed to edit the generated key before it is used."
679   :group 'bibtex-autokey
680   :type 'boolean)
681
682 (defcustom bibtex-autokey-before-presentation-function nil
683   "Function to call before the generated key is presented.
684 If non-nil this should be a single function, which is called before
685 the generated key is presented (in entry or, if
686 `bibtex-autokey-edit-before-use' is t, in minibuffer).  This function
687 must take one argument (the automatically generated key), and must
688 return with a string (the key to use)."
689   :group 'bibtex-autokey
690   :type '(choice (const nil) function))
691
692 (defcustom bibtex-entry-offset 0
693   "*Offset for BibTeX entries.
694 Added to the value of all other variables which determine colums."
695   :group 'bibtex
696   :type 'integer)
697
698 (defcustom bibtex-field-indentation 2
699   "*Starting column for the name part in BibTeX fields."
700   :group 'bibtex
701   :type 'integer)
702
703 (defcustom bibtex-text-indentation
704   (+
705    bibtex-field-indentation
706    (length "organization = "))
707   "*Starting column for the text part in BibTeX fields.
708 Should be equal to the space needed for the longest name part."
709   :group 'bibtex
710   :type 'integer)
711
712 (defcustom bibtex-contline-indentation
713   (+ bibtex-text-indentation 1)
714   "*Starting column for continuation lines of BibTeX fields."
715   :group 'bibtex
716   :type 'integer)
717
718 (defcustom bibtex-align-at-equal-sign nil
719   "*If non-nil, align fields at equal sign instead of field text.
720 If non-nil, the column for the equal sign is
721 the value of `bibtex-text-indentation', minus 2."
722   :group 'bibtex
723   :type 'boolean)
724
725 (defcustom bibtex-comma-after-last-field nil
726   "*If non-nil, a comma is put at end of last field in the entry template."
727   :group 'bibtex
728   :type 'boolean)
729
730 ;; bibtex-font-lock-keywords is a user option as well, but since the
731 ;; patterns used to define this variable are defined in a later
732 ;; section of this file, it is defined later.
733 \f
734 ;; Special support taking care of variants
735 (if (boundp 'mark-active)
736     (defun bibtex-mark-active ()
737       ;; In Emacs mark-active indicates if mark is active.
738       mark-active)
739   (defun bibtex-mark-active ()
740     ;; In XEmacs (mark) returns nil when not active.
741     (if zmacs-regions (mark) (mark t))))
742
743 (if (fboundp 'run-with-idle-timer)
744     ;; timer.el is distributed with Emacs
745     (fset 'bibtex-run-with-idle-timer 'run-with-idle-timer)
746   ;; timer.el is not distributed with XEmacs
747   ;; Notice that this does not (yet) pass the arguments, but they
748   ;; are not used (yet) in bibtex.el. Fix if needed.
749   (defun bibtex-run-with-idle-timer (secs repeat function &rest args)
750     (start-itimer "bibtex" function secs (if repeat secs nil) t)))
751
752 \f
753 ;; Support for hideshow minor mode
754 (defun bibtex-hs-forward-sexp (arg)
755   "Replacement for `forward-sexp' to be used by `hs-minor-mode'."
756   (if (< arg 0)
757       (backward-sexp 1)
758     (if (looking-at "@\\S(*\\s(")
759         (progn
760           (goto-char (match-end 0))
761           (forward-char -1)
762           (forward-sexp 1))
763       (forward-sexp 1))))
764
765 (add-to-list
766  'hs-special-modes-alist
767  '(bibtex-mode "@\\S(*\\s(" "\\s)" nil bibtex-hs-forward-sexp nil))
768
769 \f
770 ;; Syntax Table, Keybindings and BibTeX Entry List
771 (defvar bibtex-mode-syntax-table
772   (let ((st (make-syntax-table)))
773     (modify-syntax-entry ?\" "\"" st)
774     (modify-syntax-entry ?$ "$$  " st)
775     (modify-syntax-entry ?% "<   " st)
776     (modify-syntax-entry ?' "w   " st)
777     (modify-syntax-entry ?@ "w   " st)
778     (modify-syntax-entry ?\\ "\\" st)
779     (modify-syntax-entry ?\f ">   " st)
780     (modify-syntax-entry ?\n ">   " st)
781     (modify-syntax-entry ?~ " " st)
782     st))
783
784 (defvar bibtex-mode-map
785   (let ((km (make-sparse-keymap)))
786     ;; The Key `C-c&' is reserved for reftex.el
787     (define-key km "\t" 'bibtex-find-text)
788     (define-key km "\n" 'bibtex-next-field)
789     (define-key km "\M-\t" 'bibtex-complete-string)
790     (define-key km [(meta tab)] 'bibtex-complete-key)
791     (define-key km "\C-c\"" 'bibtex-remove-delimiters)
792     (define-key km "\C-c{" 'bibtex-remove-delimiters)
793     (define-key km "\C-c}" 'bibtex-remove-delimiters)
794     (define-key km "\C-c\C-c" 'bibtex-clean-entry)
795     (define-key km "\C-c\C-q" 'bibtex-fill-entry)
796     (define-key km "\C-c?" 'bibtex-print-help-message)
797     (define-key km "\C-c\C-p" 'bibtex-pop-previous)
798     (define-key km "\C-c\C-n" 'bibtex-pop-next)
799     (define-key km "\C-c\C-k" 'bibtex-kill-field)
800     (define-key km "\C-c\M-k" 'bibtex-copy-field-as-kill)
801     (define-key km "\C-c\C-w" 'bibtex-kill-entry)
802     (define-key km "\C-c\M-w" 'bibtex-copy-entry-as-kill)
803     (define-key km "\C-c\C-y" 'bibtex-yank)
804     (define-key km "\C-c\M-y" 'bibtex-yank-pop)
805     (define-key km "\C-c\C-d" 'bibtex-empty-field)
806     (define-key km "\C-c\C-f" 'bibtex-make-field)
807     (define-key km "\C-c$" 'bibtex-ispell-abstract)
808     (define-key km "\M-\C-a" 'bibtex-beginning-of-entry)
809     (define-key km "\M-\C-e" 'bibtex-end-of-entry)
810     (define-key km "\C-\M-l" 'bibtex-reposition-window)
811     (define-key km "\C-\M-h" 'bibtex-mark-entry)
812     (define-key km "\C-c\C-b" 'bibtex-entry)
813     (define-key km "\C-c\C-rn" 'bibtex-narrow-to-entry)
814     (define-key km "\C-c\C-rw" 'widen)
815     (define-key km "\C-c\C-o" 'bibtex-remove-OPT-or-ALT)
816     (define-key km "\C-c\C-e\C-i" 'bibtex-InProceedings)
817     (define-key km "\C-c\C-ei" 'bibtex-InCollection)
818     (define-key km "\C-c\C-eI" 'bibtex-InBook)
819     (define-key km "\C-c\C-e\C-a" 'bibtex-Article)
820     (define-key km "\C-c\C-e\C-b" 'bibtex-InBook)
821     (define-key km "\C-c\C-eb" 'bibtex-Book)
822     (define-key km "\C-c\C-eB" 'bibtex-Booklet)
823     (define-key km "\C-c\C-e\C-c" 'bibtex-InCollection)
824     (define-key km "\C-c\C-e\C-m" 'bibtex-Manual)
825     (define-key km "\C-c\C-em" 'bibtex-MastersThesis)
826     (define-key km "\C-c\C-eM" 'bibtex-Misc)
827     (define-key km "\C-c\C-e\C-p" 'bibtex-InProceedings)
828     (define-key km "\C-c\C-ep" 'bibtex-Proceedings)
829     (define-key km "\C-c\C-eP" 'bibtex-PhdThesis)
830     (define-key km "\C-c\C-e\M-p" 'bibtex-Preamble)
831     (define-key km "\C-c\C-e\C-s" 'bibtex-String)
832     (define-key km "\C-c\C-e\C-t" 'bibtex-TechReport)
833     (define-key km "\C-c\C-e\C-u" 'bibtex-Unpublished)
834     km))
835
836 (easy-menu-define
837  bibtex-edit-menu bibtex-mode-map "BibTeX-Edit Menu in BibTeX mode"
838  '("BibTeX-Edit"
839    ("Moving inside an Entry"
840     ["End of Field" bibtex-find-text t]
841     ["Next Field" bibtex-next-field t]
842     ["Beginning of Entry" bibtex-beginning-of-entry t]
843     ["End of Entry" bibtex-end-of-entry t])
844    ("Operating on Current Entry"
845     ["Fill Entry" bibtex-fill-entry t]
846     ["Clean Entry" bibtex-clean-entry t]
847     "--"
848     ["Kill Entry" bibtex-kill-entry t]
849     ["Copy Entry to Kill Ring" bibtex-copy-entry-as-kill t]
850     ["Paste Most Recently Killed Entry" bibtex-yank t]
851     ["Paste Previously Killed Entry" bibtex-yank-pop t]
852     "--"
853     ["Ispell Entry" bibtex-ispell-entry t]
854     ["Ispell Entry Abstract" bibtex-ispell-abstract t]
855     ["Narrow to Entry" bibtex-narrow-to-entry t]
856     "--"
857     ["View Cite Locations (RefTeX)" reftex-view-crossref-from-bibtex
858      (fboundp 'reftex-view-crossref-from-bibtex)])
859    ("Operating on Current Field"
860     ["Remove Delimiters" bibtex-remove-delimiters t]
861     ["Remove OPT or ALT Prefix" bibtex-remove-OPT-or-ALT t]
862     ["Clear Field" bibtex-empty-field t]
863     "--"
864     ["Kill Field" bibtex-kill-field t]
865     ["Copy Field to Kill Ring" bibtex-copy-field-as-kill t]
866     ["Paste Most Recently Killed Field" bibtex-yank t]
867     ["Paste Previously Killed Field" bibtex-yank-pop t]
868     "--"
869     ["Make New Field" bibtex-make-field t]
870     "--"
871     ["Snatch from Similar Following Field" bibtex-pop-next t]
872     ["Snatch from Similar Preceding Field" bibtex-pop-previous t]
873     "--"
874     ["String Complete" bibtex-complete-string t]
875     ["Key Complete" bibtex-complete-key t]
876     "--"
877     ["Help about Current Field" bibtex-print-help-message t])
878    ("Operating on Buffer or Region"
879     ["Validate Entries" bibtex-validate t]
880     ["Sort Entries" bibtex-sort-buffer t]
881     ["Reformat Entries" bibtex-reformat t]
882     ["Count Entries" bibtex-count-entries t])
883    ("Miscellaneous"
884     ["Convert Alien Buffer" bibtex-convert-alien t]
885     ["Submit Bug Report" bibtex-submit-bug-report t])))
886
887 (easy-menu-define
888  bibtex-entry-menu bibtex-mode-map "Entry-Types Menu in BibTeX mode"
889  (list "Entry-Types"
890        ["Article in Journal" bibtex-Article t]
891        ["Article in Conference Proceedings" bibtex-InProceedings t]
892        ["Article in a Collection" bibtex-InCollection t]
893        ["Chapter or Pages in a Book" bibtex-InBook t]
894        ["Conference Proceedings" bibtex-Proceedings t]
895        ["Book" bibtex-Book t]
896        ["Booklet (Bound, but no Publisher/Institution)" bibtex-Booklet t]
897        ["PhD. Thesis" bibtex-PhdThesis t]
898        ["Master's Thesis" bibtex-MastersThesis t]
899        ["Technical Report" bibtex-TechReport t]
900        ["Technical Manual" bibtex-Manual t]
901        ["Unpublished" bibtex-Unpublished t]
902        ["Miscellaneous" bibtex-Misc t]
903        ["String" bibtex-String t]
904        ["Preamble" bibtex-Preamble t]))
905
906 \f
907 ;; Internal Variables
908
909 (defvar bibtex-pop-previous-search-point nil)
910 ;; Next point where bibtex-pop-previous starts looking for a similar
911 ;; entry.
912
913 (defvar bibtex-pop-next-search-point nil)
914 ;; Next point where bibtex-pop-next starts looking for a similar entry.
915
916 (defvar bibtex-field-kill-ring nil)
917 ;; Ring of least recently killed fields. At most
918 ;; bibtex-field-kill-ring-max items are kept here.
919
920 (defvar bibtex-field-kill-ring-yank-pointer nil)
921 ;; The tail of bibtex-field-kill-ring whose car is the last item yanked.
922
923 (defvar bibtex-entry-kill-ring nil)
924 ;; Ring of least recently killed entries. At most
925 ;; bibtex-entry-kill-ring-max items are kept here.
926
927 (defvar bibtex-entry-kill-ring-yank-pointer nil)
928 ;; The tail of bibtex-entry-kill-ring whose car is the last item yanked.
929
930 (defvar bibtex-last-kill-command nil)
931 ;; Holds the type of the last kill command (either 'field or 'entry)
932
933 (defvar bibtex-strings nil)
934 ;; Candidates for bibtex-complete-string. Initialized from
935 ;; bibtex-predefined-strings and bibtex-string-files.
936 (make-variable-buffer-local 'bibtex-strings)
937
938 (defvar bibtex-reference-keys nil)
939 ;; Candidates for TAB completion when entering a reference key using
940 ;; the minibuffer. Also used for bibtex-complete-key. Initialized in
941 ;; bibtex-mode and updated for each new entry.
942 (make-variable-buffer-local 'bibtex-reference-keys)
943
944 (defvar bibtex-buffer-last-parsed-tick nil)
945 ;; Remembers the value returned by buffer-modified-tick when buffer
946 ;; was parsed for keys the last time.
947 (make-variable-buffer-local 'bibtex-buffer-last-parsed-tick)
948
949 (defvar bibtex-parse-idle-timer nil)
950 ;; Stores if timer is already installed
951
952 (defvar bibtex-progress-lastperc nil)
953 ;; Holds the last reported percentage for the progress message
954
955 (defvar bibtex-progress-lastmes nil)
956 ;; Holds the last reported progress message
957
958 (defvar bibtex-progress-interval nil)
959 ;; Holds the chosen interval
960
961 (defvar bibtex-key-history nil)
962 ;; Used to store the history list for reading keys
963
964 (defvar bibtex-entry-type-history nil)
965 ;; Used to store the history list for reading entry types
966
967 (defvar bibtex-field-history nil)
968 ;; Used to store the history list for reading field names
969
970 (defvar bibtex-reformat-previous-options nil)
971 ;; Used to store the last reformat options given
972
973 (defvar bibtex-reformat-previous-reference-keys nil)
974 ;; Used to store the last reformat reference keys option given
975
976 \f
977 ;; Functions to Parse the BibTeX Entries
978
979 (defconst bibtex-field-name "[^\"#%'(),={} \t\n0-9][^\"#%'(),={} \t\n]*")
980 ;; Regexp defining the name part of a BibTeX field.
981
982 (defconst bibtex-entry-type (concat "@" bibtex-field-name))
983 ;; Regexp defining the type part of a BibTeX entry.
984
985 (defconst bibtex-reference-key "[][a-zA-Z0-9.:;?!`'/*@+=|()<>&_^$-]+")
986 ;; Regexp defining the reference key part of a BibTeX entry
987
988 (defun bibtex-parse-nested-braces (nesting-level)
989   "*Starting on an opening brace, find the corresponding closing brace.
990 When the function is called, NESTING-LEVEL has to be set to `0'."
991   (cond ((looking-at "{")
992          (search-forward-regexp "{[^{}]*")
993          (bibtex-parse-nested-braces (+ nesting-level 1)))
994         ((looking-at "}")
995          (forward-char 1)
996          (if (= nesting-level 1)
997              (point)
998            (search-forward-regexp "[^{}]*")
999            (bibtex-parse-nested-braces (- nesting-level 1))))
1000         (t nil)))
1001
1002 (defun bibtex-parse-field-string-braced ()
1003   "*Parse a field string enclosed by braces.
1004 The field string has to be syntactically correct, which means that the number
1005 of opening and closing braces has to match.  If this is the case, a pair
1006 containing the start and end position of the field string is returned, nil
1007 otherwise."
1008   (save-match-data
1009     (let ((starting-point (point))
1010           (end-point nil))
1011       (if (looking-at "{")
1012           (setq end-point (bibtex-parse-nested-braces 0)))
1013       (goto-char starting-point)
1014       (if end-point
1015           (cons starting-point end-point)
1016         nil))))
1017
1018 (defun bibtex-parse-quoted-string ()
1019   "*Starting on an opening quote, find the corresponding closing quote."
1020   (let ((rx (concat "\""
1021                         "\\("
1022                             "[^\"\\]"               ;; anything but quote or backslash
1023                             "\\|"
1024                             "\\("
1025                                 "\\\\\\(.\\|\n\\)"  ;; any backslash quoted character
1026                             "\\)"
1027                         "\\)*"
1028                     "\"")))
1029     (if (looking-at rx)
1030         (search-forward-regexp rx nil t)
1031       nil)))
1032
1033 (defun bibtex-parse-field-string-quoted ()
1034   "*Parse a field string enclosed by quotes.
1035 If a syntactically correct string is found, a pair containing the start and
1036 end position of the field string is returned, nil otherwise."
1037   (save-match-data
1038     (let ((starting-point (point))
1039           (end-point nil))
1040       (if (looking-at "\"")
1041           (setq end-point (bibtex-parse-quoted-string)))
1042       (goto-char starting-point)
1043       (if end-point
1044           (cons starting-point end-point)
1045         nil))))
1046
1047 (defun bibtex-parse-field-string ()
1048   "*Parse a field string enclosed by braces or quotes.
1049 If a syntactically correct string is found, a pair containing the start and
1050 end position of the field string is returned, nil otherwise."
1051   (save-match-data
1052     (let ((starting-point (point))
1053           (boundaries (or (bibtex-parse-field-string-braced)
1054                           (bibtex-parse-field-string-quoted))))
1055       (goto-char starting-point)
1056       boundaries)))
1057
1058 (defun bibtex-search-forward-field-string (bound)
1059   "*Search forward to find a field string enclosed by braces or quotes.
1060 If a syntactically correct string is found, a pair containing the start and
1061 end position of the field string is returned, nil otherwise.  The search is
1062 delimited by BOUND."
1063   (save-match-data
1064     (let ((starting-point (point))
1065           (boundaries nil))
1066       (while (and (not boundaries) (< (point) bound))
1067         (if (search-forward-regexp "[{\"]" bound 'move)
1068             (progn
1069               (goto-char (match-beginning 0))
1070               (let ((temp-boundaries (or (bibtex-parse-field-string-braced)
1071                                          (bibtex-parse-field-string-quoted))))
1072                 (if (and temp-boundaries (<= (cdr temp-boundaries) bound))
1073                     (setq boundaries temp-boundaries)
1074                   (forward-char 1))))))
1075       (goto-char starting-point)
1076       boundaries)))
1077
1078 (defun bibtex-parse-association (parse-lhs parse-rhs)
1079   "*Parse a string of the format <left hand side = right-hand-side>.
1080 The functions PARSE-LHS and PARSE-RHS are used to parse the corresponding
1081 substrings.  These functions are expected to return nil if parsing is not
1082 successfull.  If both functions return non-nil, a pair containing the returned
1083 values of the functions PARSE-LHS and PARSE-RHSis returned."
1084   (save-match-data
1085     (let ((starting-point (point))
1086           (left (funcall parse-lhs))
1087           (right nil))
1088       (if (and left (looking-at "[ \t\n]*=[ \t\n]*"))
1089           (progn
1090             (goto-char (match-end 0))
1091             (setq right (funcall parse-rhs))))
1092       (goto-char starting-point)
1093       (if (and left right)
1094           (cons left right)
1095         nil))))
1096
1097 (defvar bibtex-field-name-for-parsing nil)
1098 ;; Temporary variable storing the name string to be parsed by the callback
1099 ;; function bibtex-parse-field-name.
1100 (make-variable-buffer-local 'bibtex-field-name-for-parsing)
1101
1102 (defun bibtex-parse-field-name ()
1103   "*Parse the field name stored in bibtex-field-name-for-parsing.
1104 If the field name is found, return a triple consisting of the position of the
1105 very first character of the match, the actual starting position of the name
1106 part and end position of the match."
1107   (if (looking-at ",[ \t\n]*")
1108       (let ((start (point)))
1109         (goto-char (match-end 0))
1110         (if (looking-at bibtex-field-name-for-parsing)
1111             (let ((boundaries (list start (match-beginning 0) (match-end 0))))
1112               (goto-char (match-end 0))
1113               boundaries)))))
1114
1115 (defconst bibtex-field-const "[][a-zA-Z0-9.:;?!`'/*@+=|<>&_^$-]+")
1116 ;; Regexp defining a bibtex field constant
1117
1118 (defun bibtex-parse-field-text ()
1119   "*Parse the text part of a BibTeX field.
1120 The text part is either a string, or an empty string, or a constant followed
1121 by one or more <# (string|constant)> pairs.  If a syntactically correct text
1122 is found, a pair containing the start and end position of the text is
1123 returned, nil otherwise."
1124   (let ((starting-point (point))
1125         (end-point nil)
1126         (failure nil))
1127     (while (and (not end-point) (not failure))
1128       (if (looking-at bibtex-field-const)
1129           (goto-char (match-end 0))
1130         (let ((boundaries (bibtex-parse-field-string)))
1131           (if boundaries
1132               (goto-char (cdr boundaries))
1133             (setq failure t))))
1134       (if (not (looking-at "[ \t\n]*#[ \t\n]*"))
1135           (setq end-point (point))
1136         (goto-char (match-end 0))))
1137     (if (and (not failure) end-point)
1138         (cons starting-point end-point)
1139       nil)))
1140
1141 (defun bibtex-parse-field (name)
1142   "*Parse a BibTeX field of regexp NAME.
1143 If a syntactically correct field is found, a pair containing the boundaries of
1144 the name and text parts of the field is returned."
1145   (setq bibtex-field-name-for-parsing name)
1146   (bibtex-parse-association 'bibtex-parse-field-name
1147                             'bibtex-parse-field-text))
1148
1149 (defun bibtex-search-forward-field (name bound)
1150   "*Search forward to find a field of name NAME.
1151 If a syntactically correct field is found, a pair containing the boundaries of
1152 the name and text parts of the field is returned.  The search is limited by
1153 BOUND."
1154   (save-match-data
1155     (setq bibtex-field-name-for-parsing name)
1156     (let ((starting-point (point))
1157           (boundaries nil))
1158       (while (and (not boundaries)
1159                   (< (point) bound)
1160                   (search-forward "," bound t))
1161         (goto-char (match-beginning 0))
1162         (let ((temp-boundaries
1163                (bibtex-parse-association 'bibtex-parse-field-name
1164                                          'bibtex-parse-field-text)))
1165           (if (and temp-boundaries (<= (cdr (cdr temp-boundaries)) bound))
1166               (setq boundaries temp-boundaries)
1167             (forward-char 1))))
1168       (goto-char starting-point)
1169       boundaries)))
1170
1171 (defun bibtex-search-backward-field (name bound)
1172   "*Search backward to find a field of name NAME.
1173 If a syntactically correct field is found, a pair containing the boundaries of
1174 the name and text parts of the field is returned.  The search is limited by
1175 BOUND."
1176   (save-match-data
1177     (setq bibtex-field-name-for-parsing name)
1178     (let ((starting-point (point))
1179           (boundaries nil))
1180       (while (and (not boundaries)
1181                   (>= (point) bound)
1182                   (search-backward "," bound t))
1183         (let ((temp-boundaries
1184                (bibtex-parse-association 'bibtex-parse-field-name
1185                                          'bibtex-parse-field-text)))
1186           (if temp-boundaries
1187               (setq boundaries temp-boundaries))))
1188       (goto-char starting-point)
1189       boundaries)))
1190
1191 (defun bibtex-start-of-field (bounds)
1192   (car (car bounds)))
1193 (defun bibtex-end-of-field (bounds)
1194   (cdr (cdr bounds)))
1195 (defun bibtex-start-of-name-in-field (bounds)
1196   (car (cdr (car bounds))))
1197 (defun bibtex-end-of-name-in-field (bounds)
1198   (car (cdr (cdr (car bounds)))))
1199 (defun bibtex-start-of-text-in-field (bounds)
1200   (car (cdr bounds)))
1201 (defun bibtex-end-of-text-in-field (bounds)
1202   (cdr (cdr bounds)))
1203
1204 (defun bibtex-parse-string-prefix ()
1205   "*Parse the prefix part of a bibtex string, including the reference key.
1206 If the string prefix is found, return a triple consisting of the position of
1207 the very first character of the match, the actual starting position of the
1208 reference key and the end position of the match."
1209   (let* ((case-fold-search t))
1210     (if (looking-at "^[ \t]*@string[ \t\n]*[({][ \t\n]*")
1211         (let ((start (point)))
1212           (goto-char (match-end 0))
1213           (if (looking-at bibtex-reference-key)
1214               (let ((boundaries (list start (match-beginning 0) (match-end 0))))
1215                 (goto-char (match-end 0))
1216                 boundaries))))))
1217
1218 (defun bibtex-parse-string-postfix ()
1219   "*Parse the postfix part of a bibtex string, including the text.
1220 If the string postfix is found, return a triple consisting of the position of
1221 the actual starting and ending position of the text and the very last
1222 character of the string entry."
1223   (let* ((case-fold-search t)
1224          (text-boundaries (bibtex-parse-field-text)))
1225     (if text-boundaries
1226         (progn
1227           (goto-char (cdr text-boundaries))
1228           (if (looking-at "[ \t\n]*[})]")
1229               (let ((boundaries (list (car text-boundaries)
1230                                       (cdr text-boundaries)
1231                                       (match-end 0))))
1232                 (goto-char (match-end 0))
1233                 boundaries))))))
1234
1235 (defun bibtex-parse-string ()
1236   "*Parse a BibTeX string entry.
1237 If a syntactically correct entry is found, a pair containing the boundaries of
1238 the reference key and text parts of the entry is returned."
1239   (bibtex-parse-association 'bibtex-parse-string-prefix
1240                             'bibtex-parse-string-postfix))
1241
1242 (defun bibtex-search-forward-string ()
1243   "*Search forward to find a bibtex string entry.
1244 If a syntactically correct entry is found, a pair containing the boundaries of
1245 the reference key and text parts of the string is returned."
1246   (save-match-data
1247     (let* ((case-fold-search t)
1248            (starting-point (point))
1249            (boundaries nil))
1250       (while (and (not boundaries)
1251                   (search-forward-regexp
1252                    "^[ \t]*@string[ \t\n]*[({][ \t\n]*" nil t))
1253         (goto-char (match-beginning 0))
1254         (let ((temp-boundaries (bibtex-parse-string)))
1255           (if temp-boundaries
1256               (setq boundaries temp-boundaries)
1257             (forward-char 1))))
1258       (goto-char starting-point)
1259       boundaries)))
1260
1261 (defun bibtex-search-backward-string ()
1262   "*Search backward to find a bibtex string entry.
1263 If a syntactically correct entry is found, a pair containing the boundaries of
1264 the reference key and text parts of the field is returned."
1265   (save-match-data
1266     (let* ((case-fold-search t)
1267            (starting-point (point))
1268            (boundaries nil))
1269       (while (and (not boundaries)
1270                   (search-backward-regexp
1271                    "^[ \t]*@string[ \t\n]*[({][ \t\n]*" nil t))
1272         (goto-char (match-beginning 0))
1273         (let ((temp-boundaries (bibtex-parse-string)))
1274           (if temp-boundaries
1275               (setq boundaries temp-boundaries))))
1276       (goto-char starting-point)
1277       boundaries)))
1278
1279 (defun bibtex-end-of-string (bounds)
1280   (car (cdr (cdr (cdr bounds)))))
1281 (defun bibtex-start-of-reference-key-in-string (bounds)
1282   (car (cdr (car bounds))))
1283 (defun bibtex-end-of-reference-key-in-string (bounds)
1284   (car (cdr (cdr (car bounds)))))
1285 (defun bibtex-start-of-text-in-string (bounds)
1286   (car (cdr bounds)))
1287 (defun bibtex-end-of-text-in-string (bounds)
1288   (car (cdr (cdr bounds))))
1289
1290 (defconst bibtex-entry-head
1291   (concat "^[ \t]*\\("
1292           bibtex-entry-type
1293           "\\)[ \t]*[({][ \t\n]*\\("
1294           bibtex-reference-key
1295           "\\)"))
1296 ;; Regexp defining format of the header line of a BibTeX entry.
1297
1298 (defconst bibtex-entry-maybe-empty-head
1299   (concat bibtex-entry-head "?"))
1300 ;; Regexp defining format of the header line of a maybe empty
1301 ;; BibTeX entry (possibly without reference key).
1302
1303 (defconst bibtex-type-in-head 1)
1304 ;; The regexp subexpression number of the type part in
1305 ;; bibtex-entry-head.
1306
1307 (defconst bibtex-key-in-head 2)
1308 ;; The regexp subexpression number of the key part in
1309 ;; bibtex-entry-head.
1310
1311 (defconst bibtex-entry-postfix "[ \t\n]*,?[ \t\n]*[})]")
1312 ;; Regexp defining the postfix of a bibtex entry
1313
1314 (defconst bibtex-key-in-entry bibtex-key-in-head)
1315 ;; The regexp subexpression number of the key part in a bibtex entry.
1316
1317 (defvar bibtex-font-lock-keywords
1318   (list
1319    ;; entry type and reference key
1320    (list bibtex-entry-maybe-empty-head
1321          (list bibtex-type-in-head 'font-lock-function-name-face)
1322          (list bibtex-key-in-head 'font-lock-constant-face nil t))
1323    ;; comments
1324    (list
1325     (concat "^\\([ \t]*" bibtex-comment-start ".*\\)$")
1326     1 'font-lock-comment-face)
1327    ;; optional field names (treated as comments)
1328    (list
1329     (concat "^[ \t]*\\(OPT" bibtex-field-name "\\)[ \t]*=")
1330     1 'font-lock-comment-face)
1331    ;; field names
1332    (list (concat "^[ \t]*\\(" bibtex-field-name "\\)[ \t]*=")
1333          1 'font-lock-variable-name-face)
1334    "*Default expressions to highlight in BibTeX mode."))
1335 ;; now all needed patterns are defined
1336
1337
1338 \f
1339 ;; Helper Functions
1340
1341 (defun bibtex-delete-whitespace ()
1342   ;; Delete all whitespace starting at point
1343   (if (looking-at "[ \t\n]+")
1344       (delete-region (point) (match-end 0))))
1345
1346 (defun bibtex-current-line ()
1347   ;; this computes line number of point regardless whether the buffer
1348   ;; is narrowed
1349   (+ (count-lines 1 (point))
1350      (if (equal (current-column) 0) 1 0)))
1351
1352 (defun bibtex-member-of-regexp (string list)
1353   ;; Return non-nil if STRING is exactly matched by an element of
1354   ;; LIST. The value is actually the tail of LIST whose
1355   ;; car matches STRING.
1356   (let* (case-fold-search)
1357     (while
1358         (and list (not (string-match (concat "^" (car list) "$") string)))
1359       (setq list (cdr list)))
1360     list))
1361
1362 (defun bibtex-assoc-of-regexp (string alist)
1363   ;; Return non-nil if STRING is exactly matched by the car of an
1364   ;; element of LIST (case ignored). The value is actually the element
1365   ;; of LIST whose car matches STRING.
1366   (let* ((case-fold-search t))
1367     (while
1368         (and alist
1369              (not (string-match (concat "^" (car (car alist)) "$") string)))
1370       (setq alist (cdr alist)))
1371     (car alist)))
1372
1373 (defun bibtex-skip-to-valid-entry (&optional backward)
1374   ;; If not at beginning of valid BibTeX entry, move to beginning of
1375   ;; the next valid one. With argument backward non-nil, move backward
1376   ;; to beginning of previous valid one. A valid entry is a
1377   ;; syntactical correct one with type contained in
1378   ;; bibtex-entry-field-alist or, if bibtex-sort-ignore-string-entries
1379   ;; is nil, a syntactical correct string entry.
1380   (let* ((case-fold-search t)
1381          (valid-bibtex-entry
1382           (concat
1383            "@[ \t]*\\("
1384            (mapconcat
1385             (lambda (type)
1386               (concat "\\(" (car type) "\\)"))
1387             bibtex-entry-field-alist
1388             "\\|")
1389            "\\)"))
1390          found)
1391     (while (and (not found)
1392                 (not (if backward
1393                          (bobp)
1394                        (eobp))))
1395       (let ((pnt (point)))
1396         (cond
1397          ((looking-at valid-bibtex-entry)
1398           (if (and
1399                (bibtex-search-entry nil nil t)
1400                (equal (match-beginning 0) pnt))
1401               (setq found t)))
1402          ((and (not bibtex-sort-ignore-string-entries)
1403                (bibtex-parse-string))
1404           (setq found t)))
1405         (if found
1406             (goto-char pnt)
1407           (if backward
1408               (progn
1409                 (goto-char (1- pnt))
1410                 (if (re-search-backward "^[ \t]*\\(@\\)" nil 'move)
1411                     (goto-char (match-beginning 1))))
1412             (goto-char (1+ pnt))
1413             (if (re-search-forward "^[ \t]*@" nil 'move)
1414                 (forward-char -1))))))))
1415
1416 (defun bibtex-map-entries (fun)
1417   ;; Call FUN for each BibTeX entry starting with the current. Do this
1418   ;; to the end of the file. FUN is called with one argument, the key
1419   ;; of the entry, and with point inside the entry. If
1420   ;; bibtex-sort-ignore-string-entries is non-nil, FUN will not be
1421   ;; called for @String entries.
1422   (let* ((case-fold-search t))
1423     (bibtex-beginning-of-entry)
1424     (while (re-search-forward bibtex-entry-maybe-empty-head nil t)
1425       (let ((pnt (point))
1426             (entry-type
1427              (downcase (buffer-substring-no-properties
1428                         (1+ (match-beginning bibtex-type-in-head))
1429                         (match-end bibtex-type-in-head))))
1430             (reference-key
1431              (if (match-beginning bibtex-key-in-head)
1432                  (buffer-substring-no-properties
1433                   (match-beginning bibtex-key-in-head)
1434                   (match-end bibtex-key-in-head))
1435                "")))
1436         (if (or
1437              (and
1438               (not bibtex-sort-ignore-string-entries)
1439               (string-equal "string" (downcase entry-type)))
1440              (assoc-ignore-case entry-type bibtex-entry-field-alist))
1441             (funcall fun reference-key))
1442         (goto-char pnt)
1443         (bibtex-end-of-entry)))))
1444
1445 (defun bibtex-progress-message (&optional flag interval)
1446   ;; echos a message about progress of current buffer
1447   ;; if flag is a string, the message is initialized (in this case a
1448   ;; value for INTERVAL may be given as well (if not this is set to 5))
1449   ;; if flag is done, the message is deinitialized
1450   ;; if flag is absent, a message is echoed if point was incremented
1451   ;; at least INTERVAL percent since last message was echoed
1452   (let* ((size (- (point-max) (point-min)))
1453          (perc (if (= size 0)
1454                    100
1455                  (/ (* 100 (- (point) (point-min))) size))))
1456     (if (or (and (not flag)
1457                  (>= perc
1458                      (+ bibtex-progress-interval bibtex-progress-lastperc)))
1459             (stringp flag))
1460         (progn
1461           (if (stringp flag)
1462               (progn
1463                 (setq bibtex-progress-lastmes flag)
1464                 (if interval
1465                     (setq bibtex-progress-interval interval)
1466                   (setq bibtex-progress-interval 5))))
1467           (setq bibtex-progress-lastperc perc)
1468           (message (concat bibtex-progress-lastmes " (%d%%)") perc))
1469       (if (equal flag 'done)
1470           (progn
1471             (message (concat bibtex-progress-lastmes " (done)"))
1472             (setq bibtex-progress-lastmes nil))))))
1473
1474
1475 (defun bibtex-field-left-delimiter ()
1476   ;; returns a string dependent on bibtex-field-delimiters
1477   (if (equal bibtex-field-delimiters 'braces)
1478       "{"
1479     "\""))
1480
1481 (defun bibtex-field-right-delimiter ()
1482   ;; returns a string dependent on bibtex-field-delimiters
1483   (if (equal bibtex-field-delimiters 'braces)
1484       "}"
1485     "\""))
1486
1487 (defun bibtex-entry-left-delimiter ()
1488   ;; returns a string dependent on bibtex-field-delimiters
1489   (if (equal bibtex-entry-delimiters 'braces)
1490       "{"
1491     "("))
1492
1493 (defun bibtex-entry-right-delimiter ()
1494   ;; returns a string dependent on bibtex-field-delimiters
1495   (if (equal bibtex-entry-delimiters 'braces)
1496       "}"
1497     ")"))
1498
1499 (defun bibtex-search-entry
1500   (empty-head &optional bound noerror backward)
1501   ;; A helper function necessary since the failure stack size limit for
1502   ;; regexps was reduced in emacs 19.32.
1503   ;; It searches for a BibTeX entry (maybe without a reference key if
1504   ;; EMPTY-HEAD is t).
1505   ;; BOUND and NOERROR are exactly as in re-search-forward. If
1506   ;; BACKWARD is non-nil, search is done in reverse direction. After
1507   ;; call to this function MATCH-BEGINNING and MATCH-END functions are
1508   ;; defined, but only for the head part of the entry (especially
1509   ;; (match-end 0) just gives the end of the head part).
1510   (let ((pnt (point))
1511         (prefix (if empty-head
1512                     bibtex-entry-maybe-empty-head
1513                   bibtex-entry-head)))
1514     (if backward
1515         (let (found)
1516           (while (and (not found)
1517                       (re-search-backward prefix bound noerror))
1518             (setq found (bibtex-search-entry empty-head pnt t)))
1519           (if found
1520               (goto-char (match-beginning 0))
1521             (if (equal noerror nil)
1522                 ;; yell
1523                 (error "Search of BibTeX entry failed"))
1524             (if (equal noerror t)
1525                 ;; don't move
1526                 (goto-char pnt))
1527             nil))
1528       (let ((limit (if bound bound (point-max)))
1529             md
1530             found)
1531         (while (and (not found)
1532                     (re-search-forward prefix bound noerror))
1533           (setq md (match-data))
1534           ;; save match-data of prefix regexp
1535           (let ((entry-closer
1536                  (if (save-excursion
1537                        (goto-char (match-end bibtex-type-in-head))
1538                        (looking-at "[ \t]*("))
1539                      ;; entry opened with parenthesis
1540                      ")"
1541                    "}")))
1542             (let ((infix-start (point))
1543                   (finished nil))
1544               (while (not finished)
1545                 (if (and (looking-at "[ \t\n]*")
1546                          (<= (match-end 0) limit))
1547                     (goto-char (match-end 0)))
1548                 (let ((bounds (bibtex-parse-field bibtex-field-name)))
1549                   (if (and bounds (<= (bibtex-end-of-field bounds) limit))
1550                       (progn
1551                         (goto-char (bibtex-end-of-field bounds))
1552                         (setq infix-start (point)))
1553                     (goto-char infix-start)
1554                     (setq finished t)))))
1555             ;; This matches the infix* part. The AND construction assures
1556             ;; that BOUND is respected.
1557             (if (and (looking-at bibtex-entry-postfix)
1558                      (string-equal
1559                       (buffer-substring-no-properties
1560                        (1- (match-end 0)) (match-end 0))
1561                       entry-closer)
1562                      (<= (match-end 0) limit))
1563                 (progn
1564                   (re-search-forward bibtex-entry-postfix)
1565                   (setq found t)))))
1566         (if found
1567             (progn
1568               (set-match-data md)
1569               ;; to set match-beginning/end again
1570               (point))
1571           (if (equal noerror nil)
1572               ;; yell
1573               (error "Search of BibTeX entry failed"))
1574           (if (equal noerror t)
1575               ;; don't move
1576               (goto-char pnt))
1577           nil)))))
1578
1579 (defun bibtex-flash-head ()
1580   ;; Flash at BibTeX entry head before point, if exists.
1581   (let* ((case-fold-search t)
1582          flash)
1583     (cond ((re-search-backward bibtex-entry-head nil t)
1584            (goto-char (match-beginning bibtex-type-in-head))
1585            (setq flash (match-end bibtex-key-in-entry)))
1586           (t
1587            (end-of-line)
1588            (skip-chars-backward " \t")
1589            (setq flash (point))
1590            (beginning-of-line)
1591            (skip-chars-forward " \t")))
1592     (if (pos-visible-in-window-p (point))
1593         (sit-for 1)
1594       (message "From: %s"
1595                (buffer-substring (point) flash)))))
1596
1597 (defun bibtex-make-optional-field (e-t)
1598   "Makes an optional field named E-T in current BibTeX entry."
1599   (if (consp e-t)
1600       (bibtex-make-field (cons (concat "OPT" (car e-t)) (cdr e-t)))
1601     (bibtex-make-field (concat "OPT" e-t))))
1602
1603 (defun bibtex-move-outside-of-entry ()
1604   ;; Make sure we are outside of a BibTeX entry.
1605   (let ((orig-point (point)))
1606     (bibtex-end-of-entry)
1607     (if (< (point) orig-point)
1608         ;; We moved backward, so we weren't inside an entry to begin with.
1609         ;; Leave point at the beginning of a line, and preferably
1610         ;; at the beginning of a paragraph.
1611         (progn
1612           (goto-char orig-point)
1613           (beginning-of-line 1)
1614           (if (not (= ?\n (char-before (1- (point)))))
1615               (progn
1616                 (re-search-forward "^[ \t]*[@\n]" nil 'move)
1617                 (backward-char 1)))))
1618     (skip-chars-forward " \t\n")))
1619
1620 (defun bibtex-beginning-of-first-entry ()
1621   ;; Go to the beginning of the first BibTeX entry in buffer. Return
1622   ;; point.
1623   (goto-char (point-min))
1624   (if (re-search-forward "^[ \t]*@" nil 'move)
1625       (beginning-of-line))
1626   (point))
1627
1628 (defun bibtex-beginning-of-last-entry ()
1629   ;; Go to the beginning of the last BibTeX entry in buffer.
1630   (goto-char (point-max))
1631   (if (re-search-backward "^[ \t]*@" nil 'move)
1632       (beginning-of-line))
1633   (point))
1634
1635 (defun bibtex-inside-field ()
1636   ;; Try to avoid point being at end of a BibTeX field.
1637   (end-of-line)
1638   (skip-chars-backward " \t")
1639   (cond ((= (preceding-char) ?,)
1640          (forward-char -2)))
1641   (cond ((or
1642           (= (preceding-char) ?})
1643           (= (preceding-char) ?\"))
1644          (forward-char -1))))
1645
1646 (defun bibtex-enclosing-field (&optional noerr)
1647   ;; Search for BibTeX field enclosing point. Point moves to end of
1648   ;; field. Use match-beginning and match-end to parse the field. If
1649   ;; NOERR is non-nil, no error is signalled. In this case, t is
1650   ;; returned on success, nil otherwise.
1651   (let* ((case-fold-search t)
1652          (old-point (point))
1653          (boe (bibtex-beginning-of-entry)))
1654     (goto-char old-point)
1655     (let ((bounds (bibtex-search-backward-field bibtex-field-name boe)))
1656       (if (and bounds
1657                (<= (bibtex-start-of-field bounds) old-point)
1658                (>= (bibtex-end-of-field bounds) old-point))
1659           bounds
1660         (if noerr
1661             nil
1662           (error "Can't find enclosing BibTeX field"))))))
1663
1664 (defun bibtex-enclosing-entry-maybe-empty-head ()
1665   ;; Search for BibTeX entry enclosing point. Point moves to
1666   ;; end of entry. Beginning (but not end) of entry is given
1667   ;; by (match-beginning 0).
1668   (let* ((case-fold-search t)
1669          (old-point (point)))
1670     (if (not
1671          (re-search-backward
1672           bibtex-entry-maybe-empty-head nil t))
1673         (progn
1674           (error "Can't find enclosing BibTeX entry")
1675           (goto-char old-point)))
1676     (goto-char (match-beginning bibtex-type-in-head))
1677     (if (not
1678          (bibtex-search-entry t nil t))
1679         (progn
1680           (error "Can't find enclosing BibTeX entry")
1681           (goto-char old-point)))))
1682
1683 (defun bibtex-insert-current-kill (n)
1684   (if (not bibtex-last-kill-command)
1685       (error "BibTeX kill ring is empty")
1686     (let* ((kr (if (equal bibtex-last-kill-command 'field)
1687                    'bibtex-field-kill-ring
1688                  'bibtex-entry-kill-ring))
1689            (kryp (if (equal bibtex-last-kill-command 'field)
1690                      'bibtex-field-kill-ring-yank-pointer
1691                    'bibtex-entry-kill-ring-yank-pointer))
1692            (ARGth-kill-element
1693             (nthcdr
1694              (mod (- n (length (eval kryp))) (length (eval kr)))
1695              (eval kr)))
1696            (current (car (set kryp ARGth-kill-element))))
1697       (cond
1698        ((equal bibtex-last-kill-command 'field)
1699         (let (bibtex-help-message)
1700           (bibtex-find-text nil t)
1701           (if (looking-at "[}\"]")
1702               (forward-char)))
1703         (set-mark (point))
1704         (message "Mark set")
1705         (bibtex-make-field (list (elt current 1) nil (elt current 2)) t))
1706        ((equal bibtex-last-kill-command 'entry)
1707         (if (not (eobp))
1708             (bibtex-beginning-of-entry))
1709         (set-mark (point))
1710         (message "Mark set")
1711         (insert (elt current 1)))
1712        (t
1713         (error
1714          "Unknown tag field: %s.  Please submit a bug report"
1715          bibtex-last-kill-command))))))
1716
1717 (defun bibtex-format-field-delimiters (start stop)
1718   "*Replaces delimiters for field strings between START and STOP.
1719 If the current delimiters equal the new delimiters, the buffer is not
1720 changed."
1721   (goto-char start)
1722   (let ((boundaries (bibtex-search-forward-field-string stop)))
1723     (while boundaries
1724       (goto-char (car boundaries))
1725       (if (not (looking-at (bibtex-field-left-delimiter)))
1726           (progn
1727             (delete-char 1)
1728             (insert (bibtex-field-left-delimiter))))
1729       (goto-char (- (cdr boundaries) 1))
1730       (if (not (looking-at (bibtex-field-right-delimiter)))
1731           (progn
1732             (delete-char 1)
1733             (insert (bibtex-field-right-delimiter))))
1734       (setq boundaries (bibtex-search-forward-field-string stop)))))
1735
1736 (defun bibtex-format-entry ()
1737   ;; Helper function for bibtex-clean-entry. Formats current entry
1738   ;; according to variable bibtex-entry-format.
1739   (let* ((case-fold-search t)
1740          (beg (point))
1741          (start (bibtex-beginning-of-entry))
1742          crossref-there
1743          alternatives-there
1744          non-empty-alternative)
1745     (let ((end (copy-marker (bibtex-end-of-entry))))
1746       (if (equal start (marker-position end))
1747           (error "Not on a known BibTeX entry")
1748         (goto-char start)
1749         (let ((bounds (bibtex-search-forward-field bibtex-field-name end)))
1750           (while bounds
1751             ;; determine if entry has crossref field and if at least
1752             ;; one alternative is non-empty
1753             (let ((begin-name (bibtex-start-of-name-in-field bounds))
1754                   (end-name (bibtex-end-of-name-in-field bounds))
1755                   (begin-text (bibtex-start-of-text-in-field bounds))
1756                   (end-text (bibtex-end-of-text-in-field bounds)))
1757               (goto-char begin-name)
1758               (if (looking-at "ALT")
1759                   (progn
1760                     (setq alternatives-there t)
1761                     (goto-char begin-text)
1762                     (if (not (looking-at "\\(\"\"\\)\\|\\({}\\)"))
1763                         (setq non-empty-alternative t))))
1764               (if (string-match
1765                    "\\(OPT\\)?crossref"
1766                    (buffer-substring-no-properties begin-name end-name))
1767                   (progn
1768                     (setq
1769                      crossref-there
1770                      (buffer-substring-no-properties
1771                       (1+ begin-text) (1- end-text)))
1772                     (if (equal crossref-there "")
1773                         (setq crossref-there nil)))))
1774             (goto-char (bibtex-end-of-field bounds))
1775             (setq bounds (bibtex-search-forward-field bibtex-field-name end))))
1776         (if (and alternatives-there
1777                  (not non-empty-alternative))
1778             (progn
1779               (goto-char beg)
1780               (error "All alternatives are empty")))
1781         (goto-char start)
1782         (re-search-forward bibtex-entry-type end)
1783         (let* ((begin-type (1+ (match-beginning 0)))
1784                (end-type (match-end 0))
1785                (entry-type
1786                 (downcase
1787                  (buffer-substring-no-properties begin-type end-type)))
1788                (entry-list
1789                 (assoc-ignore-case entry-type bibtex-entry-field-alist))
1790                (req (elt (elt entry-list 1) 0))
1791                (creq (elt (elt entry-list 2) 0))
1792                (format (if (equal bibtex-entry-format t)
1793                            '(realign opts-or-alts numerical-fields
1794                                      last-comma page-dashes delimiters
1795                                      unify-case inherit-booktitle)
1796                          bibtex-entry-format))
1797                field-done)
1798           (if (memq 'unify-case format)
1799               (progn
1800                 (delete-region begin-type end-type)
1801                 (insert (car entry-list))))
1802           (if (memq 'delimiters format)
1803               (progn
1804                 (goto-char end-type)
1805                 (skip-chars-forward " \t\n")
1806                 (delete-char 1)
1807                 (insert (bibtex-entry-left-delimiter))))
1808           (goto-char start)
1809           (let ((bounds (bibtex-search-forward-field bibtex-field-name end)))
1810             (while bounds
1811               (let* ((begin-field (copy-marker (bibtex-start-of-field bounds)))
1812                      (end-field (copy-marker (bibtex-end-of-field bounds)))
1813                      (begin-name (copy-marker (bibtex-start-of-name-in-field bounds)))
1814                      (end-name (copy-marker (bibtex-end-of-name-in-field bounds)))
1815                      (begin-text (copy-marker (bibtex-start-of-text-in-field bounds)))
1816                      (end-text (copy-marker (bibtex-end-of-text-in-field bounds)))
1817                      (field-name
1818                       (buffer-substring-no-properties
1819                        (if (string-match
1820                             "^\\(OPT\\)\\|\\(ALT\\)$"
1821                             (buffer-substring-no-properties
1822                              begin-name (+ begin-name 3)))
1823                            (+ begin-name 3)
1824                          begin-name)
1825                        end-name)))
1826                 (cond
1827                  ((and
1828                    (memq 'opts-or-alts format)
1829                    (progn (goto-char begin-name)
1830                           (looking-at "OPT\\|ALT")))
1831                   (goto-char begin-text)
1832                   (if (looking-at "\\(\"\"\\)\\|\\({}\\)")
1833                       ;; empty: delete whole field if really optional
1834                       ;; (missing crossref handled) or complain
1835                       (if (and
1836                            (progn
1837                              (goto-char begin-name)
1838                              (looking-at "OPT"))
1839                            (not crossref-there)
1840                            (assoc-ignore-case field-name req))
1841                           ;; field is not really optional
1842                           (progn
1843                             (goto-char begin-name)
1844                             (bibtex-remove-OPT-or-ALT)
1845                             (error
1846                              "Mandatory field ``%s'' is empty" field-name))
1847                         ;; field is optional
1848                         (delete-region begin-field end-field))
1849                     ;; otherwise: not empty, delete "OPT"
1850                     (goto-char begin-name)
1851                     (bibtex-remove-OPT-or-ALT)))
1852                  ((and
1853                    (memq 'numerical-fields format)
1854                    (progn
1855                      (goto-char begin-text)
1856                      (looking-at "\\(\"[0-9]+\"\\)\\|\\({[0-9]+}\\)")))
1857                   (goto-char end-text)
1858                   (delete-char -1)
1859                   (goto-char begin-text)
1860                   (delete-char 1))
1861                  (t
1862                   (if (memq 'delimiters format)
1863                       (bibtex-format-field-delimiters begin-text end-text))
1864                   (if (and
1865                        (memq 'page-dashes format)
1866                        (string-match "^\\(OPT\\)?pages$" (downcase field-name))
1867                        (progn
1868                          (goto-char begin-text)
1869                          (looking-at
1870                           "\\([\"{][0-9]+\\)[ \t\n]*--?[ \t\n]*\\([0-9]+[\"}]\\)")))
1871                       (replace-match "\\1-\\2"))
1872                   (if (and
1873                        (memq 'inherit-booktitle format)
1874                        (equal (downcase field-name) "booktitle")
1875                        (progn
1876                          (goto-char begin-text)
1877                          (looking-at "\\(\"\"\\)\\|\\({}\\)"))
1878                        crossref-there
1879                        (not (bibtex-find-entry-location crossref-there t)))
1880                       ;; booktitle field empty and crossref entry found
1881                       ;; --> insert title field of crossreferenced entry if there
1882                       (let ((stop (bibtex-end-of-entry)))
1883                         (bibtex-beginning-of-entry)
1884                         (let ((bounds (bibtex-search-forward-field "title" stop)))
1885                           (if bounds
1886                               (progn
1887                                 (goto-char begin-text)
1888                                 (forward-char)
1889                                 (insert
1890                                  (buffer-substring-no-properties
1891                                   (1+ (bibtex-start-of-text-in-field bounds))
1892                                   (1- (bibtex-end-of-text-in-field bounds)))))))))
1893                   (if (progn
1894                         (goto-char begin-text)
1895                         (looking-at "\\(\"\"\\)\\|\\({}\\)"))
1896                       ;; if empty field, complain
1897                       (progn
1898                         (forward-char)
1899                         (if (or (and
1900                                  crossref-there
1901                                  (assoc-ignore-case
1902                                   field-name creq))
1903                                 (and
1904                                  (not crossref-there)
1905                                  (assoc-ignore-case
1906                                   field-name req)))
1907                             (error
1908                              "Mandatory field ``%s'' is empty" field-name))))
1909                   (if (memq 'unify-case format)
1910                       (let* ((fl
1911                               (car (cdr (assoc-ignore-case
1912                                          entry-type
1913                                          bibtex-entry-field-alist))))
1914                              (field-list
1915                               (append
1916                                (elt fl 0)
1917                                (elt fl 1)
1918                                bibtex-user-optional-fields))
1919                              (new-field-name
1920                               (car
1921                                (assoc-ignore-case field-name field-list))))
1922                         (goto-char begin-name)
1923                         (if new-field-name
1924                             (progn
1925                               (delete-region begin-name end-name)
1926                               (insert new-field-name))
1927                           (downcase-region begin-name end-name))))
1928                   (setq field-done t)))
1929                 (if (not field-done)
1930                     (goto-char begin-field)
1931                   (setq field-done nil)
1932                   (goto-char end-field)))
1933               (setq bounds (bibtex-search-forward-field bibtex-field-name end))))
1934           (if (looking-at (bibtex-field-right-delimiter))
1935               (forward-char))
1936           (if (memq 'last-comma format)
1937               (cond ((and
1938                       bibtex-comma-after-last-field
1939                       (not (looking-at ",")))
1940                      (insert ","))
1941                     ((and
1942                       (not bibtex-comma-after-last-field)
1943                       (looking-at ","))
1944                      (delete-char 1))))
1945           (if (looking-at ",")
1946               (forward-char))
1947           (if (memq 'delimiters format)
1948               (progn
1949                 (skip-chars-forward " \t\n")
1950                 (delete-char 1)
1951                 (insert (bibtex-entry-right-delimiter))))
1952           (if (memq 'realign format)
1953               (bibtex-fill-entry)))))))
1954
1955 (defun bibtex-autokey-change (string change-list)
1956   ;; Returns a string where some regexps are changed according to
1957   ;; change-list. Every item of change-list is an (old-regexp
1958   ;; new-string) pair.
1959   (let* (case-fold-search
1960          (return-string string)
1961          (index 0)
1962          (len (length change-list))
1963          change-item)
1964     (while (< index len)
1965       (setq change-item (elt change-list index))
1966       (while (string-match (car change-item) return-string)
1967         (setq
1968          return-string
1969          (concat (substring return-string 0 (match-beginning 0))
1970                  (elt change-item 1)
1971                  (substring return-string (match-end 0)))))
1972       (setq index (1+ index)))
1973     return-string))
1974
1975 (defun bibtex-autokey-abbrev (string len)
1976   ;; Returns an abbreviation of string with at least len
1977   ;; characters.  String is aborted only after a consonant or at the
1978   ;; word end.  If len is not a number, string is returned unchanged.
1979   (cond ((or
1980           (not (numberp len))
1981           (<= (length string) len))
1982          string)
1983         ((equal len 0)
1984          "")
1985         (t
1986          (let* ((case-fold-search t)
1987                 (abort-char
1988                  (string-match "[^aeiou]" string (1- len))))
1989            (if abort-char
1990                (substring string 0 (1+ abort-char))
1991              string)))))
1992
1993 (defun bibtex-autokey-get-namefield (min max)
1994   ;; returns the contents of the name field of the current entry
1995   ;; does some modifications based on `bibtex-autokey-name-change-strings'
1996   ;; and removes newlines unconditionally
1997   (goto-char min)
1998   (let* ((case-fold-search t)
1999          (author-or-editor "\\(author\\)\\|\\(editor\\)")
2000          (bounds (bibtex-search-forward-field author-or-editor max)))
2001     (if bounds
2002         (bibtex-autokey-change
2003          (buffer-substring-no-properties
2004           (1+ (bibtex-start-of-text-in-field bounds))
2005           (1- (bibtex-end-of-text-in-field bounds)))
2006          (append bibtex-autokey-name-change-strings '(("\n" " "))))
2007       "")))
2008
2009 (defun bibtex-autokey-get-names (namefield)
2010   ;; gathers all names in namefield into a list
2011   (let* ((case-fold-search t)
2012          names)
2013     (while (not (equal namefield ""))
2014       (let (name)
2015         (if (string-match "[ \t\n]and[ \t\n]" namefield)
2016             (setq name (substring namefield 0 (match-beginning 0))
2017                   namefield (substring namefield (match-end 0)))
2018           (setq name namefield
2019                 namefield ""))
2020         (setq names (append names (list name)))))
2021     names))
2022
2023 (defun bibtex-autokey-demangle-name (fullname)
2024   ;; gets the `last' part from a well-formed name
2025   (let* (case-fold-search
2026          (lastname
2027           (if (string-match "," fullname)
2028               ;; name is of the form "von Last, First" or
2029               ;; "von Last, Jr, First"
2030               ;; --> take only the part before the comma
2031               (let ((von-last
2032                      (substring fullname 0 (match-beginning 0))))
2033                 (if (string-match "^[a-z]" von-last)
2034                     ;; von-last has a "von" part --> take the "last" part
2035                     (if (string-match "[ \t][A-Z]" von-last)
2036                         (substring von-last (1+ (match-beginning 0)))
2037                       (error
2038                        "Name %s is incorrectly formed" fullname))
2039                   ;; von-last has no "von" part --> take all
2040                   von-last))
2041             ;; name is of the form "First von Last"
2042             (if (string-match "[ \t]" fullname)
2043                 ;; more than one token
2044                 (if (string-match "[ \t][a-z]" fullname)
2045                     ;; there is a "von" part
2046                     ;; --> take everything after that
2047                     (if (string-match
2048                          "[ \t][A-Z]" fullname (match-end 0))
2049                         (substring fullname (1+ (match-beginning 0)))
2050                       (error
2051                        "Name %s is incorrectly formed" fullname))
2052                   ;; there is no "von" part --> take only the last token
2053                   (if (string-match " [^ ]*$" fullname)
2054                       (substring fullname (1+ (match-beginning 0)))
2055                     (error "Name %s is incorrectly formed" fullname)))
2056               ;; only one token --> take it
2057               fullname)))
2058          (usename
2059           (if (string-match "[ \t]+" lastname)
2060               ;; lastname consists of two or more tokens
2061               ;; --> take only the first one
2062               (substring lastname 0 (match-beginning 0))
2063             lastname)))
2064     (funcall bibtex-autokey-name-case-convert usename)))
2065
2066 (defun bibtex-autokey-get-namelist (namefield)
2067   ;; gets namefield, performs abbreviations on the last parts, and
2068   ;; return results as a list
2069   (mapcar
2070    (lambda (fullname)
2071      (setq
2072       fullname (substring fullname (string-match "[^ \t]" fullname)))
2073      (bibtex-autokey-abbrev
2074       (bibtex-autokey-demangle-name fullname)
2075       bibtex-autokey-name-length))
2076    (bibtex-autokey-get-names namefield)))
2077
2078 (defun bibtex-autokey-get-yearfield-digits (max)
2079   ;; get digit substring from year field.
2080   (let ((bounds (bibtex-search-forward-field "year" max)))
2081     (if bounds
2082         (let ((year (buffer-substring-no-properties
2083                      (bibtex-start-of-text-in-field bounds)
2084                      (bibtex-end-of-text-in-field bounds))))
2085           (string-match "[^0-9]*\\([0-9]+\\)" year)
2086           (substring year (match-beginning 1) (match-end 1)))
2087       "")))
2088
2089 (defun bibtex-autokey-get-yearfield (min max)
2090   ;; get year field from current or maybe crossreferenced entry
2091   (goto-char min)
2092   (let* ((case-fold-search t)
2093          (year (bibtex-autokey-get-yearfield-digits max)))
2094     (if (and (string= year "") bibtex-autokey-year-use-crossref-entry)
2095         (let* ((bounds
2096                 (bibtex-search-forward-field "\\(OPT\\)?crossref" max))
2097                (crossref-field
2098                 (if bounds
2099                     (buffer-substring-no-properties
2100                      (1+ (bibtex-start-of-text-in-field bounds))
2101                      (1- (bibtex-end-of-text-in-field bounds))))))
2102           (if (not (bibtex-find-entry-location crossref-field t))
2103               (let ((stop (bibtex-end-of-entry)))
2104                 (bibtex-beginning-of-entry)
2105                 (bibtex-autokey-get-yearfield-digits stop))
2106             ""))
2107       year)))
2108
2109 (defun bibtex-autokey-get-titlestring (min max)
2110   ;; get title field contents up to a terminator
2111   (goto-char min)
2112   (let* ((case-fold-search t)
2113          (bounds (bibtex-search-forward-field "title" max))
2114          (titlefield
2115           (if bounds
2116               (bibtex-autokey-change
2117                (buffer-substring-no-properties
2118                 (1+ (bibtex-start-of-text-in-field bounds))
2119                 (1- (bibtex-end-of-text-in-field bounds)))
2120                bibtex-autokey-titleword-change-strings)
2121             ""))
2122          (title-terminators bibtex-autokey-title-terminators))
2123     (while (not (null title-terminators))
2124       (if (string-match (car title-terminators) titlefield)
2125           (setq titlefield (substring titlefield 0 (match-beginning 0))))
2126       (setq title-terminators (cdr title-terminators)))
2127     titlefield))
2128
2129 (defun bibtex-autokey-get-titles (titlestring)
2130   ;; gathers words from titlestring into a list. Ignores
2131   ;; specific words and uses only a specific amount of words.
2132   (let* (case-fold-search
2133          titlewords
2134          titlewords-extra
2135          (counter 0))
2136     (while (and
2137             (not (equal titlestring ""))
2138             (or
2139              (not (numberp bibtex-autokey-titlewords))
2140              (< counter
2141                 (+ bibtex-autokey-titlewords
2142                    bibtex-autokey-titlewords-stretch))))
2143       (if (string-match "\\b\\w+" titlestring)
2144           (let* ((end-match (match-end 0))
2145                  (titleword
2146                   (substring titlestring (match-beginning 0) end-match)))
2147             (if (bibtex-member-of-regexp
2148                  titleword
2149                  bibtex-autokey-titleword-ignore)
2150                 (setq counter (1- counter))
2151               (setq
2152                titleword
2153                (funcall bibtex-autokey-titleword-case-convert titleword))
2154               (if (or (not (numberp bibtex-autokey-titlewords))
2155                       (< counter bibtex-autokey-titlewords))
2156                   (setq titlewords (append titlewords (list titleword)))
2157                 (setq titlewords-extra
2158                       (append titlewords-extra (list titleword)))))
2159             (setq
2160              titlestring (substring titlestring end-match)))
2161         (setq titlestring ""))
2162       (setq counter (1+ counter)))
2163     (if (string-match "\\b\\w+" titlestring)
2164         titlewords
2165       (append titlewords titlewords-extra))))
2166
2167 (defun bibtex-autokey-get-titlelist (titlestring)
2168   ;; returns all words in titlestring as a list
2169   ;; does some abbreviation on the found words
2170   (mapcar
2171    (lambda (titleword)
2172      (let ((abbrev
2173             (bibtex-assoc-of-regexp
2174              titleword bibtex-autokey-titleword-abbrevs)))
2175        (if abbrev
2176            (elt abbrev 1)
2177          (bibtex-autokey-abbrev
2178           titleword
2179           bibtex-autokey-titleword-length))))
2180    (bibtex-autokey-get-titles titlestring)))
2181
2182 (defun bibtex-generate-autokey ()
2183   "Generates automatically a key from the author/editor and the title field.
2184 This will only work for entries where each field begins on a separate line.
2185 The generation algorithm works as follows:
2186  1. Use the value of `bibtex-autokey-prefix-string' as a prefix.
2187  2. If there is a non-empty author (preferred) or editor field,
2188     use it as the name part of the key.
2189  3. Change any substring found in
2190     `bibtex-autokey-name-change-strings' to the corresponding new
2191     one (see documentation of this variable for further detail).
2192  4. For every of at least first `bibtex-autokey-names' names in
2193     the name field, determine the last name. If there are maximal
2194     `bibtex-autokey-names' + `bibtex-autokey-names-stretch'
2195     names, all names are used.
2196  5. From every last name, take at least
2197     `bibtex-autokey-name-length' characters (abort only after a
2198     consonant or at a word end).
2199  6. Convert all last names according to the conversion function
2200     `bibtex-autokey-name-case-convert'.
2201  7. Build the name part of the key by concatenating all
2202     abbreviated last names with the string
2203     `bibtex-autokey-name-separator' between any two. If there are
2204     more names than are used in the name part, prepend the string
2205     contained in `bibtex-autokey-additional-names'.
2206  8. Build the year part of the key by truncating the contents of
2207     the year field to the rightmost `bibtex-autokey-year-length'
2208     digits (useful values are 2 and 4). If the year field is
2209     absent, but the entry has a valid crossref field and the
2210     variable `bibtex-autokey-year-use-crossref-entry' is non-nil,
2211     use the year field of the crossreferenced entry instead.
2212  9. For the title part of the key change the contents of the
2213     title field of the entry according to
2214     `bibtex-autokey-titleword-change-strings' to the
2215     corresponding new one (see documentation of this variable for
2216     further detail).
2217 10. Abbreviate the result to the string up to (but not including)
2218     the first occurrence of a regexp matched by the items of
2219     `bibtex-autokey-title-terminators' and delete those words which
2220     appear in `bibtex-autokey-titleword-ignore'.
2221     Build the title part of the key by using at least the first
2222     `bibtex-autokey-titlewords' words from this
2223     abbreviated title. If the abbreviated title ends after
2224     maximal `bibtex-autokey-titlewords' +
2225     `bibtex-autokey-titlewords-stretch' words, all
2226     words from the abbreviated title are used.
2227 11. Convert all used titlewords according to the conversion function
2228     `bibtex-autokey-titleword-case-convert'.
2229 12. For every used title word that appears in
2230     `bibtex-autokey-titleword-abbrevs' use the corresponding
2231     abbreviation (see documentation of this variable for further
2232     detail).
2233 13. From every title word not generated by an abbreviation, take
2234     at least `bibtex-autokey-titleword-length' characters (abort
2235     only after a consonant or at a word end).
2236 14. Build the title part of the key by concatenating all
2237     abbreviated title words with the string
2238     `bibtex-autokey-titleword-separator' between any two.
2239 15. At least, to get the key, concatenate
2240     `bibtex-autokey-prefix-string', the name part, the year part
2241     and the title part with `bibtex-autokey-name-year-separator'
2242     between the name part and the year part if both are non-empty
2243     and `bibtex-autokey-year-title-separator' between the year
2244     part and the title part if both are non-empty. If the year
2245     part is empty, but not the other two parts,
2246     `bibtex-autokey-year-title-separator' is used as well.
2247 16. If the value of `bibtex-autokey-before-presentation-function'
2248     is non-nil, it must be a function taking one argument. This
2249     function is then called with the generated key as the
2250     argument. The return value of this function (a string) is
2251     used as the key.
2252 17. If the value of `bibtex-autokey-edit-before-use' is non-nil,
2253     the key is then presented in the minibuffer to the user,
2254     where it can be edited.  The key given by the user is then
2255     used."
2256   (let* ((pnt (point))
2257          (min (bibtex-beginning-of-entry))
2258          (max (bibtex-end-of-entry))
2259          (namefield (bibtex-autokey-get-namefield min max))
2260          (name-etal "")
2261          (namelist
2262           (let ((nl (bibtex-autokey-get-namelist namefield)))
2263             (if (or (not (numberp bibtex-autokey-names))
2264                     (<= (length nl)
2265                         (+ bibtex-autokey-names
2266                            bibtex-autokey-names-stretch)))
2267                 nl
2268               (setq name-etal bibtex-autokey-additional-names)
2269               (let (nnl)
2270                 (while (< (length nnl) bibtex-autokey-names)
2271                   (setq nnl (append nnl (list (car nl)))
2272                         nl (cdr nl)))
2273                 nnl))))
2274          (namepart
2275           (concat
2276            (mapconcat (lambda (name) name)
2277                       namelist
2278                       bibtex-autokey-name-separator)
2279            name-etal))
2280          (yearfield (bibtex-autokey-get-yearfield min max))
2281          (yearpart
2282           (if (equal yearfield "")
2283               ""
2284             (substring
2285              yearfield
2286              (- (length yearfield) bibtex-autokey-year-length))))
2287          (titlestring (bibtex-autokey-get-titlestring min max))
2288          (titlelist (bibtex-autokey-get-titlelist titlestring))
2289          (titlepart
2290           (mapconcat
2291            (lambda (name) name)
2292            titlelist
2293            bibtex-autokey-titleword-separator))
2294          (autokey
2295           (concat
2296            bibtex-autokey-prefix-string
2297            namepart
2298            (if (not
2299                 (or
2300                  (equal namepart "")
2301                  (equal yearpart "")))
2302                bibtex-autokey-name-year-separator)
2303            yearpart
2304            (if (not
2305                 (or
2306                  (and
2307                   (equal namepart "")
2308                   (equal yearpart ""))
2309                  (equal titlepart "")))
2310                bibtex-autokey-year-title-separator)
2311            titlepart)))
2312     (if bibtex-autokey-before-presentation-function
2313         (setq
2314          autokey
2315          (funcall bibtex-autokey-before-presentation-function autokey)))
2316     (goto-char pnt)
2317     autokey))
2318
2319 (defun bibtex-parse-keys (add verbose &optional abortable)
2320   ;; Sets bibtex-reference-keys to the keys used in the whole (possibly
2321   ;; restricted) buffer (either as entry keys or as crossref entries).
2322   ;; If ADD is non-nil adds the new keys to bibtex-reference-keys instead of
2323   ;; simply resetting it. If VERBOSE is non-nil gives messages about
2324   ;; progress. If ABORTABLE is non-nil abort on user input.
2325   (if bibtex-maintain-sorted-entries
2326       (let* ((case-fold-search t)
2327              (reference-keys (if add bibtex-reference-keys)))
2328         (save-excursion
2329           (goto-char (point-min))
2330           (if verbose
2331               (bibtex-progress-message
2332                (concat (buffer-name) ": parsing reference keys")))
2333           (if (catch 'userkey
2334                 (bibtex-skip-to-valid-entry)
2335                 (while (not (eobp))
2336                   (if (and
2337                        abortable
2338                        (input-pending-p))
2339                       (throw 'userkey t))
2340                   (if verbose
2341                       (bibtex-progress-message))
2342                   (let (reference-key
2343                         xrefd-reference-key)
2344                     (cond
2345                      ((looking-at bibtex-entry-head)
2346                       (setq
2347                        reference-key
2348                        (buffer-substring-no-properties
2349                         (match-beginning bibtex-key-in-head)
2350                         (match-end bibtex-key-in-head)))
2351                       (let ((p (point))
2352                             (m (bibtex-end-of-entry)))
2353                         (goto-char p)
2354                         (let ((bounds (bibtex-search-forward-field "crossref" m)))
2355                           (if bounds
2356                               (setq
2357                                xrefd-reference-key
2358                                (buffer-substring-no-properties
2359                                 (1+ (bibtex-start-of-text-in-field bounds))
2360                                 (1- (bibtex-end-of-text-in-field bounds))))))))
2361                      ((bibtex-parse-string)
2362                       (let ((bounds (bibtex-parse-string)))
2363                         (setq
2364                          reference-key
2365                          (buffer-substring-no-properties
2366                           (bibtex-start-of-reference-key-in-string bounds)
2367                           (bibtex-end-of-reference-key-in-string bounds))))))
2368                     (forward-char)
2369                     (bibtex-skip-to-valid-entry)
2370                     (if (not (assoc reference-key reference-keys))
2371                         (setq reference-keys
2372                               (cons (list reference-key) reference-keys)))
2373                     (if (and xrefd-reference-key
2374                              (not (assoc xrefd-reference-key reference-keys)))
2375                         (setq reference-keys
2376                               (cons (list xrefd-reference-key) reference-keys))))))
2377               ;; user has aborted by typing a key --> return nil
2378               nil
2379             ;; successful operation --> return t
2380             (setq
2381              bibtex-buffer-last-parsed-tick (buffer-modified-tick)
2382              bibtex-reference-keys reference-keys)
2383             (if verbose
2384                 (bibtex-progress-message 'done))
2385             t)))))
2386
2387 (defun bibtex-parse-buffers-stealthily ()
2388   ;; Called by bibtex-run-with-idle-timer. Whenever emacs has been idle
2389   ;; for bibtex-parse-keys-timeout seconds, all BibTeX buffers (starting
2390   ;; with the current) are parsed.
2391   (let ((buffers (buffer-list)))
2392     (save-excursion
2393       (while (and buffers (not (input-pending-p)))
2394         (set-buffer (car buffers))
2395         (save-restriction
2396           (widen)
2397           (if (and
2398                (eq major-mode 'bibtex-mode)
2399                bibtex-maintain-sorted-entries
2400                (not
2401                 (eq (buffer-modified-tick)
2402                     bibtex-buffer-last-parsed-tick)))
2403               (if (bibtex-parse-keys nil t t)
2404                   ;; successful operation --> remove buffer from list
2405                   (setq buffers (cdr buffers)))
2406             ;; buffer is no BibTeX buffer or needs no parsing
2407             (setq buffers (cdr buffers))))))))
2408
2409 (defun bibtex-complete (string-list &optional complete-strings)
2410   ;; Complete word fragment before point to longest prefix of one
2411   ;; string defined in STRING-LIST. If point is not after the part of
2412   ;; a word, all strings are listed. If COMPLETE-STRINGS is non-nil,
2413   ;; add the strings defined in this buffer before cursor to
2414   ;; STRING-LIST and remove surrounding delimiters if complete string
2415   ;; could be expanded.
2416   (let* ((case-fold-search t)
2417          (end (point))
2418          (beg (save-excursion
2419                 (re-search-backward "[ \t{\"]")
2420                 (forward-char)
2421                 (point)))
2422          (part-of-word (buffer-substring-no-properties beg end))
2423          (completions (copy-sequence string-list))
2424          (completion (save-excursion
2425                        (if complete-strings
2426                            (while (bibtex-search-backward-string)
2427                              (let ((bounds (bibtex-search-backward-string)))
2428                                (setq completions
2429                                      (cons
2430                                       (list
2431                                        (buffer-substring-no-properties
2432                                         (bibtex-start-of-reference-key-in-string bounds)
2433                                         (bibtex-end-of-reference-key-in-string bounds)))
2434                                       completions)))))
2435                        (setq completions
2436                              (sort completions
2437                                    (lambda(x y)
2438                                      (string-lessp
2439                                       (car x)
2440                                       (car y)))))
2441                        (try-completion part-of-word completions))))
2442     (cond ((eq completion t)
2443            (if complete-strings
2444                ;; remove double-quotes or braces if field is no concatenation
2445                (save-excursion
2446                  (bibtex-inside-field)
2447                  (let* ((bounds (bibtex-enclosing-field)))
2448                    (goto-char (bibtex-start-of-text-in-field bounds))
2449                    (let ((boundaries (bibtex-parse-field-string)))
2450                      (if (and boundaries (equal (cdr boundaries) (bibtex-end-of-text-in-field bounds)))
2451                          (bibtex-remove-delimiters)))))))
2452           ((not completion)
2453            (error "Can't find completion for \"%s\"" part-of-word))
2454           ((not (string= part-of-word completion))
2455            (delete-region beg end)
2456            (insert completion)
2457            (if (and (assoc completion completions)
2458                     complete-strings)
2459                ;; remove double-quotes or braces if field is no concatenation
2460                (save-excursion
2461                  (bibtex-inside-field)
2462                  (let* ((bounds (bibtex-enclosing-field)))
2463                    (goto-char (bibtex-start-of-text-in-field bounds))
2464                    (let ((boundaries (bibtex-parse-field-string)))
2465                      (if (and boundaries (equal (cdr boundaries) (bibtex-end-of-text-in-field bounds)))
2466                          (bibtex-remove-delimiters)))))))
2467           (t
2468            (message "Making completion list...")
2469            (let ((list (all-completions part-of-word completions)))
2470              (with-output-to-temp-buffer "*Completions*"
2471                (display-completion-list list)))
2472            (message "Making completion list...done")))))
2473
2474 (defun bibtex-do-auto-fill ()
2475   (let ((fill-prefix
2476          (make-string
2477           (+ bibtex-entry-offset bibtex-contline-indentation) ? )))
2478     (do-auto-fill)))
2479
2480 (defun bibtex-pop (arg direction)
2481   ;; generic function to be used by bibtex-pop-previous and bibtex-pop-next
2482   (let (bibtex-help-message)
2483     (bibtex-find-text nil))
2484   (save-excursion
2485     ;; parse current field
2486     (bibtex-inside-field)
2487     (let* ((case-fold-search t)
2488            (bounds (bibtex-enclosing-field))
2489            (start-old-text (bibtex-start-of-text-in-field bounds))
2490            (stop-old-text (bibtex-end-of-text-in-field bounds))
2491            (start-name (bibtex-start-of-name-in-field bounds))
2492            (stop-name (bibtex-end-of-name-in-field bounds))
2493            (new-text))
2494       (goto-char start-name)
2495       ;; construct regexp for field with same name as this one,
2496       ;; ignoring possible OPT's or ALT's
2497       (let* ((field-name
2498               (buffer-substring-no-properties
2499                (if (looking-at "\\(OPT\\)\\|\\(ALT\\)")
2500                    (match-end 0)
2501                  (point))
2502                stop-name)))
2503         ;; if executed several times in a row, start each search where
2504         ;; the last one was finished
2505         (cond ((eq last-command 'bibtex-pop) t)
2506               (t
2507                (bibtex-enclosing-entry-maybe-empty-head)
2508                (setq
2509                 bibtex-pop-previous-search-point (match-beginning 0)
2510                 bibtex-pop-next-search-point (point))))
2511         (if (eq direction 'previous)
2512             (goto-char bibtex-pop-previous-search-point)
2513           (goto-char bibtex-pop-next-search-point))
2514         ;; Now search for arg'th previous/next similar field
2515         (let ((bounds nil)
2516               (failure nil))
2517           (while (and (not failure) (> arg 0))
2518             (cond ((eq direction 'previous)
2519                    (setq bounds (bibtex-search-backward-field field-name (point-min)))
2520                    (if bounds
2521                        (goto-char (bibtex-start-of-field bounds))
2522                      (setq failure t)))
2523                   ((eq direction 'next)
2524                    (setq bounds (bibtex-search-forward-field field-name (point-max)))
2525                    (if bounds
2526                        (goto-char (bibtex-end-of-field bounds))
2527                      (setq failure t))))
2528             (setq arg (- arg 1)))
2529           (if failure
2530               (error (if (eq direction 'previous)
2531                          "No previous matching BibTeX field."
2532                        "No next matching BibTeX field."))
2533             ;; Found a matching field. Remember boundaries.
2534             (setq bibtex-pop-previous-search-point (bibtex-start-of-field bounds))
2535             (setq bibtex-pop-next-search-point (bibtex-end-of-field bounds))
2536             (setq new-text
2537                   (buffer-substring-no-properties
2538                    (bibtex-start-of-text-in-field bounds)
2539                    (bibtex-end-of-text-in-field bounds)))
2540             (bibtex-flash-head)
2541             ;; Go back to where we started, delete old text, and pop new.
2542             (goto-char stop-old-text)
2543             (delete-region start-old-text stop-old-text)
2544             (insert new-text))))))
2545   (let (bibtex-help-message)
2546     (bibtex-find-text nil))
2547   (setq this-command 'bibtex-pop))
2548
2549 \f
2550 ;; Interactive Functions:
2551
2552 ;;;###autoload
2553 (defun bibtex-mode ()
2554   "Major mode for editing BibTeX files.
2555
2556 To submit a problem report, enter \\[bibtex-submit-bug-report] from a
2557 BibTeX mode buffer.  This automatically sets up a mail buffer with
2558 version information already added.  You just need to add a description
2559 of the problem, including a reproducible test case and send the
2560 message.
2561
2562
2563 General information on working with BibTeX mode:
2564
2565 You should use commands as \\[bibtex-Book] to get a template for a
2566 specific entry. You should then fill in all desired fields using
2567 \\[bibtex-next-field] to jump from field to field. After having filled
2568 in all desired fields in the entry, you should clean the new entry
2569 with command \\[bibtex-clean-entry].
2570
2571 Some features of BibTeX mode are available only by setting variable
2572 bibtex-maintain-sorted-entries to t. However, then BibTeX mode will
2573 work with buffer containing only valid (syntactical correct) entries
2574 and with entries being sorted. This is usually the case, if you have
2575 created a buffer completely with BibTeX mode and finished every new
2576 entry with \\[bibtex-clean-entry].
2577
2578 For third party BibTeX buffers, please call the function
2579 `bibtex-convert-alien' to fully take advantage of all features of
2580 BibTeX mode.
2581
2582
2583 Special information:
2584
2585 A command such as \\[bibtex-Book] will outline the fields for a BibTeX book entry.
2586
2587 The optional fields start with the string OPT, and are thus ignored by BibTeX.
2588 Alternatives from which only one is required start with the string ALT.
2589 The OPT or ALT string may be removed from a field with \\[bibtex-remove-OPT-or-ALT].
2590 \\[bibtex-make-field] inserts a new field after the current one.
2591 \\[bibtex-kill-field] kills the current field entirely.
2592 \\[bibtex-yank] will yank the last recently killed field after the
2593 current field.
2594 \\[bibtex-remove-delimiters] removes the double-quotes or braces around the text of the current field.
2595  \\[bibtex-empty-field] replaces the text of the current field with the default \"\" or {}.
2596
2597 The command \\[bibtex-clean-entry] cleans the current entry, i.e. it removes OPT/ALT
2598 from all non-empty optional or alternative fields, checks that no required
2599 fields are empty, and does some formatting dependent on the value of
2600 bibtex-entry-format.
2601 Note: some functions in BibTeX mode depend on entries being in a special
2602 format (all fields beginning on separate lines), so it is usually a bad
2603 idea to remove `realign' from bibtex-entry-format.
2604
2605 Use \\[bibtex-find-text] to position the cursor at the end of the current field.
2606 Use \\[bibtex-next-field] to move to end of the next field.
2607
2608 The following may be of interest as well:
2609
2610   Functions:
2611     bibtex-entry
2612     bibtex-kill-entry
2613     bibtex-yank-pop
2614     bibtex-pop-previous
2615     bibtex-pop-next
2616     bibtex-complete-string
2617     bibtex-complete-key
2618     bibtex-print-help-message
2619     bibtex-generate-autokey
2620     bibtex-beginning-of-entry
2621     bibtex-end-of-entry
2622     bibtex-reposition-window
2623     bibtex-mark-entry
2624     bibtex-ispell-abstract
2625     bibtex-ispell-entry
2626     bibtex-narrow-to-entry
2627     bibtex-sort-buffer
2628     bibtex-validate
2629     bibtex-count
2630     bibtex-fill-entry
2631     bibtex-reformat
2632     bibtex-convert-alien
2633
2634   Variables:
2635     bibtex-field-delimiters
2636     bibtex-include-OPTcrossref
2637     bibtex-include-OPTkey
2638     bibtex-user-optional-fields
2639     bibtex-entry-format
2640     bibtex-sort-ignore-string-entries
2641     bibtex-maintain-sorted-entries
2642     bibtex-entry-field-alist
2643     bibtex-predefined-strings
2644     bibtex-string-files
2645
2646 ---------------------------------------------------------
2647 Entry to BibTeX mode calls the value of `bibtex-mode-hook' if that value is
2648 non-nil.
2649
2650 \\{bibtex-mode-map}"
2651   (interactive)
2652   (kill-all-local-variables)
2653   (use-local-map bibtex-mode-map)
2654   (setq major-mode 'bibtex-mode)
2655   (setq mode-name "BibTeX")
2656   (set-syntax-table bibtex-mode-syntax-table)
2657   (setq bibtex-strings bibtex-predefined-strings)
2658   (mapcar
2659    (lambda (filename)
2660      ;; collect pathnames
2661      (let* ((path (if bibtex-string-file-path
2662                       bibtex-string-file-path
2663                     "."))
2664             (dirs (split-string path ":+"))
2665             (filename (if (string-match "\.bib$" filename)
2666                           filename
2667                         (concat filename ".bib")))
2668             fullfilename
2669             (item 0)
2670             (size (length dirs)))
2671        ;; test filenames
2672        (while (and
2673                (< item size)
2674                (not (file-readable-p
2675                      (setq fullfilename
2676                            (concat (elt dirs item) "/" filename)))))
2677          (setq item (1+ item)))
2678        (if (< item size)
2679            ;; file was found
2680            (let* ((case-fold-search t)
2681                   (compl nil))
2682              (with-temp-buffer
2683                (insert-file-contents fullfilename)
2684                (goto-char (point-min))
2685                (let ((bounds (bibtex-search-forward-string)))
2686                  (while bounds
2687                    (setq compl
2688                          (cons (list (buffer-substring-no-properties
2689                                       (bibtex-start-of-reference-key-in-string bounds)
2690                                       (bibtex-end-of-reference-key-in-string bounds)))
2691                                compl))
2692                    (goto-char (bibtex-end-of-string bounds))
2693                    (setq bounds (bibtex-search-forward-string)))))
2694              (setq bibtex-strings (append bibtex-strings (nreverse compl))))
2695          (error
2696           "File %s not in paths defined by bibtex-string-file-path variable"
2697           filename))))
2698    bibtex-string-files)
2699   (if bibtex-maintain-sorted-entries
2700       (bibtex-run-with-idle-timer
2701        1 nil
2702        (lambda ()
2703          (bibtex-parse-keys nil t t))))
2704   ;; to get buffer parsed once if everything else (including things
2705   ;; installed in bibtex-mode-hook) has done its work
2706   (if (not bibtex-parse-idle-timer)
2707       (setq bibtex-parse-idle-timer
2708             (bibtex-run-with-idle-timer
2709              bibtex-parse-keys-timeout t
2710              'bibtex-parse-buffers-stealthily)))
2711   ;; Install stealthy parse function if not already installed
2712   (make-local-variable 'paragraph-start)
2713   (setq paragraph-start "[ \f\n\t]*$")
2714   (make-local-variable 'comment-start)
2715   (setq comment-start bibtex-comment-start)
2716   (make-local-variable 'comment-start-skip)
2717   (setq comment-start-skip bibtex-comment-start)
2718   (make-local-variable 'comment-column)
2719   (setq comment-column 0)
2720   (make-local-variable 'defun-prompt-regexp)
2721   (setq defun-prompt-regexp "^@[a-zA-Z0-9]+")
2722   (make-local-variable 'outline-regexp)
2723   (setq outline-regexp "@")
2724   (make-local-variable 'normal-auto-fill-function)
2725   (setq normal-auto-fill-function 'bibtex-do-auto-fill)
2726   (make-local-variable 'font-lock-defaults)
2727   (setq font-lock-defaults
2728         '(bibtex-font-lock-keywords
2729           nil t ((?$ . "\"")
2730                  ;; Mathematical expressions should be fontified as strings
2731                  (?\" . ".")
2732                  ;; Quotes are field delimiters and quote-delimited
2733                  ;; entries should be fontified in the same way as
2734                  ;; brace-delimited ones
2735                  )))
2736   (make-local-variable 'font-lock-mark-block-function)
2737   (setq font-lock-mark-block-function
2738         (lambda ()
2739           (set-mark (bibtex-end-of-entry))
2740           (bibtex-beginning-of-entry)))
2741   (setq imenu-generic-expression
2742         (list (list nil bibtex-entry-head bibtex-key-in-head)))
2743   (setq imenu-case-fold-search t)
2744   ;; XEmacs needs easy-menu-add, Emacs does not care
2745   (easy-menu-add bibtex-edit-menu)
2746   (easy-menu-add bibtex-entry-menu)
2747   (run-hooks 'bibtex-mode-hook))
2748
2749 (defun bibtex-submit-bug-report ()
2750   "Submit via mail a bug report on bibtex.el."
2751   (interactive)
2752   (if (y-or-n-p "Do you want to submit a bug report on BibTeX mode? ")
2753       (progn
2754         (require 'reporter)
2755         (let ((reporter-prompt-for-summary-p t))
2756           (reporter-submit-bug-report
2757            bibtex-maintainer-address
2758            "bibtex.el"
2759            (list
2760             'system-configuration
2761             'system-configuration-options
2762             'bibtex-mode-hook
2763             'bibtex-parse-keys-timeout
2764             ;; possible general errors
2765             'bibtex-sort-ignore-string-entries
2766             'bibtex-maintain-sorted-entries
2767             'bibtex-entry-delimiters
2768             'bibtex-field-delimiters
2769             'bibtex-comma-after-last-field
2770             'bibtex-entry-offset
2771             'bibtex-field-indentation
2772             'bibtex-text-indentation
2773             'bibtex-contline-indentation
2774             'bibtex-align-at-equal-sign
2775             ;; possible sorting and parsing bugs
2776             'bibtex-entry-format
2777             'bibtex-add-entry-hook
2778             'bibtex-clean-entry-hook
2779             ;; possible cleaning error
2780             'bibtex-user-optional-fields
2781             ;; possible format error
2782             'bibtex-predefined-month-strings
2783             'bibtex-predefined-strings
2784             'bibtex-string-files
2785             'bibtex-string-file-path
2786             ;; possible format error
2787             'bibtex-font-lock-keywords
2788             ;; possible bugs regarding fontlocking
2789             'bibtex-autokey-prefix-string
2790             'bibtex-autokey-names
2791             'bibtex-autokey-names-stretch
2792             'bibtex-autokey-additional-names
2793             'bibtex-autokey-transcriptions
2794             'bibtex-autokey-name-change-strings
2795             'bibtex-autokey-name-case-convert
2796             'bibtex-autokey-name-length
2797             'bibtex-autokey-name-separator
2798             'bibtex-autokey-year-length
2799             'bibtex-autokey-year-use-crossref-entry
2800             'bibtex-autokey-titlewords
2801             'bibtex-autokey-title-terminators
2802             'bibtex-autokey-titlewords-stretch
2803             'bibtex-autokey-titleword-ignore
2804             'bibtex-autokey-titleword-case-convert
2805             'bibtex-autokey-titleword-abbrevs
2806             'bibtex-autokey-titleword-change-strings
2807             'bibtex-autokey-titleword-length
2808             'bibtex-autokey-titleword-separator
2809             'bibtex-autokey-name-year-separator
2810             'bibtex-autokey-year-title-separator
2811             'bibtex-autokey-edit-before-use
2812             'bibtex-autokey-before-presentation-function
2813             ;; possible bugs regarding automatic reference keys
2814             'bibtex-entry-field-alist
2815             ;; possible format error
2816             'bibtex-help-message
2817             'bibtex-include-OPTcrossref
2818             'bibtex-include-OPTkey
2819             'bibtex-field-kill-ring-max
2820             'bibtex-entry-kill-ring-max
2821             ;; user variables which shouldn't cause any errors
2822             )
2823            nil nil
2824            (concat bibtex-maintainer-salutation "
2825
2826 I want to report a bug on Emacs BibTeX mode.
2827
2828 I've read the `Bugs' section in the `Emacs' info page, so I know how
2829 to make a clear and unambiguous report. I have started a fresh Emacs
2830 via `"invocation-name " --no-init-file --no-site-file', thereafter (in
2831 case I'm reporting on a version of `bibtex.el' which is not part of
2832 the standard emacs distribution) I loaded the questionable version
2833 of `bibtex.el' with `M-x load-file', and then, to produce the buggy
2834 behaviour, I did the following:")))
2835         (message nil))))
2836
2837 (defun bibtex-entry (entry-type)
2838   "Insert a new BibTeX entry.
2839 After insertion it calls the functions in `bibtex-add-entry-hook'."
2840   (interactive (let* ((completion-ignore-case t)
2841                       (e-t (completing-read
2842                             "Entry Type: "
2843                             bibtex-entry-field-alist
2844                             nil t nil 'bibtex-entry-type-history)))
2845                  (list e-t)))
2846   (if (not bibtex-reference-keys)
2847       (bibtex-parse-keys nil t))
2848   (let* (required
2849          optional
2850          (key
2851           (if bibtex-maintain-sorted-entries
2852               (completing-read
2853                (format "%s key: " entry-type)
2854                bibtex-reference-keys nil nil nil 'bibtex-key-history)))
2855          (e (assoc-ignore-case entry-type bibtex-entry-field-alist))
2856          (r-n-o (elt e 1))
2857          (c-ref (elt e 2)))
2858     (if (not e)
2859         (error "Bibtex entry type %s not defined" entry-type))
2860     (if (and
2861          (member entry-type bibtex-include-OPTcrossref)
2862          c-ref)
2863         (setq required (elt c-ref 0)
2864               optional (elt c-ref 1))
2865       (setq required (elt r-n-o 0)
2866             optional (elt r-n-o 1)))
2867     (if bibtex-maintain-sorted-entries
2868         (bibtex-find-entry-location key)
2869       (bibtex-move-outside-of-entry))
2870     (indent-to-column bibtex-entry-offset)
2871     (insert "@" entry-type (bibtex-entry-left-delimiter))
2872     (if key
2873         (insert key))
2874     (save-excursion
2875       (mapcar 'bibtex-make-field required)
2876       (if (member entry-type bibtex-include-OPTcrossref)
2877           (bibtex-make-optional-field '("crossref")))
2878       (if bibtex-include-OPTkey
2879           (if (or
2880                (stringp bibtex-include-OPTkey)
2881                (fboundp bibtex-include-OPTkey))
2882               (bibtex-make-optional-field
2883                (list "key" nil bibtex-include-OPTkey))
2884             (bibtex-make-optional-field '("key"))))
2885       (mapcar 'bibtex-make-optional-field optional)
2886       (mapcar 'bibtex-make-optional-field bibtex-user-optional-fields)
2887       (if bibtex-comma-after-last-field
2888           (insert ","))
2889       (insert "\n")
2890       (indent-to-column bibtex-entry-offset)
2891       (insert (bibtex-entry-right-delimiter) "\n\n"))
2892     (bibtex-next-field t)
2893     (run-hooks 'bibtex-add-entry-hook)))
2894
2895 (defun bibtex-print-help-message ()
2896   "Prints helpful information about current field in current BibTeX entry."
2897   (interactive)
2898   (let* ((case-fold-search t)
2899          (pnt (point))
2900          (field-name
2901           (let* ((bounds (bibtex-enclosing-field))
2902                  (mb (bibtex-start-of-name-in-field bounds))
2903                  (me (bibtex-end-of-name-in-field bounds)))
2904             (goto-char mb)
2905             (buffer-substring-no-properties
2906              (if (looking-at "OPT\\|ALT")
2907                  (+ 3 mb)
2908                mb)
2909              me)))
2910          (entry-type
2911           (progn
2912             (re-search-backward
2913              bibtex-entry-maybe-empty-head nil t)
2914             (buffer-substring-no-properties
2915              (1+ (match-beginning bibtex-type-in-head))
2916              (match-end bibtex-type-in-head))))
2917          (entry-list
2918           (assoc-ignore-case entry-type
2919                                bibtex-entry-field-alist))
2920          (c-r-list (elt entry-list 2))
2921          (req-opt-list
2922           (if (and
2923                (member entry-type bibtex-include-OPTcrossref)
2924                c-r-list)
2925               c-r-list
2926             (elt entry-list 1)))
2927          (list-of-entries (append
2928                            (elt req-opt-list 0)
2929                            (elt req-opt-list 1)
2930                            bibtex-user-optional-fields
2931                            (if (member
2932                                 entry-type
2933                                 bibtex-include-OPTcrossref)
2934                                '(("crossref"
2935                                   "Reference key of the crossreferenced entry")))
2936                            (if bibtex-include-OPTkey
2937                                '(("key"
2938                                   "Used for reference key creation if author and editor fields are missing"))))))
2939     (goto-char pnt)
2940     (let ((comment (assoc-ignore-case field-name list-of-entries)))
2941       (if comment
2942           (message (elt comment 1))
2943         (message "NO COMMENT AVAILABLE")))))
2944
2945 (defun bibtex-make-field (e-t &optional called-by-yank)
2946   "Makes a field named E-T in current BibTeX entry.
2947 This function is for interactive and non-interactive purposes.  To call
2948 it interactively, just give it no arguments and enter the field name
2949 using the minibuffer."
2950   (interactive "*P")
2951   (if (not e-t)
2952       (setq
2953        e-t
2954        (let* ((entry-type
2955                (save-excursion
2956                  (bibtex-enclosing-entry-maybe-empty-head)
2957                  (buffer-substring-no-properties
2958                   (1+ (match-beginning bibtex-type-in-head))
2959                   (match-end bibtex-type-in-head))))
2960               (fl
2961                (car (cdr (assoc-ignore-case
2962                           entry-type bibtex-entry-field-alist))))
2963               (field-list
2964                (append
2965                 (elt fl 0) (elt fl 1) bibtex-user-optional-fields
2966                 (if bibtex-include-OPTcrossref '(("crossref" nil)))
2967                 (if bibtex-include-OPTkey '(("key" nil)))))
2968               (completion-ignore-case t))
2969          (completing-read
2970           "BibTeX field name: " field-list
2971           nil nil nil bibtex-field-history))))
2972   (if (not (consp e-t))
2973       (setq e-t (list e-t)))
2974   (if (equal (length e-t) 1)
2975       (setq e-t (append e-t (list ""))))
2976   (if (equal (length e-t) 2)
2977       (setq e-t (append e-t (list ""))))
2978   (let ((name (if (elt e-t 3)
2979                   (concat "ALT" (car e-t))
2980                 (car e-t))))
2981     (if (or (interactive-p) called-by-yank)
2982         (let (bibtex-help-message)
2983           (bibtex-find-text nil t)
2984           (if (looking-at "[}\"]")
2985               (forward-char))))
2986     (insert ",\n")
2987     (indent-to-column
2988      (+ bibtex-entry-offset bibtex-field-indentation))
2989     (insert name " ")
2990     (if bibtex-align-at-equal-sign
2991         (indent-to-column
2992          (+ bibtex-entry-offset (- bibtex-text-indentation 2))))
2993     (insert "= ")
2994     (if (not bibtex-align-at-equal-sign)
2995         (indent-to-column
2996          (+ bibtex-entry-offset bibtex-text-indentation)))
2997     (insert (if called-by-yank
2998                 ""
2999               (bibtex-field-left-delimiter))
3000             (let ((init (elt e-t 2)))
3001               (cond
3002                ((stringp init)
3003                 init)
3004                ((fboundp init)
3005                 (funcall init))
3006                (t
3007                 (error "%s is neither a string nor a function" init))))
3008             (if called-by-yank
3009                 ""
3010               (bibtex-field-right-delimiter)))
3011     (if (interactive-p)
3012         (forward-char -1))))
3013
3014 (defun bibtex-beginning-of-entry ()
3015   "Move to beginning of BibTeX entry.
3016 If inside an entry, move to the beginning of it, otherwise move to the
3017 beginning of the previous entry.
3018 If called from a program, this function returns the new location of point."
3019   (interactive)
3020   (skip-chars-forward " \t")
3021   (if (looking-at "@")
3022       (forward-char))
3023   (re-search-backward "^[ \t]*@" nil 'move))
3024
3025 (defun bibtex-end-of-entry ()
3026   "Move to end of BibTeX entry.
3027 If inside an entry, move to the end of it, otherwise move to the end
3028 of the previous entry.
3029 If called from a program, this function returns the new location of point."
3030   (interactive)
3031   (let* ((case-fold-search t)
3032          (valid-entry-head
3033           (concat "[ \t]*@[ \t]*\\("
3034                   (mapconcat
3035                    (lambda (type)
3036                      (concat "\\(" (car type) "\\)"))
3037                    bibtex-entry-field-alist
3038                    "\\|")
3039                   "\\)"))
3040          (org (point))
3041          (pnt (bibtex-beginning-of-entry))
3042          err)
3043     (cond
3044      ((bibtex-parse-string)
3045       (let ((bounds (bibtex-parse-string)))
3046         (goto-char (bibtex-end-of-string bounds))))
3047      ((looking-at "[ \t]*@[ \t]*preamble[ \t\n]*")
3048       (goto-char (match-end 0))
3049       (cond
3050        ((looking-at "(")
3051         (if (not (re-search-forward ")[ \t]*\n\n" nil 'move))
3052             (setq err t)))
3053        ((looking-at "{")
3054         (if (not (re-search-forward "}[ \t]*\n\n" nil 'move))
3055             (setq err t)))
3056        (t
3057         (setq err t)))
3058       (if (not err)
3059           (progn
3060             (goto-char (match-beginning 0))
3061             (forward-char))))
3062      ((looking-at valid-entry-head)
3063       (bibtex-search-entry t nil t)
3064       (if (not (equal (match-beginning 0) pnt))
3065           (setq err t)))
3066      (t
3067       (if (interactive-p)
3068           (message "Not on a known BibTeX entry."))
3069       (goto-char org)))
3070     (if err
3071         (progn
3072           (goto-char pnt)
3073           (error "Syntactical incorrect entry starts here"))))
3074   (point))
3075
3076 (defun bibtex-reposition-window (arg)
3077   "Make the current BibTeX entry visible."
3078   (interactive "P")
3079   (save-excursion
3080     (goto-char
3081      (/ (+ (bibtex-beginning-of-entry) (bibtex-end-of-entry)) 2))
3082     (recenter arg)))
3083
3084 (defun bibtex-mark-entry ()
3085   "Put mark at beginning, point at end of current BibTeX entry."
3086   (interactive)
3087   (set-mark (bibtex-beginning-of-entry))
3088   (bibtex-end-of-entry))
3089
3090 (defun bibtex-count-entries (&optional count-string-entries)
3091   "Count number of entries in current buffer or region.
3092 With prefix argument COUNT-STRING-ENTRIES it counts all entries,
3093 otherwise it counts all except Strings.
3094 If mark is active it counts entries in region, if not in whole buffer."
3095   (interactive "P")
3096   (let ((pnt (point))
3097         (start-point
3098          (if (bibtex-mark-active)
3099              (region-beginning)
3100            (bibtex-beginning-of-first-entry)))
3101         (end-point
3102          (if (bibtex-mark-active)
3103              (region-end)
3104            (point-max)))
3105         (number 0)
3106         (bibtex-sort-ignore-string-entries
3107          (not count-string-entries)))
3108     (save-restriction
3109       (narrow-to-region start-point end-point)
3110       (goto-char start-point)
3111       (bibtex-map-entries
3112        (lambda (current)
3113          (setq number (1+ number)))))
3114     (message (concat (if (bibtex-mark-active) "Region" "Buffer")
3115                      " contains %d entries.") number)
3116     (goto-char pnt)))
3117
3118 (defun bibtex-ispell-entry ()
3119   "Spell whole BibTeX entry."
3120   (interactive)
3121   (ispell-region (bibtex-beginning-of-entry) (bibtex-end-of-entry)))
3122
3123 (defun bibtex-ispell-abstract ()
3124   "Spell abstract of BibTeX entry."
3125   (interactive)
3126   (let* ((case-fold-search t)
3127          (pnt (bibtex-end-of-entry)))
3128     (bibtex-beginning-of-entry)
3129     (let ((bounds (bibtex-search-forward-field "abstract" pnt)))
3130       (if bounds
3131           (ispell-region (bibtex-start-of-text-in-field bounds) (bibtex-end-of-text-in-field bounds))
3132         (error "No abstract in entry")))))
3133
3134 (defun bibtex-narrow-to-entry ()
3135   "Narrow buffer to current BibTeX entry."
3136   (interactive)
3137   (save-excursion
3138     (narrow-to-region
3139      (bibtex-beginning-of-entry) (bibtex-end-of-entry))))
3140
3141 (defun bibtex-sort-buffer ()
3142   "Sort BibTeX buffer alphabetically by key.
3143 Text outside of BibTeX entries is not affected.  If
3144 `bibtex-sort-ignore-string-entries' is non-nil, @String entries will be
3145 ignored."
3146   (interactive)
3147   (save-restriction
3148     (narrow-to-region
3149      (bibtex-beginning-of-first-entry)
3150      (save-excursion
3151        (goto-char (point-max))
3152        (bibtex-end-of-entry)))
3153     (bibtex-skip-to-valid-entry)
3154     (sort-subr
3155      nil
3156      ;; NEXTREC function
3157      'bibtex-skip-to-valid-entry
3158      ;; ENDREC function
3159      'bibtex-end-of-entry
3160      ;; STARTKEY function
3161      (lambda ()
3162        (let* ((case-fold-search t))
3163          (re-search-forward bibtex-entry-head)
3164          (buffer-substring-no-properties
3165           (match-beginning bibtex-key-in-head)
3166           (match-end bibtex-key-in-head)))))))
3167
3168 (defun bibtex-find-entry-location (entry-name &optional ignore-dups)
3169   "Looking for place to put the BibTeX entry named ENTRY-NAME.
3170 Performs a binary search (therefore, buffer is assumed to be in sorted
3171 order, without duplicates (see \\[bibtex-validate]), if it is
3172 not, `bibtex-find-entry-location' will fail).  If entry-name is already
3173 used as a reference key, an error is signaled.  However, if optional
3174 variable IGNORE-DUPS is non-nil, no error messages about duplicate
3175 entries are signaled, but the error handling is assumed to be made in
3176 the calling function.
3177 The value is nil if a duplicate entry error occurred,
3178 and t in all other cases."
3179   (let* ((case-fold-search t)
3180          (left
3181           (progn
3182             (bibtex-beginning-of-first-entry)
3183             (bibtex-skip-to-valid-entry)
3184             (bibtex-end-of-entry)))
3185          (right
3186           (progn
3187             (bibtex-beginning-of-last-entry)
3188             (bibtex-skip-to-valid-entry t)
3189             (point)))
3190          actual-point
3191          actual-key
3192          (done (>= left right))
3193          new
3194          dup)
3195     (while (not done)
3196       (setq actual-point (/ (+ left right) 2))
3197       (goto-char actual-point)
3198       (bibtex-skip-to-valid-entry t)
3199       (setq actual-key
3200             (progn
3201               (re-search-forward bibtex-entry-head)
3202               (buffer-substring-no-properties
3203                (match-beginning bibtex-key-in-head)
3204                (match-end bibtex-key-in-head))))
3205       (cond
3206        ((string-lessp entry-name actual-key)
3207         (setq new (bibtex-beginning-of-entry))
3208         (if (equal right new)
3209             (setq done t)
3210           (setq right new)))
3211        ((string-lessp actual-key entry-name)
3212         (setq new (bibtex-end-of-entry))
3213         (if (equal left new)
3214             (setq done t)
3215           (setq left new)))
3216        ((string-equal actual-key entry-name)
3217         (setq dup t
3218               done t)
3219         (if (not ignore-dups)
3220             (progn
3221               (bibtex-beginning-of-entry)
3222               (error "Entry with key `%s' already exists" entry-name))))))
3223     (if dup
3224         (progn
3225           (bibtex-beginning-of-entry)
3226           nil)
3227       (goto-char right)
3228       (setq actual-key
3229             (if (looking-at bibtex-entry-head)
3230                 (buffer-substring-no-properties
3231                  (match-beginning bibtex-key-in-entry)
3232                  (match-end bibtex-key-in-entry))))
3233       (if (or
3234            (not actual-key)
3235            (string-lessp actual-key entry-name))
3236           ;; buffer contains no valid entries or
3237           ;; greater than last entry --> append
3238           (progn
3239             (bibtex-end-of-entry)
3240             (if (not (bobp))
3241                 (newline (forward-line 2)))
3242             (beginning-of-line))
3243         (goto-char right))
3244       t)))
3245
3246 (defun bibtex-validate (&optional test-thoroughly)
3247   "Validate if buffer or region is syntactically correct.
3248 Only known entry types are checked, so you can put comments
3249 outside of entries.
3250 With optional argument TEST-THOROUGHLY non-nil it checks for absence of
3251 required fields and questionable month fields as well.
3252 If mark is active, it validates current region, if not whole buffer.
3253 Returns t if test was successful, nil otherwise."
3254   (interactive "P")
3255   (let* (error-list
3256          syntax-error
3257          (case-fold-search t)
3258          (valid-bibtex-entry
3259           (concat
3260            "@[ \t]*\\(\\(string\\)\\|"
3261            (mapconcat
3262             (lambda (type)
3263               (concat "\\(" (car type) "\\)"))
3264             bibtex-entry-field-alist
3265             "\\|")
3266            "\\)"))
3267          (pnt (point))
3268          (start-point
3269           (if (bibtex-mark-active)
3270               (region-beginning)
3271             (bibtex-beginning-of-first-entry)))
3272          (end-point
3273           (if (bibtex-mark-active)
3274               (region-end)
3275             (point-max))))
3276     (save-restriction
3277       (narrow-to-region start-point end-point)
3278       ;; looking if entries fit syntactical structure
3279       (goto-char start-point)
3280       (bibtex-progress-message "Checking syntactical structure")
3281       (while (re-search-forward "^[ \t]*@" nil t)
3282         (bibtex-progress-message)
3283         (forward-char -1)
3284         (let ((p (point))
3285               (must-match
3286                (looking-at valid-bibtex-entry)))
3287           (if (not must-match)
3288               (forward-char)
3289             (let (bibtex-sort-ignore-string-entries)
3290               (bibtex-skip-to-valid-entry))
3291             (if (equal (point) p)
3292                 (forward-char)
3293               (goto-char p)
3294               (setq
3295                error-list
3296                (cons (list
3297                       (bibtex-current-line)
3298                       "Syntax error (check esp. commas, braces, and quotes)")
3299                      error-list))
3300               (forward-char)))))
3301       (bibtex-progress-message 'done)
3302       (if error-list
3303           (setq syntax-error t)
3304         ;; looking for correct sort order and duplicates (only if
3305         ;; there were no syntax errors)
3306         (if bibtex-maintain-sorted-entries
3307             (let (previous)
3308               (goto-char start-point)
3309               (bibtex-progress-message "Checking correct sort order")
3310               (bibtex-map-entries
3311                (lambda (current)
3312                  (bibtex-progress-message)
3313                  (cond ((or (not previous)
3314                             (string< previous current))
3315                         (setq previous current))
3316                        ((string-equal previous current)
3317                         (setq
3318                          error-list
3319                          (cons (list (bibtex-current-line)
3320                                      "Duplicate key with previous")
3321                                error-list)))
3322                        (t
3323                         (setq previous current
3324                               error-list
3325                               (cons (list (bibtex-current-line)
3326                                           "Entries out of order")
3327                                     error-list))))))
3328               (bibtex-progress-message 'done)))
3329         (if test-thoroughly
3330             (progn
3331               (goto-char start-point)
3332               (bibtex-progress-message
3333                "Checking required fields and month fields")
3334               (let ((bibtex-sort-ignore-string-entries t)
3335                     (questionable-month
3336                      (concat
3337                       "[{\"]\\("
3338                       (mapconcat
3339                        (lambda (mon)
3340                          (concat "\\(" (car mon) "\\)"))
3341                        bibtex-predefined-month-strings
3342                        "\\|")
3343                       "\\)[}\"]")))
3344                 (bibtex-map-entries
3345                  (lambda (current)
3346                    (bibtex-progress-message)
3347                    (let* ((beg (bibtex-beginning-of-entry))
3348                           (end (bibtex-end-of-entry))
3349                           (entry-list
3350                            (progn
3351                              (goto-char beg)
3352                              (bibtex-search-entry nil end)
3353                              (assoc-ignore-case
3354                               (buffer-substring-no-properties
3355                                (1+ (match-beginning bibtex-type-in-head))
3356                                (match-end bibtex-type-in-head))
3357                               bibtex-entry-field-alist)))
3358                           (req (copy-sequence (elt (elt entry-list 1) 0)))
3359                           (creq (copy-sequence (elt (elt entry-list 2) 0)))
3360                           crossref-there)
3361                      (goto-char beg)
3362                      (let ((bounds (bibtex-search-forward-field bibtex-field-name end)))
3363                        (while bounds
3364                          (let ((field-name
3365                                 (buffer-substring-no-properties
3366                                  (bibtex-start-of-name-in-field bounds)
3367                                  (bibtex-end-of-name-in-field bounds))))
3368                            (if (and (equal (downcase field-name) "month")
3369                                     (string-match
3370                                      questionable-month
3371                                      (buffer-substring-no-properties
3372                                       (bibtex-start-of-text-in-field bounds)
3373                                       (bibtex-end-of-text-in-field bounds))))
3374                                (setq
3375                                 error-list
3376                                 (cons
3377                                  (list
3378                                   (bibtex-current-line)
3379                                   "Questionable month field (delimited string)")
3380                                  error-list)))
3381                            (setq
3382                             req
3383                             (delete (assoc-ignore-case field-name req) req)
3384                             creq
3385                             (delete (assoc-ignore-case field-name creq) creq))
3386                            (if (equal (downcase field-name) "crossref")
3387                                (setq crossref-there t)))
3388                          (goto-char (bibtex-end-of-field bounds))
3389                          (setq bounds (bibtex-search-forward-field bibtex-field-name end))))
3390                      (if crossref-there
3391                          (setq req creq))
3392                      (if (or (> (length req) 1)
3393                              (and (= (length req) 1)
3394                                   (not (elt (car req) 3))))
3395                          ;; two (or more) fields missed or one field
3396                          ;; missed and this isn't flagged alternative
3397                          ;; (notice that this fails if there are more
3398                          ;; than two alternatives in a BibTeX entry,
3399                          ;; which isn't the case momentarily)
3400                          (setq
3401                           error-list
3402                           (cons
3403                            (list (save-excursion
3404                                    (bibtex-beginning-of-entry)
3405                                    (bibtex-current-line))
3406                                  (concat
3407                                   "Required field \""
3408                                   (car (car req))
3409                                   "\" missing"))
3410                            error-list)))))))
3411               (bibtex-progress-message 'done)))))
3412     (goto-char pnt)
3413     (if error-list
3414         (let ((bufnam (buffer-name))
3415               (dir default-directory))
3416           (setq error-list
3417                 (sort error-list
3418                       (lambda (a b)
3419                         (< (car a) (car b)))))
3420           (let ((pop-up-windows t))
3421             (pop-to-buffer nil t))
3422           (switch-to-buffer
3423            (get-buffer-create "*BibTeX validation errors*") t)
3424           ;; don't use switch-to-buffer-other-window, since this
3425           ;; doesn't allow the second parameter NORECORD
3426           (setq default-directory dir)
3427           (toggle-read-only -1)
3428           (compilation-mode)
3429           (delete-region (point-min) (point-max))
3430           (goto-char (point-min))
3431           (insert
3432            "BibTeX mode command `bibtex-validate'\n"
3433            (if syntax-error
3434                "Maybe undetected errors due to syntax errors. Correct and validate again."
3435              "")
3436            "\n")
3437           (while error-list
3438             (insert
3439              bufnam ":" (number-to-string (elt (car error-list) 0))
3440              ": " (elt (car error-list) 1) "\n")
3441             (setq error-list (cdr error-list)))
3442           (compilation-parse-errors nil nil)
3443           (setq compilation-old-error-list compilation-error-list)
3444           ;; this is necessary to avoid reparsing of buffer if you
3445           ;; switch to compilation buffer and enter
3446           ;; `compile-goto-error'
3447           (set-buffer-modified-p nil)
3448           (toggle-read-only 1)
3449           (goto-char (point-min))
3450           (other-window -1)
3451           ;; return nil
3452           nil)
3453       (if (bibtex-mark-active)
3454           (message "Region is syntactically correct")
3455         (message "Buffer is syntactically correct"))
3456       t)))
3457
3458 (defun bibtex-next-field (arg)
3459   "Finds end of text of next BibTeX field; with ARG, to its beginning."
3460   (interactive "P")
3461   (bibtex-inside-field)
3462   (let ((start (point)))
3463     (condition-case ()
3464         (let ((bounds (bibtex-enclosing-field)))
3465           (goto-char (bibtex-end-of-field bounds))
3466           (forward-char 2))
3467       (error
3468        (goto-char start)
3469        (end-of-line)
3470        (forward-char))))
3471   (bibtex-find-text arg t))
3472
3473 (defun bibtex-find-text (arg &optional as-if-interactive silent)
3474   "Go to end of text of current field; with ARG, go to beginning."
3475   (interactive "P")
3476   (bibtex-inside-field)
3477   (let ((bounds (bibtex-enclosing-field (or (interactive-p) as-if-interactive))))
3478     (if bounds
3479         (progn
3480           (if arg
3481               (progn
3482                 (goto-char (bibtex-start-of-text-in-field bounds))
3483                 (if (looking-at "[{\"]")
3484                     (forward-char)))
3485             (goto-char (bibtex-end-of-text-in-field bounds))
3486             (if (or
3487                  (= (preceding-char) ?})
3488                  (= (preceding-char) ?\"))
3489                 (forward-char -1)))
3490           (if bibtex-help-message
3491               (bibtex-print-help-message)))
3492       (beginning-of-line)
3493       (cond
3494        ((bibtex-parse-string)
3495         (let ((bounds (bibtex-parse-string)))
3496           (goto-char
3497            (if arg
3498                (bibtex-start-of-text-in-string bounds)
3499              (bibtex-end-of-text-in-string bounds)))))
3500        ((looking-at bibtex-entry-maybe-empty-head)
3501         (goto-char
3502          (if arg
3503              (match-beginning bibtex-key-in-head)
3504            (match-end 0))))
3505        (t
3506         (if (not silent)
3507             (error "Not on BibTeX field")))))))
3508
3509 (defun bibtex-remove-OPT-or-ALT ()
3510   "Removes the string starting optional/alternative fields.
3511 Aligns text and goes thereafter to end of text."
3512   (interactive)
3513   (bibtex-inside-field)
3514   (let* ((case-fold-search t)
3515          (bounds (bibtex-enclosing-field)))
3516     (save-excursion
3517       (goto-char (bibtex-start-of-name-in-field bounds))
3518       (if (looking-at "OPT\\|ALT")
3519           (progn
3520             (delete-char (length "OPT"))
3521             ;; make field non-OPT
3522             (search-forward "=")
3523             (forward-char -1)
3524             (delete-horizontal-space)
3525             (if bibtex-align-at-equal-sign
3526                 (indent-to-column (- bibtex-text-indentation 2))
3527               (insert " "))
3528             (search-forward "=")
3529             (delete-horizontal-space)
3530             (if bibtex-align-at-equal-sign
3531                 (insert " ")
3532               (indent-to-column bibtex-text-indentation)))))
3533     (bibtex-inside-field)))
3534
3535 (defun bibtex-remove-delimiters ()
3536   "Removes \"\" or {} around string."
3537   (interactive)
3538   (save-excursion
3539     (bibtex-inside-field)
3540     (let* ((case-fold-search t)
3541            (bounds (bibtex-enclosing-field))
3542            (stop (copy-marker (bibtex-end-of-text-in-field bounds))))
3543       (goto-char (bibtex-start-of-text-in-field bounds))
3544       (let* ((boundaries (bibtex-search-forward-field-string stop)))
3545         (while boundaries
3546           (let ((text-end (copy-marker (cdr boundaries))))
3547             (goto-char (car boundaries))
3548             (delete-char 1)
3549             (goto-char text-end)
3550             (delete-backward-char 1)
3551             (setq boundaries (bibtex-search-forward-field-string stop))))))))
3552
3553 (defun bibtex-kill-field (&optional copy-only)
3554   "Kills the entire enclosing BibTeX field.
3555 With prefix arg COPY-ONLY, copy the current field to `bibtex-field-kill-ring,'
3556 but do not actually kill it."
3557   (interactive "P")
3558   (let* ((pnt (point))
3559          (case-fold-search t))
3560     (bibtex-inside-field)
3561     (let* ((bounds (bibtex-enclosing-field))
3562            (the-end (bibtex-end-of-field bounds))
3563            (the-beginning (bibtex-start-of-field bounds)))
3564       (goto-char the-end)
3565       (skip-chars-forward " \t\n,")
3566       (setq
3567        bibtex-field-kill-ring
3568        (cons
3569         (list
3570          'field
3571          (buffer-substring-no-properties
3572           (bibtex-start-of-name-in-field bounds)
3573           (bibtex-end-of-name-in-field bounds))
3574          (buffer-substring-no-properties
3575           (bibtex-start-of-text-in-field bounds)
3576           (bibtex-end-of-text-in-field bounds)))
3577         bibtex-field-kill-ring))
3578       (if (> (length bibtex-field-kill-ring) bibtex-field-kill-ring-max)
3579           (setcdr
3580            (nthcdr (1- bibtex-field-kill-ring-max) bibtex-field-kill-ring)
3581            nil))
3582       (setq bibtex-field-kill-ring-yank-pointer bibtex-field-kill-ring)
3583       (if copy-only
3584           (goto-char pnt)
3585         (delete-region the-beginning the-end)
3586         (let (bibtex-help-message)
3587           (bibtex-find-text nil t t)))))
3588   (setq bibtex-last-kill-command 'field))
3589
3590 (defun bibtex-copy-field-as-kill ()
3591   (interactive)
3592   (bibtex-kill-field t))
3593
3594 (defun bibtex-kill-entry (&optional copy-only)
3595   "Kill the entire enclosing BibTeX entry.
3596 With prefix arg COPY-ONLY the current entry to
3597 `bibtex-entry-kill-ring', but do not actually kill it."
3598   (interactive "P")
3599   (let* ((pnt (point))
3600          (case-fold-search t)
3601          (beg (bibtex-beginning-of-entry))
3602          (end
3603           (progn
3604             (bibtex-end-of-entry)
3605             (if (re-search-forward
3606                  bibtex-entry-maybe-empty-head nil 'move)
3607                 (goto-char (match-beginning 0)))
3608             (point))))
3609     (setq
3610      bibtex-entry-kill-ring
3611      (cons
3612       (list 'entry (buffer-substring-no-properties beg end))
3613       bibtex-entry-kill-ring))
3614     (if (> (length bibtex-entry-kill-ring) bibtex-entry-kill-ring-max)
3615         (setcdr
3616          (nthcdr (1- bibtex-entry-kill-ring-max) bibtex-entry-kill-ring)
3617          nil))
3618     (setq bibtex-entry-kill-ring-yank-pointer bibtex-entry-kill-ring)
3619     (if copy-only
3620         (goto-char pnt)
3621       (delete-region beg end)))
3622   (setq bibtex-last-kill-command 'entry))
3623
3624 (defun bibtex-copy-entry-as-kill ()
3625   (interactive)
3626   (bibtex-kill-entry t))
3627
3628 (defun bibtex-yank (&optional n)
3629   "Reinsert the last BibTeX item.
3630 More precisely, reinsert the field or entry killed or yanked most recently.
3631 With argument N, reinsert the Nth most recently killed BibTeX item.
3632 See also the command \\[bibtex-yank-pop]]."
3633   (interactive "*p")
3634   (bibtex-insert-current-kill (1- n))
3635   (setq this-command 'bibtex-yank))
3636
3637 (defun bibtex-yank-pop (n)
3638   "Replace just-yanked killed BibTeX item with a different.
3639 This command is allowed only immediately after a `bibtex-yank' or a
3640 `bibtex-yank-pop'.
3641 At such a time, the region contains a reinserted previously killed
3642 BibTeX item.  `bibtex-yank-pop' deletes that item and inserts in its
3643 place a different killed BibTeX item.
3644
3645 With no argument, the previous kill is inserted.
3646 With argument N, insert the Nth previous kill.
3647 If N is negative, this is a more recent kill.
3648
3649 The sequence of kills wraps around, so that after the oldest one
3650 comes the newest one."
3651   (interactive "*p")
3652   (if (not (eq last-command 'bibtex-yank))
3653       (error "Previous command was not a BibTeX yank"))
3654   (setq this-command 'bibtex-yank)
3655   (let ((inhibit-read-only t))
3656     (delete-region (point) (mark t))
3657     (bibtex-insert-current-kill n)))
3658
3659 (defun bibtex-empty-field ()
3660   "Delete the text part of the current field, replace with empty text."
3661   (interactive)
3662   (bibtex-inside-field)
3663   (let ((bounds (bibtex-enclosing-field)))
3664     (goto-char (bibtex-start-of-text-in-field bounds))
3665     (delete-region (point) (bibtex-end-of-text-in-field bounds))
3666     (insert (concat (bibtex-field-left-delimiter)
3667                     (bibtex-field-right-delimiter)) )
3668     (bibtex-find-text t)))
3669
3670 (defun bibtex-pop-previous (arg)
3671   "Replace text of current field with the similar field in previous entry.
3672 With arg, goes up ARG entries.  Repeated, goes up so many times.  May be
3673 intermixed with \\[bibtex-pop-next] (bibtex-pop-next)."
3674   (interactive "p")
3675   (bibtex-pop arg 'previous))
3676
3677 (defun bibtex-pop-next (arg)
3678   "Replace text of current field with the text of similar field in next entry.
3679 With arg, goes down ARG entries.  Repeated, goes down so many times.  May be
3680 intermixed with \\[bibtex-pop-previous] (bibtex-pop-previous)."
3681   (interactive "p")
3682   (bibtex-pop arg 'next))
3683
3684 (defun bibtex-clean-entry (&optional new-reference-key called-by-reformat)
3685   "Finish editing the current BibTeX entry and clean it up.
3686 Checks that no required fields are empty and formats entry dependent
3687 on the value of bibtex-entry-format.
3688 If the reference key of the entry is empty or a prefix argument is given,
3689 calculate a new reference key (note: this only will work if fields in entry
3690 begin on separate lines prior to calling bibtex-clean-entry or if 'realign is
3691 contained in bibtex-entry-format).
3692 Don't call this on `string' or `preamble' entries.
3693 At end of the cleaning process, the functions in
3694 bibtex-clean-entry-hook are called with region narrowed to entry."
3695   (interactive "P")
3696   (bibtex-format-entry)
3697   (let* ((case-fold-search t)
3698          (eob (bibtex-end-of-entry))
3699          (key (progn
3700                 (bibtex-beginning-of-entry)
3701                 (if (re-search-forward
3702                      bibtex-entry-head eob t)
3703                     (buffer-substring-no-properties
3704                      (match-beginning bibtex-key-in-head)
3705                      (match-end bibtex-key-in-head))))))
3706     (if (or
3707          new-reference-key
3708          (not key))
3709         (progn
3710           (let ((autokey
3711                  (if bibtex-autokey-edit-before-use
3712                      (read-from-minibuffer
3713                       "Key to use: " (bibtex-generate-autokey) nil nil
3714                       'bibtex-key-history)
3715                    (bibtex-generate-autokey))))
3716             (bibtex-beginning-of-entry)
3717             (re-search-forward bibtex-entry-maybe-empty-head)
3718             (if (match-beginning bibtex-key-in-head)
3719                 (delete-region (match-beginning bibtex-key-in-head)
3720                                (match-end bibtex-key-in-head)))
3721             (insert autokey)
3722             (let* ((start (bibtex-beginning-of-entry))
3723                    (end (progn
3724                           (bibtex-end-of-entry)
3725                           (if (re-search-forward
3726                                bibtex-entry-maybe-empty-head nil 'move)
3727                               (goto-char (match-beginning 0)))
3728                           (point)))
3729                    (entry (buffer-substring start end)))
3730               (delete-region start end)
3731               (let ((success
3732                      (or
3733                       called-by-reformat
3734                       (not bibtex-maintain-sorted-entries)
3735                       (bibtex-find-entry-location autokey t))))
3736                 (insert entry)
3737                 (forward-char -1)
3738                 (bibtex-beginning-of-entry)
3739                 (re-search-forward bibtex-entry-head)
3740                 (if (not success)
3741                     (error
3742                      "New inserted entry yields duplicate key"))))))))
3743   (if (not called-by-reformat)
3744       (save-excursion
3745         (save-restriction
3746           (narrow-to-region
3747            (bibtex-beginning-of-entry) (bibtex-end-of-entry))
3748           (bibtex-parse-keys t nil)
3749           (run-hooks 'bibtex-clean-entry-hook)))))
3750
3751 (defun bibtex-fill-entry ()
3752   "Fill current entry.
3753 Realigns entry, so that every field starts on a separate line.  Field
3754 names appear in column `bibtex-field-indentation', field text starts in
3755 column `bibtex-text-indentation' and continuation lines start here, too.
3756 If `bibtex-align-at-equal-sign' is non-nil, align equal signs also."
3757   (interactive "*")
3758   (let ((pnt (copy-marker (point)))
3759         (end (copy-marker (bibtex-end-of-entry))))
3760     (bibtex-beginning-of-entry)
3761     (bibtex-delete-whitespace)
3762     (indent-to-column bibtex-entry-offset)
3763     (let ((bounds (bibtex-search-forward-field bibtex-field-name end)))
3764       (while bounds
3765         (let* ((begin-field (copy-marker (bibtex-start-of-field bounds)))
3766                (end-field (copy-marker (bibtex-end-of-field bounds)))
3767                (begin-name (copy-marker (bibtex-start-of-name-in-field bounds)))
3768                (end-name (copy-marker (bibtex-end-of-name-in-field bounds))))
3769           (goto-char begin-field)
3770           (forward-char)
3771           (bibtex-delete-whitespace)
3772           (open-line 1)
3773           (forward-char)
3774           (indent-to-column
3775            (+ bibtex-entry-offset bibtex-field-indentation))
3776           (re-search-forward "[ \t\n]*=" end)
3777           (replace-match "=")
3778           (forward-char -1)
3779           (if bibtex-align-at-equal-sign
3780               (indent-to-column
3781                (+ bibtex-entry-offset (- bibtex-text-indentation 2)))
3782             (insert " "))
3783           (forward-char)
3784           (bibtex-delete-whitespace)
3785           (if bibtex-align-at-equal-sign
3786               (insert " ")
3787             (indent-to-column bibtex-text-indentation))
3788           (while (re-search-forward "[ \t\n]+" end-field 'move)
3789             (replace-match " "))
3790           (bibtex-do-auto-fill)
3791           (goto-char end-field))
3792         (setq bounds (bibtex-search-forward-field bibtex-field-name end))))
3793     (if (looking-at ",")
3794         (forward-char))
3795     (bibtex-delete-whitespace)
3796     (open-line 1)
3797     (forward-char)
3798     (indent-to-column bibtex-entry-offset)
3799     (goto-char pnt)))
3800
3801 (defun bibtex-reformat (&optional additional-options called-by-convert-alien)
3802   "Reformat all BibTeX entries in buffer or region.
3803 With prefix argument, read options for reformatting from minibuffer.
3804 With \\[universal-argument] \\[universal-argument] prefix argument, reuse previous answers (if any) again.
3805 If mark is active it reformats entries in region, if not in whole buffer."
3806   (interactive "*P")
3807   (let* ((pnt (point))
3808          (use-previous-options
3809           (and (equal (prefix-numeric-value additional-options) 16)
3810                (or bibtex-reformat-previous-options
3811                    bibtex-reformat-previous-reference-keys)))
3812          (bibtex-entry-format
3813           (if additional-options
3814               (if use-previous-options
3815                   bibtex-reformat-previous-options
3816                 (setq
3817                  bibtex-reformat-previous-options
3818                  (delq
3819                   nil
3820                   (list
3821                    (if (or
3822                         called-by-convert-alien
3823                         (y-or-n-p
3824                          "Realign entries (recommended for files not created by BibTeX mode)? "))
3825                        'realign)
3826                    (if (y-or-n-p
3827                         "Remove empty optional and alternative fields? ")
3828                        'opts-or-alts)
3829                    (if (y-or-n-p
3830                         "Remove delimiters around pure numerical fields? ")
3831                        'numerical-fields)
3832                    (if (y-or-n-p (concat
3833                                   (if bibtex-comma-after-last-field
3834                                       "Insert"
3835                                     "Remove")
3836                                   " comma at end of entry? "))
3837                        'last-comma)
3838                    (if (y-or-n-p
3839                         "Replace double page dashes by single ones? ")
3840                        'page-dashes)
3841                    (if (y-or-n-p
3842                         "Force delimiters? ")
3843                        'delimiters)
3844                    (if (y-or-n-p
3845                         "Unify case of entry types and field names? ")
3846                        'unify-case)))))
3847             '(realign)))
3848          (reformat-reference-keys
3849              (if additional-options
3850                  (if use-previous-options
3851                      bibtex-reformat-previous-reference-keys
3852                    (setq
3853                     bibtex-reformat-previous-reference-keys
3854                     (y-or-n-p "Generate new reference keys automatically? ")))))
3855          bibtex-autokey-edit-before-use
3856          (bibtex-sort-ignore-string-entries t)
3857          (start-point
3858           (if (bibtex-mark-active)
3859               (region-beginning)
3860             (progn
3861               (bibtex-beginning-of-first-entry)
3862               (bibtex-skip-to-valid-entry)
3863               (point))))
3864          (end-point
3865           (if (bibtex-mark-active)
3866               (region-end)
3867             (point-max)))
3868          (valid-bibtex-entry
3869           (concat
3870            "[ \t\n]+\\(@[ \t]*\\("
3871            (mapconcat
3872             (lambda (type)
3873               (concat "\\(" (car type) "\\)"))
3874             bibtex-entry-field-alist
3875             "\\|")
3876            "\\)\\)")))
3877     (save-restriction
3878       (narrow-to-region start-point end-point)
3879       (if (memq 'realign bibtex-entry-format)
3880           (progn
3881             (goto-char (point-min))
3882             (while (re-search-forward valid-bibtex-entry nil t)
3883               (replace-match "\n\\1"))))
3884       (goto-char start-point)
3885       (bibtex-progress-message "Formatting" 1)
3886       (bibtex-map-entries
3887        (lambda (current)
3888          (bibtex-progress-message)
3889          (bibtex-clean-entry reformat-reference-keys reformat-reference-keys)
3890          (if (memq 'realign bibtex-entry-format)
3891              (progn
3892                (bibtex-end-of-entry)
3893                (bibtex-delete-whitespace)
3894                (open-line 2)))))
3895       (bibtex-progress-message 'done))
3896     (if (and
3897          reformat-reference-keys
3898          bibtex-maintain-sorted-entries
3899          (not called-by-convert-alien))
3900         (progn
3901           (bibtex-sort-buffer)
3902           (setq bibtex-reference-keys nil)
3903           (bibtex-parse-keys nil t t)))
3904     (goto-char pnt)))
3905
3906 (defun bibtex-convert-alien (&optional do-additional-reformatting)
3907   "Converts an alien BibTeX buffer to be fully usable by BibTeX mode.
3908 If a file doesn't confirm with some standards used by BibTeX mode,
3909 some of the high-level features of BibTeX mode won't be available.
3910 This function tries to convert current buffer to confirm with these standards.
3911 With prefix argument DO-ADDITIONAL-REFORMATTING
3912 non-nil, read options for reformatting entries from minibuffer."
3913   (interactive "*P")
3914   (message "Starting to validate buffer...")
3915   (sit-for 1 nil t)
3916   (goto-char (point-min))
3917   (while (re-search-forward "[ \t\n]+@" nil t)
3918     (replace-match "\n@"))
3919   (message
3920    "If errors occur, correct them and call `bibtex-convert-alien' again")
3921   (sit-for 5 nil t)
3922   (if (let ((bibtex-mark-active)
3923             bibtex-maintain-sorted-entries)
3924         (bibtex-validate))
3925       (progn
3926         (message "Starting to reformat entries...")
3927         (sit-for 2 nil t)
3928         (bibtex-reformat do-additional-reformatting t)
3929         (if bibtex-maintain-sorted-entries
3930             (progn
3931               (message "Starting to sort buffer...")
3932               (bibtex-sort-buffer)))
3933         (goto-char (point-max))
3934         (message "Buffer is now parsable. Please save it."))))
3935
3936 (defun bibtex-complete-string ()
3937   "Complete word fragment before point to longest prefix of a defined string.
3938 If point is not after the part of a word, all strings are listed.
3939 Remove surrounding delimiters if complete string could be expanded."
3940   (interactive "*")
3941   (bibtex-complete bibtex-strings t))
3942
3943 (defun bibtex-complete-key ()
3944   "Complete word fragment before point to longest prefix of a defined key.
3945 If point is not after the part of a word, all keys are listed.  This
3946 function is most useful in completing crossref entries."
3947   (interactive "*")
3948   (if (not bibtex-reference-keys)
3949       (bibtex-parse-keys nil t))
3950   (bibtex-complete bibtex-reference-keys))
3951
3952 (defun bibtex-Article ()
3953   "Insert a new BibTeX @Article entry; see also `bibtex-entry'."
3954   (interactive)
3955   (bibtex-entry "Article"))
3956
3957 (defun bibtex-Book ()
3958   "Insert a new BibTeX @Book entry; see also `bibtex-entry'."
3959   (interactive)
3960   (bibtex-entry "Book"))
3961
3962 (defun bibtex-Booklet ()
3963   "Insert a new BibTeX @Booklet entry; see also `bibtex-entry'."
3964   (interactive)
3965   (bibtex-entry "Booklet"))
3966
3967 (defun bibtex-InBook ()
3968   "Insert a new BibTeX @InBook entry; see also `bibtex-entry'."
3969   (interactive)
3970   (bibtex-entry "InBook"))
3971
3972 (defun bibtex-InCollection ()
3973   "Insert a new BibTeX @InCollection entry; see also `bibtex-entry'."
3974   (interactive)
3975   (bibtex-entry "InCollection"))
3976
3977 (defun bibtex-InProceedings ()
3978   "Insert a new BibTeX @InProceedings entry; see also `bibtex-entry'."
3979   (interactive)
3980   (bibtex-entry "InProceedings"))
3981
3982 (defun bibtex-Manual ()
3983   "Insert a new BibTeX @Manual entry; see also `bibtex-entry'."
3984   (interactive)
3985   (bibtex-entry "Manual"))
3986
3987 (defun bibtex-MastersThesis ()
3988   "Insert a new BibTeX @MastersThesis entry; see also `bibtex-entry'."
3989   (interactive)
3990   (bibtex-entry "MastersThesis"))
3991
3992 (defun bibtex-Misc ()
3993   "Insert a new BibTeX @Misc entry; see also `bibtex-entry'."
3994   (interactive)
3995   (bibtex-entry "Misc"))
3996
3997 (defun bibtex-PhdThesis ()
3998   "Insert a new BibTeX @PhdThesis entry; see also `bibtex-entry'."
3999   (interactive)
4000   (bibtex-entry "PhdThesis"))
4001
4002 (defun bibtex-Proceedings ()
4003   "Insert a new BibTeX @Proceedings entry; see also `bibtex-entry'."
4004   (interactive)
4005   (bibtex-entry "Proceedings"))
4006
4007 (defun bibtex-TechReport ()
4008   "Insert a new BibTeX @TechReport entry; see also `bibtex-entry'."
4009   (interactive)
4010   (bibtex-entry "TechReport"))
4011
4012 (defun bibtex-Unpublished ()
4013   "Insert a new BibTeX @Unpublished entry; see also `bibtex-entry'."
4014   (interactive)
4015   (bibtex-entry "Unpublished"))
4016
4017 (defun bibtex-String ()
4018   "Insert a new BibTeX @String entry."
4019   (interactive)
4020   (if (not bibtex-reference-keys)
4021       (bibtex-parse-keys nil t))
4022   (let ((key
4023          (if (and
4024               bibtex-maintain-sorted-entries
4025               (not bibtex-sort-ignore-string-entries))
4026              (completing-read
4027               "String key: " bibtex-reference-keys nil nil nil 'bibtex-key-history))))
4028     (if (and
4029          bibtex-maintain-sorted-entries
4030          (not bibtex-sort-ignore-string-entries))
4031         (bibtex-find-entry-location key)
4032       (bibtex-move-outside-of-entry))
4033     (indent-to-column bibtex-entry-offset)
4034     (insert
4035      (concat
4036       "@String"
4037       (bibtex-entry-left-delimiter)
4038       (if (and
4039            bibtex-maintain-sorted-entries
4040            (not bibtex-sort-ignore-string-entries))
4041           key)
4042       " = "
4043       (bibtex-field-left-delimiter)
4044       (bibtex-field-right-delimiter)
4045       (bibtex-entry-right-delimiter)
4046       "\n"))
4047   (forward-line -1)
4048   (forward-char
4049    (if (and
4050         bibtex-maintain-sorted-entries
4051         (not bibtex-sort-ignore-string-entries))
4052        (+ (length "@String{") (length key) (length " = {"))
4053      (length "@String{")))))
4054
4055 (defun bibtex-Preamble ()
4056   "Insert a new BibTeX @Preamble entry."
4057   (interactive)
4058   (bibtex-move-outside-of-entry)
4059   (indent-to-column bibtex-entry-offset)
4060   (insert
4061    "@Preamble"
4062    (bibtex-entry-left-delimiter)
4063    (bibtex-entry-right-delimiter)
4064    "\n")
4065   (forward-line -1)
4066   (forward-char 10))
4067
4068 \f
4069 ;; Make BibTeX a Feature
4070
4071 (provide 'bibtex)
4072
4073 ;;; bibtex.el ends here