Merge from emacs--rel--22
[bpt/emacs.git] / lisp / textmodes / bibtex.el
1 ;;; bibtex.el --- BibTeX mode for GNU Emacs
2
3 ;; Copyright (C) 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002,
4 ;; 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
5
6 ;; Author: Stefan Schoef <schoef@offis.uni-oldenburg.de>
7 ;; Bengt Martensson <bengt@mathematik.uni-Bremen.de>
8 ;; Marc Shapiro <marc.shapiro@acm.org>
9 ;; Mike Newton <newton@gumby.cs.caltech.edu>
10 ;; Aaron Larson <alarson@src.honeywell.com>
11 ;; Dirk Herrmann <D.Herrmann@tu-bs.de>
12 ;; Maintainer: Roland Winkler <roland.winkler@physik.uni-erlangen.de>
13 ;; Keywords: BibTeX, LaTeX, TeX
14
15 ;; This file is part of GNU Emacs.
16
17 ;; GNU Emacs is free software; you can redistribute it and/or modify
18 ;; it under the terms of the GNU General Public License as published by
19 ;; the Free Software Foundation; either version 3, or (at your option)
20 ;; any later version.
21
22 ;; GNU Emacs is distributed in the hope that it will be useful,
23 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 ;; GNU General Public License for more details.
26
27 ;; You should have received a copy of the GNU General Public License
28 ;; along with GNU Emacs; see the file COPYING. If not, write to the
29 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
30 ;; Boston, MA 02110-1301, USA.
31
32 ;;; Commentary:
33
34 ;; Major mode for editing and validating BibTeX files.
35
36 ;; Usage:
37 ;; See documentation for `bibtex-mode' or type "M-x describe-mode"
38 ;; when you are in BibTeX mode.
39
40 ;; Todo:
41 ;; Distribute texinfo file.
42
43 ;;; Code:
44
45 (require 'button)
46
47 \f
48 ;; User Options:
49
50 (defgroup bibtex nil
51 "BibTeX mode."
52 :group 'tex
53 :prefix "bibtex-")
54
55 (defgroup bibtex-autokey nil
56 "Generate automatically a key from the author/editor and the title field."
57 :group 'bibtex
58 :prefix "bibtex-autokey-")
59
60 (defcustom bibtex-mode-hook nil
61 "List of functions to call on entry to BibTeX mode."
62 :group 'bibtex
63 :type 'hook)
64
65 (defcustom bibtex-field-delimiters 'braces
66 "Type of field delimiters. Allowed values are `braces' or `double-quotes'."
67 :group 'bibtex
68 :type '(choice (const braces)
69 (const double-quotes)))
70
71 (defcustom bibtex-entry-delimiters 'braces
72 "Type of entry delimiters. Allowed values are `braces' or `parentheses'."
73 :group 'bibtex
74 :type '(choice (const braces)
75 (const parentheses)))
76
77 (defcustom bibtex-include-OPTcrossref '("InProceedings" "InCollection")
78 "List of BibTeX entries that get an OPTcrossref field."
79 :group 'bibtex
80 :type '(repeat string))
81
82 (defcustom bibtex-include-OPTkey t
83 "If non-nil, all newly created entries get an OPTkey field.
84 If this is a string, use it as the initial field text.
85 If this is a function, call it to generate the initial field text."
86 :group 'bibtex
87 :type '(choice (const :tag "None" nil)
88 (string :tag "Initial text")
89 (function :tag "Initialize Function")
90 (const :tag "Default" t)))
91 (put 'bibtex-include-OPTkey 'risky-local-variable t)
92
93 (defcustom bibtex-user-optional-fields
94 '(("annote" "Personal annotation (ignored)"))
95 "List of optional fields the user wants to have always present.
96 Entries should be of the same form as the OPTIONAL and
97 CROSSREF-OPTIONAL lists in `bibtex-entry-field-alist' (which see)."
98 :group 'bibtex
99 :type '(repeat (group (string :tag "Field")
100 (string :tag "Comment")
101 (option (choice :tag "Init"
102 (const nil) string function)))))
103 (put 'bibtex-user-optional-fields 'risky-local-variable t)
104
105 (defcustom bibtex-entry-format
106 '(opts-or-alts required-fields numerical-fields)
107 "Type of formatting performed by `bibtex-clean-entry'.
108 It may be t, nil, or a list of symbols out of the following:
109 opts-or-alts Delete empty optional and alternative fields and
110 remove OPT and ALT prefixes from used fields.
111 required-fields Signal an error if a required field is missing.
112 numerical-fields Delete delimiters around numeral fields.
113 page-dashes Change double dashes in page field to single dash
114 (for scribe compatibility).
115 whitespace Delete whitespace at the beginning and end of fields.
116 inherit-booktitle If entry contains a crossref field and the booktitle
117 field is empty, set the booktitle field to the content
118 of the title field of the crossreferenced entry.
119 realign Realign entries, so that field texts and perhaps equal
120 signs (depending on the value of
121 `bibtex-align-at-equal-sign') begin in the same column.
122 Also fill fields.
123 last-comma Add or delete comma on end of last field in entry,
124 according to value of `bibtex-comma-after-last-field'.
125 delimiters Change delimiters according to variables
126 `bibtex-field-delimiters' and `bibtex-entry-delimiters'.
127 unify-case Change case of entry types and field names.
128 braces Enclose parts of field entries by braces according to
129 `bibtex-field-braces-alist'.
130 strings Replace parts of field entries by string constants
131 according to `bibtex-field-strings-alist'.
132
133 The value t means do all of the above formatting actions.
134 The value nil means do no formatting at all."
135 :group 'bibtex
136 :type '(choice (const :tag "None" nil)
137 (const :tag "All" t)
138 (set :menu-tag "Some"
139 (const opts-or-alts)
140 (const required-fields)
141 (const numerical-fields)
142 (const page-dashes)
143 (const whitespace)
144 (const inherit-booktitle)
145 (const realign)
146 (const last-comma)
147 (const delimiters)
148 (const unify-case)
149 (const braces)
150 (const strings))))
151
152 (defcustom bibtex-field-braces-alist nil
153 "Alist of field regexps that \\[bibtex-clean-entry] encloses by braces.
154 Each element has the form (FIELDS REGEXP), where FIELDS is a list
155 of BibTeX field names and REGEXP is a regexp.
156 Whitespace in REGEXP will be replaced by \"[ \\t\\n]+\"."
157 :group 'bibtex
158 :type '(repeat (list (repeat (string :tag "field name"))
159 (choice (regexp :tag "regexp")
160 (sexp :tag "sexp")))))
161
162 (defcustom bibtex-field-strings-alist nil
163 "Alist of regexps that \\[bibtex-clean-entry] replaces by string constants.
164 Each element has the form (FIELDS REGEXP TO-STR), where FIELDS is a list
165 of BibTeX field names. In FIELDS search for REGEXP, which are replaced
166 by the BibTeX string constant TO-STR.
167 Whitespace in REGEXP will be replaced by \"[ \\t\\n]+\"."
168 :group 'bibtex
169 :type '(repeat (list (repeat (string :tag "field name"))
170 (regexp :tag "From regexp")
171 (regexp :tag "To string constant"))))
172
173 (defcustom bibtex-clean-entry-hook nil
174 "List of functions to call when entry has been cleaned.
175 Functions are called with point inside the cleaned entry, and the buffer
176 narrowed to just the entry."
177 :group 'bibtex
178 :type 'hook)
179
180 (defcustom bibtex-maintain-sorted-entries nil
181 "If non-nil, BibTeX mode maintains all entries in sorted order.
182 Allowed non-nil values are:
183 plain or t All entries are sorted alphabetically.
184 crossref All entries are sorted alphabetically unless an entry has a
185 crossref field. These crossrefed entries are placed in
186 alphabetical order immediately preceding the main entry.
187 entry-class The entries are divided into classes according to their
188 entry type, see `bibtex-sort-entry-class'. Within each class
189 the entries are sorted alphabetically.
190 See also `bibtex-sort-ignore-string-entries'."
191 :group 'bibtex
192 :type '(choice (const nil)
193 (const plain)
194 (const crossref)
195 (const entry-class)
196 (const t)))
197 (put 'bibtex-maintain-sorted-entries 'safe-local-variable
198 '(lambda (a) (memq a '(nil t plain crossref entry-class))))
199
200 (defcustom bibtex-sort-entry-class
201 '(("String")
202 (catch-all)
203 ("Book" "Proceedings"))
204 "List of classes of BibTeX entry types, used for sorting entries.
205 If value of `bibtex-maintain-sorted-entries' is `entry-class'
206 entries are ordered according to the classes they belong to. Each
207 class contains a list of entry types. An entry `catch-all' applies
208 to all entries not explicitly mentioned."
209 :group 'BibTeX
210 :type '(repeat (choice :tag "Class"
211 (const :tag "catch-all" (catch-all))
212 (repeat :tag "Entry type" string))))
213 (put 'bibtex-sort-entry-class 'safe-local-variable
214 (lambda (x) (let ((OK t))
215 (while (consp x)
216 (let ((y (pop x)))
217 (while (consp y)
218 (let ((z (pop y)))
219 (unless (or (stringp z) (eq z 'catch-all))
220 (setq OK nil))))
221 (unless (null y) (setq OK nil))))
222 (unless (null x) (setq OK nil))
223 OK)))
224
225 (defcustom bibtex-sort-ignore-string-entries t
226 "If non-nil, BibTeX @String entries are not sort-significant.
227 That means they are ignored when determining ordering of the buffer
228 \(e.g., sorting, locating alphabetical position for new entries, etc.)."
229 :group 'bibtex
230 :type 'boolean)
231
232 (defcustom bibtex-field-kill-ring-max 20
233 "Max length of `bibtex-field-kill-ring' before discarding oldest elements."
234 :group 'bibtex
235 :type 'integer)
236
237 (defcustom bibtex-entry-kill-ring-max 20
238 "Max length of `bibtex-entry-kill-ring' before discarding oldest elements."
239 :group 'bibtex
240 :type 'integer)
241
242 (defcustom bibtex-parse-keys-timeout 60
243 "Time interval in seconds for parsing BibTeX buffers during idle time.
244 Parsing initializes `bibtex-reference-keys' and `bibtex-strings'."
245 :group 'bibtex
246 :type 'integer)
247
248 (defcustom bibtex-parse-keys-fast t
249 "If non-nil, use fast but simplified algorithm for parsing BibTeX keys.
250 If parsing fails, try to set this variable to nil."
251 :group 'bibtex
252 :type 'boolean)
253
254 (defcustom bibtex-entry-field-alist
255 '(("Article"
256 ((("author" "Author1 [and Author2 ...] [and others]")
257 ("title" "Title of the article (BibTeX converts it to lowercase)")
258 ("journal" "Name of the journal (use string, remove braces)")
259 ("year" "Year of publication"))
260 (("volume" "Volume of the journal")
261 ("number" "Number of the journal (only allowed if entry contains volume)")
262 ("pages" "Pages in the journal")
263 ("month" "Month of the publication as a string (remove braces)")
264 ("note" "Remarks to be put at the end of the \\bibitem")))
265 ((("author" "Author1 [and Author2 ...] [and others]")
266 ("title" "Title of the article (BibTeX converts it to lowercase)"))
267 (("pages" "Pages in the journal")
268 ("journal" "Name of the journal (use string, remove braces)")
269 ("year" "Year of publication")
270 ("volume" "Volume of the journal")
271 ("number" "Number of the journal")
272 ("month" "Month of the publication as a string (remove braces)")
273 ("note" "Remarks to be put at the end of the \\bibitem"))))
274 ("Book"
275 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
276 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
277 ("title" "Title of the book")
278 ("publisher" "Publishing company")
279 ("year" "Year of publication"))
280 (("volume" "Volume of the book in the series")
281 ("number" "Number of the book in a small series (overwritten by volume)")
282 ("series" "Series in which the book appeared")
283 ("address" "Address of the publisher")
284 ("edition" "Edition of the book as a capitalized English word")
285 ("month" "Month of the publication as a string (remove braces)")
286 ("note" "Remarks to be put at the end of the \\bibitem")))
287 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
288 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
289 ("title" "Title of the book"))
290 (("publisher" "Publishing company")
291 ("year" "Year of publication")
292 ("volume" "Volume of the book in the series")
293 ("number" "Number of the book in a small series (overwritten by volume)")
294 ("series" "Series in which the book appeared")
295 ("address" "Address of the publisher")
296 ("edition" "Edition of the book as a capitalized English word")
297 ("month" "Month of the publication as a string (remove braces)")
298 ("note" "Remarks to be put at the end of the \\bibitem"))))
299 ("Booklet"
300 ((("title" "Title of the booklet (BibTeX converts it to lowercase)"))
301 (("author" "Author1 [and Author2 ...] [and others]")
302 ("howpublished" "The way in which the booklet was published")
303 ("address" "Address of the publisher")
304 ("month" "Month of the publication as a string (remove braces)")
305 ("year" "Year of publication")
306 ("note" "Remarks to be put at the end of the \\bibitem"))))
307 ("InBook"
308 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
309 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
310 ("title" "Title of the book")
311 ("chapter" "Chapter in the book")
312 ("publisher" "Publishing company")
313 ("year" "Year of publication"))
314 (("volume" "Volume of the book in the series")
315 ("number" "Number of the book in a small series (overwritten by volume)")
316 ("series" "Series in which the book appeared")
317 ("type" "Word to use instead of \"chapter\"")
318 ("address" "Address of the publisher")
319 ("edition" "Edition of the book as a capitalized English word")
320 ("month" "Month of the publication as a string (remove braces)")
321 ("pages" "Pages in the book")
322 ("note" "Remarks to be put at the end of the \\bibitem")))
323 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
324 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
325 ("title" "Title of the book")
326 ("chapter" "Chapter in the book"))
327 (("pages" "Pages in the book")
328 ("publisher" "Publishing company")
329 ("year" "Year of publication")
330 ("volume" "Volume of the book in the series")
331 ("number" "Number of the book in a small series (overwritten by volume)")
332 ("series" "Series in which the book appeared")
333 ("type" "Word to use instead of \"chapter\"")
334 ("address" "Address of the publisher")
335 ("edition" "Edition of the book as a capitalized English word")
336 ("month" "Month of the publication as a string (remove braces)")
337 ("note" "Remarks to be put at the end of the \\bibitem"))))
338 ("InCollection"
339 ((("author" "Author1 [and Author2 ...] [and others]")
340 ("title" "Title of the article in book (BibTeX converts it to lowercase)")
341 ("booktitle" "Name of the book")
342 ("publisher" "Publishing company")
343 ("year" "Year of publication"))
344 (("editor" "Editor1 [and Editor2 ...] [and others]")
345 ("volume" "Volume of the book in the series")
346 ("number" "Number of the book in a small series (overwritten by volume)")
347 ("series" "Series in which the book appeared")
348 ("type" "Word to use instead of \"chapter\"")
349 ("chapter" "Chapter in the book")
350 ("pages" "Pages in the book")
351 ("address" "Address of the publisher")
352 ("edition" "Edition of the book as a capitalized English word")
353 ("month" "Month of the publication as a string (remove braces)")
354 ("note" "Remarks to be put at the end of the \\bibitem")))
355 ((("author" "Author1 [and Author2 ...] [and others]")
356 ("title" "Title of the article in book (BibTeX converts it to lowercase)")
357 ("booktitle" "Name of the book"))
358 (("pages" "Pages in the book")
359 ("publisher" "Publishing company")
360 ("year" "Year of publication")
361 ("editor" "Editor1 [and Editor2 ...] [and others]")
362 ("volume" "Volume of the book in the series")
363 ("number" "Number of the book in a small series (overwritten by volume)")
364 ("series" "Series in which the book appeared")
365 ("type" "Word to use instead of \"chapter\"")
366 ("chapter" "Chapter in the book")
367 ("address" "Address of the publisher")
368 ("edition" "Edition of the book as a capitalized English word")
369 ("month" "Month of the publication as a string (remove braces)")
370 ("note" "Remarks to be put at the end of the \\bibitem"))))
371 ("InProceedings"
372 ((("author" "Author1 [and Author2 ...] [and others]")
373 ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)")
374 ("booktitle" "Name of the conference proceedings")
375 ("year" "Year of publication"))
376 (("editor" "Editor1 [and Editor2 ...] [and others]")
377 ("volume" "Volume of the conference proceedings in the series")
378 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
379 ("series" "Series in which the conference proceedings appeared")
380 ("pages" "Pages in the conference proceedings")
381 ("address" "Location of the Proceedings")
382 ("month" "Month of the publication as a string (remove braces)")
383 ("organization" "Sponsoring organization of the conference")
384 ("publisher" "Publishing company, its location")
385 ("note" "Remarks to be put at the end of the \\bibitem")))
386 ((("author" "Author1 [and Author2 ...] [and others]")
387 ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)"))
388 (("booktitle" "Name of the conference proceedings")
389 ("pages" "Pages in the conference proceedings")
390 ("year" "Year of publication")
391 ("editor" "Editor1 [and Editor2 ...] [and others]")
392 ("volume" "Volume of the conference proceedings in the series")
393 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
394 ("series" "Series in which the conference proceedings appeared")
395 ("address" "Location of the Proceedings")
396 ("month" "Month of the publication as a string (remove braces)")
397 ("organization" "Sponsoring organization of the conference")
398 ("publisher" "Publishing company, its location")
399 ("note" "Remarks to be put at the end of the \\bibitem"))))
400 ("Manual"
401 ((("title" "Title of the manual"))
402 (("author" "Author1 [and Author2 ...] [and others]")
403 ("organization" "Publishing organization of the manual")
404 ("address" "Address of the organization")
405 ("edition" "Edition of the manual as a capitalized English word")
406 ("month" "Month of the publication as a string (remove braces)")
407 ("year" "Year of publication")
408 ("note" "Remarks to be put at the end of the \\bibitem"))))
409 ("MastersThesis"
410 ((("author" "Author1 [and Author2 ...] [and others]")
411 ("title" "Title of the master\'s thesis (BibTeX converts it to lowercase)")
412 ("school" "School where the master\'s thesis was written")
413 ("year" "Year of publication"))
414 (("type" "Type of the master\'s thesis (if other than \"Master\'s thesis\")")
415 ("address" "Address of the school (if not part of field \"school\") or country")
416 ("month" "Month of the publication as a string (remove braces)")
417 ("note" "Remarks to be put at the end of the \\bibitem"))))
418 ("Misc"
419 (()
420 (("author" "Author1 [and Author2 ...] [and others]")
421 ("title" "Title of the work (BibTeX converts it to lowercase)")
422 ("howpublished" "The way in which the work was published")
423 ("month" "Month of the publication as a string (remove braces)")
424 ("year" "Year of publication")
425 ("note" "Remarks to be put at the end of the \\bibitem"))))
426 ("PhdThesis"
427 ((("author" "Author1 [and Author2 ...] [and others]")
428 ("title" "Title of the PhD. thesis")
429 ("school" "School where the PhD. thesis was written")
430 ("year" "Year of publication"))
431 (("type" "Type of the PhD. thesis")
432 ("address" "Address of the school (if not part of field \"school\") or country")
433 ("month" "Month of the publication as a string (remove braces)")
434 ("note" "Remarks to be put at the end of the \\bibitem"))))
435 ("Proceedings"
436 ((("title" "Title of the conference proceedings")
437 ("year" "Year of publication"))
438 (("booktitle" "Title of the proceedings for cross references")
439 ("editor" "Editor1 [and Editor2 ...] [and others]")
440 ("volume" "Volume of the conference proceedings in the series")
441 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
442 ("series" "Series in which the conference proceedings appeared")
443 ("address" "Location of the Proceedings")
444 ("month" "Month of the publication as a string (remove braces)")
445 ("organization" "Sponsoring organization of the conference")
446 ("publisher" "Publishing company, its location")
447 ("note" "Remarks to be put at the end of the \\bibitem"))))
448 ("TechReport"
449 ((("author" "Author1 [and Author2 ...] [and others]")
450 ("title" "Title of the technical report (BibTeX converts it to lowercase)")
451 ("institution" "Sponsoring institution of the report")
452 ("year" "Year of publication"))
453 (("type" "Type of the report (if other than \"technical report\")")
454 ("number" "Number of the technical report")
455 ("address" "Address of the institution (if not part of field \"institution\") or country")
456 ("month" "Month of the publication as a string (remove braces)")
457 ("note" "Remarks to be put at the end of the \\bibitem"))))
458 ("Unpublished"
459 ((("author" "Author1 [and Author2 ...] [and others]")
460 ("title" "Title of the unpublished work (BibTeX converts it to lowercase)")
461 ("note" "Remarks to be put at the end of the \\bibitem"))
462 (("month" "Month of the publication as a string (remove braces)")
463 ("year" "Year of publication")))))
464
465 "List of BibTeX entry types and their associated fields.
466 List elements are triples
467 \(ENTRY-TYPE (REQUIRED OPTIONAL) (CROSSREF-REQUIRED CROSSREF-OPTIONAL)).
468 ENTRY-TYPE is the type of a BibTeX entry. The remaining pairs contain
469 the required and optional fields of the BibTeX entry.
470 The second pair is used if a crossref field is present
471 and the first pair is used if a crossref field is absent.
472 If the second pair is nil, the first pair is always used.
473 REQUIRED, OPTIONAL, CROSSREF-REQUIRED and CROSSREF-OPTIONAL are lists.
474 Each element of these lists is a list of the form
475 \(FIELD-NAME COMMENT-STRING INIT ALTERNATIVE-FLAG).
476 COMMENT-STRING, INIT, and ALTERNATIVE-FLAG are optional.
477 FIELD-NAME is the name of the field, COMMENT-STRING is the comment that
478 appears in the echo area, INIT is either the initial content of the
479 field or a function, which is called to determine the initial content
480 of the field, and ALTERNATIVE-FLAG (either nil or t) marks if the
481 field is an alternative. ALTERNATIVE-FLAG may be t only in the
482 REQUIRED or CROSSREF-REQUIRED lists."
483 :group 'bibtex
484 :type '(repeat (group (string :tag "Entry type")
485 (group (repeat :tag "Required fields"
486 (group (string :tag "Field")
487 (string :tag "Comment")
488 (option (choice :tag "Init" :value nil
489 (const nil) string function))
490 (option (choice :tag "Alternative"
491 (const :tag "No" nil)
492 (const :tag "Yes" t)))))
493 (repeat :tag "Optional fields"
494 (group (string :tag "Field")
495 (string :tag "Comment")
496 (option (choice :tag "Init" :value nil
497 (const nil) string function)))))
498 (option :extra-offset -4
499 (group (repeat :tag "Crossref: required fields"
500 (group (string :tag "Field")
501 (string :tag "Comment")
502 (option (choice :tag "Init" :value nil
503 (const nil) string function))
504 (option (choice :tag "Alternative"
505 (const :tag "No" nil)
506 (const :tag "Yes" t)))))
507 (repeat :tag "Crossref: optional fields"
508 (group (string :tag "Field")
509 (string :tag "Comment")
510 (option (choice :tag "Init" :value nil
511 (const nil) string function)))))))))
512 (put 'bibtex-entry-field-alist 'risky-local-variable t)
513
514 (defcustom bibtex-comment-start "@Comment"
515 "String starting a BibTeX comment."
516 :group 'bibtex
517 :type 'string)
518
519 (defcustom bibtex-add-entry-hook nil
520 "List of functions to call when BibTeX entry has been inserted."
521 :group 'bibtex
522 :type 'hook)
523
524 (defcustom bibtex-predefined-month-strings
525 '(("jan" . "January")
526 ("feb" . "February")
527 ("mar" . "March")
528 ("apr" . "April")
529 ("may" . "May")
530 ("jun" . "June")
531 ("jul" . "July")
532 ("aug" . "August")
533 ("sep" . "September")
534 ("oct" . "October")
535 ("nov" . "November")
536 ("dec" . "December"))
537 "Alist of month string definitions used in the BibTeX style files.
538 Each element is a pair of strings (ABBREVIATION . EXPANSION)."
539 :group 'bibtex
540 :type '(repeat (cons (string :tag "Month abbreviation")
541 (string :tag "Month expansion"))))
542
543 (defcustom bibtex-predefined-strings
544 (append
545 bibtex-predefined-month-strings
546 '(("acmcs" . "ACM Computing Surveys")
547 ("acta" . "Acta Informatica")
548 ("cacm" . "Communications of the ACM")
549 ("ibmjrd" . "IBM Journal of Research and Development")
550 ("ibmsj" . "IBM Systems Journal")
551 ("ieeese" . "IEEE Transactions on Software Engineering")
552 ("ieeetc" . "IEEE Transactions on Computers")
553 ("ieeetcad" . "IEEE Transactions on Computer-Aided Design of Integrated Circuits")
554 ("ipl" . "Information Processing Letters")
555 ("jacm" . "Journal of the ACM")
556 ("jcss" . "Journal of Computer and System Sciences")
557 ("scp" . "Science of Computer Programming")
558 ("sicomp" . "SIAM Journal on Computing")
559 ("tcs" . "Theoretical Computer Science")
560 ("tocs" . "ACM Transactions on Computer Systems")
561 ("tods" . "ACM Transactions on Database Systems")
562 ("tog" . "ACM Transactions on Graphics")
563 ("toms" . "ACM Transactions on Mathematical Software")
564 ("toois" . "ACM Transactions on Office Information Systems")
565 ("toplas" . "ACM Transactions on Programming Languages and Systems")))
566 "Alist of string definitions used in the BibTeX style files.
567 Each element is a pair of strings (ABBREVIATION . EXPANSION)."
568 :group 'bibtex
569 :type '(repeat (cons (string :tag "String")
570 (string :tag "String expansion"))))
571
572 (defcustom bibtex-string-files nil
573 "List of BibTeX files containing string definitions.
574 List elements can be absolute file names or file names relative
575 to the directories specified in `bibtex-string-file-path'."
576 :group 'bibtex
577 :type '(repeat file))
578
579 (defvar bibtex-string-file-path (getenv "BIBINPUTS")
580 "*Colon separated list of paths to search for `bibtex-string-files'.")
581
582 (defcustom bibtex-files nil
583 "List of BibTeX files that are searched for entry keys.
584 List elements can be absolute file names or file names relative to the
585 directories specified in `bibtex-file-path'. If an element is a directory,
586 check all BibTeX files in this directory. If an element is the symbol
587 `bibtex-file-path', check all BibTeX files in `bibtex-file-path'."
588 :group 'bibtex
589 :type '(repeat (choice (const :tag "bibtex-file-path" bibtex-file-path)
590 directory file)))
591
592 (defvar bibtex-file-path (getenv "BIBINPUTS")
593 "*Colon separated list of paths to search for `bibtex-files'.")
594
595 (defcustom bibtex-help-message t
596 "If non-nil print help messages in the echo area on entering a new field."
597 :group 'bibtex
598 :type 'boolean)
599
600 (defcustom bibtex-autokey-prefix-string ""
601 "String prefix for automatically generated reference keys.
602 See `bibtex-generate-autokey' for details."
603 :group 'bibtex-autokey
604 :type 'string)
605
606 (defcustom bibtex-autokey-names 1
607 "Number of names to use for the automatically generated reference key.
608 Possibly more names are used according to `bibtex-autokey-names-stretch'.
609 If this variable is nil, all names are used.
610 See `bibtex-generate-autokey' for details."
611 :group 'bibtex-autokey
612 :type '(choice (const :tag "All" infty)
613 integer))
614
615 (defcustom bibtex-autokey-names-stretch 0
616 "Number of names that can additionally be used for reference keys.
617 These names are used only, if all names are used then.
618 See `bibtex-generate-autokey' for details."
619 :group 'bibtex-autokey
620 :type 'integer)
621
622 (defcustom bibtex-autokey-additional-names ""
623 "String to append to the generated key if not all names could be used.
624 See `bibtex-generate-autokey' for details."
625 :group 'bibtex-autokey
626 :type 'string)
627
628 (defcustom bibtex-autokey-expand-strings nil
629 "If non-nil, expand strings when extracting the content of a BibTeX field.
630 See `bibtex-generate-autokey' for details."
631 :group 'bibtex-autokey
632 :type 'boolean)
633
634 (defvar bibtex-autokey-transcriptions
635 '(;; language specific characters
636 ("\\\\aa" . "a") ; \aa -> a
637 ("\\\\AA" . "A") ; \AA -> A
638 ("\\\"a\\|\\\\\\\"a\\|\\\\ae" . "ae") ; "a,\"a,\ae -> ae
639 ("\\\"A\\|\\\\\\\"A\\|\\\\AE" . "Ae") ; "A,\"A,\AE -> Ae
640 ("\\\\i" . "i") ; \i -> i
641 ("\\\\j" . "j") ; \j -> j
642 ("\\\\l" . "l") ; \l -> l
643 ("\\\\L" . "L") ; \L -> L
644 ("\\\"o\\|\\\\\\\"o\\|\\\\o\\|\\\\oe" . "oe") ; "o,\"o,\o,\oe -> oe
645 ("\\\"O\\|\\\\\\\"O\\|\\\\O\\|\\\\OE" . "Oe") ; "O,\"O,\O,\OE -> Oe
646 ("\\\"s\\|\\\\\\\"s\\|\\\\3" . "ss") ; "s,\"s,\3 -> ss
647 ("\\\"u\\|\\\\\\\"u" . "ue") ; "u,\"u -> ue
648 ("\\\"U\\|\\\\\\\"U" . "Ue") ; "U,\"U -> Ue
649 ;; accents
650 ("\\\\`\\|\\\\'\\|\\\\\\^\\|\\\\~\\|\\\\=\\|\\\\\\.\\|\\\\u\\|\\\\v\\|\\\\H\\|\\\\t\\|\\\\c\\|\\\\d\\|\\\\b" . "")
651 ;; braces, quotes, concatenation.
652 ("[`'\"{}#]" . "")
653 ;; spaces
654 ("\\\\?[ \t\n]+\\|~" . " "))
655 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
656 Used by the default values of `bibtex-autokey-name-change-strings' and
657 `bibtex-autokey-titleword-change-strings'. Defaults to translating some
658 language specific characters to their ASCII transcriptions, and
659 removing any character accents.")
660
661 (defcustom bibtex-autokey-name-change-strings
662 bibtex-autokey-transcriptions
663 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
664 Any part of a name matching OLD-REGEXP is replaced by NEW-STRING.
665 Case is significant in OLD-REGEXP. All regexps are tried in the
666 order in which they appear in the list.
667 See `bibtex-generate-autokey' for details."
668 :group 'bibtex-autokey
669 :type '(repeat (cons (regexp :tag "Old")
670 (string :tag "New"))))
671
672 (defcustom bibtex-autokey-name-case-convert-function 'downcase
673 "Function called for each name to perform case conversion.
674 See `bibtex-generate-autokey' for details."
675 :group 'bibtex-autokey
676 :type '(choice (const :tag "Preserve case" identity)
677 (const :tag "Downcase" downcase)
678 (const :tag "Capitalize" capitalize)
679 (const :tag "Upcase" upcase)
680 (function :tag "Conversion function")))
681 (put 'bibtex-autokey-name-case-convert-function 'safe-local-variable
682 (lambda (x) (memq x '(upcase downcase capitalize identity))))
683 (defvaralias 'bibtex-autokey-name-case-convert
684 'bibtex-autokey-name-case-convert-function)
685
686 (defcustom bibtex-autokey-name-length 'infty
687 "Number of characters from name to incorporate into key.
688 If this is set to anything but a number, all characters are used.
689 See `bibtex-generate-autokey' for details."
690 :group 'bibtex-autokey
691 :type '(choice (const :tag "All" infty)
692 integer))
693
694 (defcustom bibtex-autokey-name-separator ""
695 "String that comes between any two names in the key.
696 See `bibtex-generate-autokey' for details."
697 :group 'bibtex-autokey
698 :type 'string)
699
700 (defcustom bibtex-autokey-year-length 2
701 "Number of rightmost digits from the year field to incorporate into key.
702 See `bibtex-generate-autokey' for details."
703 :group 'bibtex-autokey
704 :type 'integer)
705
706 (defcustom bibtex-autokey-use-crossref t
707 "If non-nil use fields from crossreferenced entry if necessary.
708 If this variable is non-nil and some field has no entry, but a
709 valid crossref entry, the field from the crossreferenced entry is used.
710 See `bibtex-generate-autokey' for details."
711 :group 'bibtex-autokey
712 :type 'boolean)
713
714 (defcustom bibtex-autokey-titlewords 5
715 "Number of title words to use for the automatically generated reference key.
716 If this is set to anything but a number, all title words are used.
717 Possibly more words from the title are used according to
718 `bibtex-autokey-titlewords-stretch'.
719 See `bibtex-generate-autokey' for details."
720 :group 'bibtex-autokey
721 :type '(choice (const :tag "All" infty)
722 integer))
723
724 (defcustom bibtex-autokey-title-terminators "[.!?:;]\\|--"
725 "Regexp defining the termination of the main part of the title.
726 Case of the regexps is ignored. See `bibtex-generate-autokey' for details."
727 :group 'bibtex-autokey
728 :type 'regexp)
729
730 (defcustom bibtex-autokey-titlewords-stretch 2
731 "Number of words that can additionally be used from the title.
732 These words are used only, if a sentence from the title can be ended then.
733 See `bibtex-generate-autokey' for details."
734 :group 'bibtex-autokey
735 :type 'integer)
736
737 (defcustom bibtex-autokey-titleword-ignore
738 '("A" "An" "On" "The" "Eine?" "Der" "Die" "Das"
739 "[^[:upper:]].*" ".*[^[:upper:]0-9].*")
740 "Determines words from the title that are not to be used in the key.
741 Each item of the list is a regexp. If a word of the title matches a
742 regexp from that list, it is not included in the title part of the key.
743 See `bibtex-generate-autokey' for details."
744 :group 'bibtex-autokey
745 :type '(repeat regexp))
746
747 (defcustom bibtex-autokey-titleword-case-convert-function 'downcase
748 "Function called for each titleword to perform case conversion.
749 See `bibtex-generate-autokey' for details."
750 :group 'bibtex-autokey
751 :type '(choice (const :tag "Preserve case" identity)
752 (const :tag "Downcase" downcase)
753 (const :tag "Capitalize" capitalize)
754 (const :tag "Upcase" upcase)
755 (function :tag "Conversion function")))
756 (defvaralias 'bibtex-autokey-titleword-case-convert
757 'bibtex-autokey-titleword-case-convert-function)
758
759 (defcustom bibtex-autokey-titleword-abbrevs nil
760 "Determines exceptions to the usual abbreviation mechanism.
761 An alist of (OLD-REGEXP . NEW-STRING) pairs. Case is ignored
762 in matching against OLD-REGEXP, and the first matching pair is used.
763 See `bibtex-generate-autokey' for details."
764 :group 'bibtex-autokey
765 :type '(repeat (cons (regexp :tag "Old")
766 (string :tag "New"))))
767
768 (defcustom bibtex-autokey-titleword-change-strings
769 bibtex-autokey-transcriptions
770 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
771 Any part of title word matching a OLD-REGEXP is replaced by NEW-STRING.
772 Case is significant in OLD-REGEXP. All regexps are tried in the
773 order in which they appear in the list.
774 See `bibtex-generate-autokey' for details."
775 :group 'bibtex-autokey
776 :type '(repeat (cons (regexp :tag "Old")
777 (string :tag "New"))))
778
779 (defcustom bibtex-autokey-titleword-length 5
780 "Number of characters from title words to incorporate into key.
781 If this is set to anything but a number, all characters are used.
782 See `bibtex-generate-autokey' for details."
783 :group 'bibtex-autokey
784 :type '(choice (const :tag "All" infty)
785 integer))
786
787 (defcustom bibtex-autokey-titleword-separator "_"
788 "String to be put between the title words.
789 See `bibtex-generate-autokey' for details."
790 :group 'bibtex-autokey
791 :type 'string)
792
793 (defcustom bibtex-autokey-name-year-separator ""
794 "String to be put between name part and year part of key.
795 See `bibtex-generate-autokey' for details."
796 :group 'bibtex-autokey
797 :type 'string)
798
799 (defcustom bibtex-autokey-year-title-separator ":_"
800 "String to be put between name part and year part of key.
801 See `bibtex-generate-autokey' for details."
802 :group 'bibtex-autokey
803 :type 'string)
804
805 (defcustom bibtex-autokey-edit-before-use t
806 "If non-nil, user is allowed to edit the generated key before it is used."
807 :group 'bibtex-autokey
808 :type 'boolean)
809
810 (defcustom bibtex-autokey-before-presentation-function nil
811 "If non-nil, function to call before generated key is presented.
812 The function must take one argument (the automatically generated key),
813 and must return a string (the key to use)."
814 :group 'bibtex-autokey
815 :type '(choice (const nil) function))
816
817 (defcustom bibtex-entry-offset 0
818 "Offset for BibTeX entries.
819 Added to the value of all other variables which determine columns."
820 :group 'bibtex
821 :type 'integer)
822
823 (defcustom bibtex-field-indentation 2
824 "Starting column for the name part in BibTeX fields."
825 :group 'bibtex
826 :type 'integer)
827
828 (defcustom bibtex-text-indentation
829 (+ bibtex-field-indentation
830 (length "organization = "))
831 "Starting column for the text part in BibTeX fields.
832 Should be equal to the space needed for the longest name part."
833 :group 'bibtex
834 :type 'integer)
835
836 (defcustom bibtex-contline-indentation
837 (+ bibtex-text-indentation 1)
838 "Starting column for continuation lines of BibTeX fields."
839 :group 'bibtex
840 :type 'integer)
841
842 (defcustom bibtex-align-at-equal-sign nil
843 "If non-nil, align fields at equal sign instead of field text.
844 If non-nil, the column for the equal sign is the value of
845 `bibtex-text-indentation', minus 2."
846 :group 'bibtex
847 :type 'boolean)
848
849 (defcustom bibtex-comma-after-last-field nil
850 "If non-nil, a comma is put at end of last field in the entry template."
851 :group 'bibtex
852 :type 'boolean)
853
854 (defcustom bibtex-autoadd-commas t
855 "If non-nil automatically add missing commas at end of BibTeX fields."
856 :group 'bibtex
857 :type 'boolean)
858
859 (defcustom bibtex-autofill-types '("Proceedings")
860 "Automatically fill fields if possible for those BibTeX entry types."
861 :group 'bibtex
862 :type '(repeat string))
863
864 (defcustom bibtex-summary-function 'bibtex-summary
865 "Function to call for generating a summary of current BibTeX entry.
866 It takes no arguments. Point must be at beginning of entry.
867 Used by `bibtex-complete-crossref-cleanup' and `bibtex-copy-summary-as-kill'."
868 :group 'bibtex
869 :type '(choice (const :tag "Default" bibtex-summary)
870 (function :tag "Personalized function")))
871
872 (defcustom bibtex-generate-url-list
873 '((("url" . ".*:.*")))
874 "List of schemes for generating the URL of a BibTeX entry.
875 These schemes are used by `bibtex-url'.
876
877 Each scheme should have one of these forms:
878
879 ((FIELD . REGEXP))
880 ((FIELD . REGEXP) STEP...)
881 ((FIELD . REGEXP) STRING STEP...)
882
883 FIELD is a field name as returned by `bibtex-parse-entry'.
884 REGEXP is matched against the text of FIELD. If the match succeeds,
885 then this scheme is used. If no STRING and STEPs are specified
886 the matched text is used as the URL, otherwise the URL is built
887 by evaluating STEPs. If no STRING is specified the STEPs must result
888 in strings which are concatenated. Otherwise the resulting objects
889 are passed through `format' using STRING as format control string.
890
891 A STEP is a list (FIELD REGEXP REPLACE). The text of FIELD
892 is matched against REGEXP, and is replaced with REPLACE.
893 REPLACE can be a string, or a number (which selects the corresponding
894 submatch), or a function called with the field's text as argument
895 and with the `match-data' properly set.
896
897 Case is always ignored. Always remove the field delimiters.
898 If `bibtex-expand-strings' is non-nil, BibTeX strings are expanded
899 for generating the URL.
900
901 The following is a complex example, see http://link.aps.org/linkfaq.html.
902
903 (((\"journal\" . \"\\\\=<\\(PR[ABCDEL]?\\|RMP\\)\\\\=>\")
904 \"http://link.aps.org/abstract/%s/v%s/p%s\"
905 (\"journal\" \".*\" downcase)
906 (\"volume\" \".*\" 0)
907 (\"pages\" \"\\`[A-Z]?[0-9]+\" 0)))"
908 :group 'bibtex
909 :type '(repeat
910 (cons :tag "Scheme"
911 (cons :tag "Matcher" :extra-offset 4
912 (string :tag "BibTeX field")
913 (regexp :tag "Regexp"))
914 (choice
915 (const :tag "Take match as is" nil)
916 (cons :tag "Formatted"
917 (string :tag "Format control string")
918 (repeat :tag "Steps to generate URL"
919 (list (string :tag "BibTeX field")
920 (regexp :tag "Regexp")
921 (choice (string :tag "Replacement")
922 (integer :tag "Sub-match")
923 (function :tag "Filter")))))
924 (repeat :tag "Concatenated"
925 (list (string :tag "BibTeX field")
926 (regexp :tag "Regexp")
927 (choice (string :tag "Replacement")
928 (integer :tag "Sub-match")
929 (function :tag "Filter"))))))))
930 (put 'bibtex-generate-url-list 'risky-local-variable t)
931
932 (defcustom bibtex-cite-matcher-alist
933 '(("\\\\cite[ \t\n]*{\\([^}]+\\)}" . 1))
934 "Alist of rules to identify cited keys in a BibTeX entry.
935 Each rule should be of the form (REGEXP . SUBEXP), where SUBEXP
936 specifies which parenthesized expression in REGEXP is a cited key.
937 Case is significant.
938 Used by `bibtex-search-crossref' and for font-locking."
939 :group 'bibtex
940 :type '(repeat (cons (regexp :tag "Regexp")
941 (integer :tag "Number"))))
942
943 (defcustom bibtex-expand-strings nil
944 "If non-nil, expand strings when extracting the content of a BibTeX field."
945 :group 'bibtex
946 :type 'boolean)
947
948 ;; `bibtex-font-lock-keywords' is a user option, too. But since the
949 ;; patterns used to define this variable are defined in a later
950 ;; section of this file, it is defined later.
951
952 \f
953 ;; Syntax Table and Keybindings
954 (defvar bibtex-mode-syntax-table
955 (let ((st (make-syntax-table)))
956 (modify-syntax-entry ?\" "\"" st)
957 (modify-syntax-entry ?$ "$$ " st)
958 (modify-syntax-entry ?% "< " st)
959 (modify-syntax-entry ?' "w " st)
960 (modify-syntax-entry ?@ "w " st)
961 (modify-syntax-entry ?\\ "\\" st)
962 (modify-syntax-entry ?\f "> " st)
963 (modify-syntax-entry ?\n "> " st)
964 ;; Keys cannot have = in them (wrong font-lock of @string{foo=bar}).
965 (modify-syntax-entry ?= "." st)
966 (modify-syntax-entry ?~ " " st)
967 st)
968 "Syntax table used in BibTeX mode buffers.")
969
970 (defvar bibtex-mode-map
971 (let ((km (make-sparse-keymap)))
972 ;; The Key `C-c&' is reserved for reftex.el
973 (define-key km "\t" 'bibtex-find-text)
974 (define-key km "\n" 'bibtex-next-field)
975 (define-key km "\M-\t" 'bibtex-complete)
976 (define-key km "\C-c\"" 'bibtex-remove-delimiters)
977 (define-key km "\C-c{" 'bibtex-remove-delimiters)
978 (define-key km "\C-c}" 'bibtex-remove-delimiters)
979 (define-key km "\C-c\C-c" 'bibtex-clean-entry)
980 (define-key km "\C-c\C-q" 'bibtex-fill-entry)
981 (define-key km "\C-c\C-s" 'bibtex-search-entry)
982 (define-key km "\C-c\C-x" 'bibtex-search-crossref)
983 (define-key km "\C-c\C-t" 'bibtex-copy-summary-as-kill)
984 (define-key km "\C-c?" 'bibtex-print-help-message)
985 (define-key km "\C-c\C-p" 'bibtex-pop-previous)
986 (define-key km "\C-c\C-n" 'bibtex-pop-next)
987 (define-key km "\C-c\C-k" 'bibtex-kill-field)
988 (define-key km "\C-c\M-k" 'bibtex-copy-field-as-kill)
989 (define-key km "\C-c\C-w" 'bibtex-kill-entry)
990 (define-key km "\C-c\M-w" 'bibtex-copy-entry-as-kill)
991 (define-key km "\C-c\C-y" 'bibtex-yank)
992 (define-key km "\C-c\M-y" 'bibtex-yank-pop)
993 (define-key km "\C-c\C-d" 'bibtex-empty-field)
994 (define-key km "\C-c\C-f" 'bibtex-make-field)
995 (define-key km "\C-c\C-u" 'bibtex-entry-update)
996 (define-key km "\C-c$" 'bibtex-ispell-abstract)
997 (define-key km "\M-\C-a" 'bibtex-beginning-of-entry)
998 (define-key km "\M-\C-e" 'bibtex-end-of-entry)
999 (define-key km "\C-\M-l" 'bibtex-reposition-window)
1000 (define-key km "\C-\M-h" 'bibtex-mark-entry)
1001 (define-key km "\C-c\C-b" 'bibtex-entry)
1002 (define-key km "\C-c\C-rn" 'bibtex-narrow-to-entry)
1003 (define-key km "\C-c\C-rw" 'widen)
1004 (define-key km "\C-c\C-l" 'bibtex-url)
1005 (define-key km "\C-c\C-o" 'bibtex-remove-OPT-or-ALT)
1006 (define-key km "\C-c\C-e\C-i" 'bibtex-InProceedings)
1007 (define-key km "\C-c\C-ei" 'bibtex-InCollection)
1008 (define-key km "\C-c\C-eI" 'bibtex-InBook)
1009 (define-key km "\C-c\C-e\C-a" 'bibtex-Article)
1010 (define-key km "\C-c\C-e\C-b" 'bibtex-InBook)
1011 (define-key km "\C-c\C-eb" 'bibtex-Book)
1012 (define-key km "\C-c\C-eB" 'bibtex-Booklet)
1013 (define-key km "\C-c\C-e\C-c" 'bibtex-InCollection)
1014 (define-key km "\C-c\C-e\C-m" 'bibtex-Manual)
1015 (define-key km "\C-c\C-em" 'bibtex-MastersThesis)
1016 (define-key km "\C-c\C-eM" 'bibtex-Misc)
1017 (define-key km "\C-c\C-e\C-p" 'bibtex-InProceedings)
1018 (define-key km "\C-c\C-ep" 'bibtex-Proceedings)
1019 (define-key km "\C-c\C-eP" 'bibtex-PhdThesis)
1020 (define-key km "\C-c\C-e\M-p" 'bibtex-Preamble)
1021 (define-key km "\C-c\C-e\C-s" 'bibtex-String)
1022 (define-key km "\C-c\C-e\C-t" 'bibtex-TechReport)
1023 (define-key km "\C-c\C-e\C-u" 'bibtex-Unpublished)
1024 km)
1025 "Keymap used in BibTeX mode.")
1026
1027 (easy-menu-define
1028 bibtex-edit-menu bibtex-mode-map "BibTeX-Edit Menu in BibTeX mode"
1029 '("BibTeX-Edit"
1030 ("Moving inside an Entry"
1031 ["End of Field" bibtex-find-text t]
1032 ["Next Field" bibtex-next-field t]
1033 ["Beginning of Entry" bibtex-beginning-of-entry t]
1034 ["End of Entry" bibtex-end-of-entry t]
1035 "--"
1036 ["Make Entry Visible" bibtex-reposition-window t])
1037 ("Moving in BibTeX Buffers"
1038 ["Search Entry" bibtex-search-entry t]
1039 ["Search Crossref Entry" bibtex-search-crossref t])
1040 "--"
1041 ("Operating on Current Field"
1042 ["Fill Field" fill-paragraph t]
1043 ["Remove Delimiters" bibtex-remove-delimiters t]
1044 ["Remove OPT or ALT Prefix" bibtex-remove-OPT-or-ALT t]
1045 ["Clear Field" bibtex-empty-field t]
1046 "--"
1047 ["Kill Field" bibtex-kill-field t]
1048 ["Copy Field to Kill Ring" bibtex-copy-field-as-kill t]
1049 ["Paste Most Recently Killed Field" bibtex-yank t]
1050 ["Paste Previously Killed Field" bibtex-yank-pop t]
1051 "--"
1052 ["Make New Field" bibtex-make-field t]
1053 "--"
1054 ["Snatch from Similar Following Field" bibtex-pop-next t]
1055 ["Snatch from Similar Preceding Field" bibtex-pop-previous t]
1056 "--"
1057 ["String or Key Complete" bibtex-complete t]
1058 "--"
1059 ["Help about Current Field" bibtex-print-help-message t])
1060 ("Operating on Current Entry"
1061 ["Fill Entry" bibtex-fill-entry t]
1062 ["Clean Entry" bibtex-clean-entry t]
1063 ["Update Entry" bibtex-entry-update t]
1064 "--"
1065 ["Kill Entry" bibtex-kill-entry t]
1066 ["Copy Entry to Kill Ring" bibtex-copy-entry-as-kill t]
1067 ["Paste Most Recently Killed Entry" bibtex-yank t]
1068 ["Paste Previously Killed Entry" bibtex-yank-pop t]
1069 "--"
1070 ["Copy Summary to Kill Ring" bibtex-copy-summary-as-kill t]
1071 ["Browse URL" bibtex-url t]
1072 "--"
1073 ["Ispell Entry" bibtex-ispell-entry t]
1074 ["Ispell Entry Abstract" bibtex-ispell-abstract t]
1075 "--"
1076 ["Narrow to Entry" bibtex-narrow-to-entry t]
1077 ["Mark Entry" bibtex-mark-entry t]
1078 "--"
1079 ["View Cite Locations (RefTeX)" reftex-view-crossref-from-bibtex
1080 (fboundp 'reftex-view-crossref-from-bibtex)])
1081 ("Operating on Buffer or Region"
1082 ["Validate Entries" bibtex-validate t]
1083 ["Sort Entries" bibtex-sort-buffer t]
1084 ["Reformat Entries" bibtex-reformat t]
1085 ["Count Entries" bibtex-count-entries t]
1086 "--"
1087 ["Convert Alien Buffer" bibtex-convert-alien t])
1088 ("Operating on Multiple Buffers"
1089 ["(Re)Initialize BibTeX Buffers" bibtex-initialize t]
1090 ["Validate Entries" bibtex-validate-globally t])))
1091
1092 (easy-menu-define
1093 bibtex-entry-menu bibtex-mode-map "Entry-Types Menu in BibTeX mode"
1094 (list "Entry-Types"
1095 ["Article in Journal" bibtex-Article t]
1096 ["Article in Conference Proceedings" bibtex-InProceedings t]
1097 ["Article in a Collection" bibtex-InCollection t]
1098 ["Chapter or Pages in a Book" bibtex-InBook t]
1099 ["Conference Proceedings" bibtex-Proceedings t]
1100 ["Book" bibtex-Book t]
1101 ["Booklet (Bound, but no Publisher/Institution)" bibtex-Booklet t]
1102 ["PhD. Thesis" bibtex-PhdThesis t]
1103 ["Master's Thesis" bibtex-MastersThesis t]
1104 ["Technical Report" bibtex-TechReport t]
1105 ["Technical Manual" bibtex-Manual t]
1106 ["Unpublished" bibtex-Unpublished t]
1107 ["Miscellaneous" bibtex-Misc t]
1108 "--"
1109 ["String" bibtex-String t]
1110 ["Preamble" bibtex-Preamble t]))
1111
1112 \f
1113 ;; Internal Variables
1114
1115 (defvar bibtex-field-braces-opt nil
1116 "Optimized value of `bibtex-field-braces-alist'.
1117 Created by `bibtex-field-re-init'.
1118 It is a an alist with elements (FIELD . REGEXP).")
1119
1120 (defvar bibtex-field-strings-opt nil
1121 "Optimized value of `bibtex-field-strings-alist'.
1122 Created by `bibtex-field-re-init'.
1123 It is a an alist with elements (FIELD RULE1 RULE2 ...),
1124 where each RULE is (REGEXP . TO-STR).")
1125
1126 (defvar bibtex-pop-previous-search-point nil
1127 "Next point where `bibtex-pop-previous' starts looking for a similar entry.")
1128
1129 (defvar bibtex-pop-next-search-point nil
1130 "Next point where `bibtex-pop-next' starts looking for a similar entry.")
1131
1132 (defvar bibtex-field-kill-ring nil
1133 "Ring of least recently killed fields.
1134 At most `bibtex-field-kill-ring-max' items are kept here.")
1135
1136 (defvar bibtex-field-kill-ring-yank-pointer nil
1137 "The tail of `bibtex-field-kill-ring' whose car is the last item yanked.")
1138
1139 (defvar bibtex-entry-kill-ring nil
1140 "Ring of least recently killed entries.
1141 At most `bibtex-entry-kill-ring-max' items are kept here.")
1142
1143 (defvar bibtex-entry-kill-ring-yank-pointer nil
1144 "The tail of `bibtex-entry-kill-ring' whose car is the last item yanked.")
1145
1146 (defvar bibtex-last-kill-command nil
1147 "Type of the last kill command (either 'field or 'entry).")
1148
1149 (defvar bibtex-strings
1150 (lazy-completion-table bibtex-strings
1151 (lambda ()
1152 (bibtex-parse-strings (bibtex-string-files-init))))
1153 "Completion table for BibTeX string keys.
1154 Initialized from `bibtex-predefined-strings' and `bibtex-string-files'.")
1155 (make-variable-buffer-local 'bibtex-strings)
1156 (put 'bibtex-strings 'risky-local-variable t)
1157
1158 (defvar bibtex-reference-keys
1159 (lazy-completion-table bibtex-reference-keys
1160 (lambda () (bibtex-parse-keys nil t)))
1161 "Completion table for BibTeX reference keys.
1162 The CDRs of the elements are t for header keys and nil for crossref keys.")
1163 (make-variable-buffer-local 'bibtex-reference-keys)
1164 (put 'bibtex-reference-keys 'risky-local-variable t)
1165
1166 (defvar bibtex-buffer-last-parsed-tick nil
1167 "Value of `buffer-modified-tick' last time buffer was parsed for keys.")
1168
1169 (defvar bibtex-parse-idle-timer nil
1170 "Stores if timer is already installed.")
1171
1172 (defvar bibtex-progress-lastperc nil
1173 "Last reported percentage for the progress message.")
1174
1175 (defvar bibtex-progress-lastmes nil
1176 "Last reported progress message.")
1177
1178 (defvar bibtex-progress-interval nil
1179 "Interval for progress messages.")
1180
1181 (defvar bibtex-key-history nil
1182 "History list for reading keys.")
1183
1184 (defvar bibtex-entry-type-history nil
1185 "History list for reading entry types.")
1186
1187 (defvar bibtex-field-history nil
1188 "History list for reading field names.")
1189
1190 (defvar bibtex-reformat-previous-options nil
1191 "Last reformat options given.")
1192
1193 (defvar bibtex-reformat-previous-reference-keys nil
1194 "Last reformat reference keys option given.")
1195
1196 (defconst bibtex-field-name "[^\"#%'(),={} \t\n0-9][^\"#%'(),={} \t\n]*"
1197 "Regexp matching the name of a BibTeX field.")
1198
1199 (defconst bibtex-name-part
1200 (concat ",[ \t\n]*\\(" bibtex-field-name "\\)")
1201 "Regexp matching the name part of a BibTeX field.")
1202
1203 (defconst bibtex-reference-key "[][[:alnum:].:;?!`'/*@+|()<>&_^$-]+"
1204 "Regexp matching the reference key part of a BibTeX entry.")
1205
1206 (defconst bibtex-field-const "[][[:alnum:].:;?!`'/*@+=|<>&_^$-]+"
1207 "Regexp matching a BibTeX field constant.")
1208
1209 (defvar bibtex-entry-type
1210 (concat "@[ \t]*\\(?:"
1211 (regexp-opt (mapcar 'car bibtex-entry-field-alist)) "\\)")
1212 "Regexp matching the type of a BibTeX entry.")
1213
1214 (defvar bibtex-entry-head
1215 (concat "^[ \t]*\\("
1216 bibtex-entry-type
1217 "\\)[ \t]*[({][ \t\n]*\\("
1218 bibtex-reference-key
1219 "\\)")
1220 "Regexp matching the header line of a BibTeX entry (including key).")
1221
1222 (defvar bibtex-entry-maybe-empty-head
1223 (concat bibtex-entry-head "?")
1224 "Regexp matching the header line of a BibTeX entry (possibly without key).")
1225
1226 (defconst bibtex-any-entry-maybe-empty-head
1227 (concat "^[ \t]*\\(@[ \t]*" bibtex-field-name "\\)[ \t]*[({][ \t\n]*\\("
1228 bibtex-reference-key "\\)?")
1229 "Regexp matching the header line of any BibTeX entry (possibly without key).")
1230
1231 (defvar bibtex-any-valid-entry-type
1232 (concat "^[ \t]*@[ \t]*\\(?:"
1233 (regexp-opt (append '("String" "Preamble")
1234 (mapcar 'car bibtex-entry-field-alist))) "\\)")
1235 "Regexp matching any valid BibTeX entry (including String and Preamble).")
1236
1237 (defconst bibtex-type-in-head 1
1238 "Regexp subexpression number of the type part in `bibtex-entry-head'.")
1239
1240 (defconst bibtex-key-in-head 2
1241 "Regexp subexpression number of the key part in `bibtex-entry-head'.")
1242
1243 (defconst bibtex-string-type "^[ \t]*\\(@[ \t]*String\\)[ \t]*[({][ \t\n]*"
1244 "Regexp matching the name of a BibTeX String entry.")
1245
1246 (defconst bibtex-string-maybe-empty-head
1247 (concat bibtex-string-type "\\(" bibtex-reference-key "\\)?")
1248 "Regexp matching the header line of a BibTeX String entry.")
1249
1250 (defconst bibtex-preamble-prefix
1251 "[ \t]*\\(@[ \t]*Preamble\\)[ \t]*[({][ \t\n]*"
1252 "Regexp matching the prefix part of a BibTeX Preamble entry.")
1253
1254 (defconst bibtex-font-lock-syntactic-keywords
1255 `((,(concat "^[ \t]*\\(" (substring bibtex-comment-start 0 1) "\\)"
1256 (substring bibtex-comment-start 1) "\\>")
1257 1 '(11))))
1258
1259 (defvar bibtex-font-lock-keywords
1260 ;; entry type and reference key
1261 `((,bibtex-any-entry-maybe-empty-head
1262 (,bibtex-type-in-head font-lock-function-name-face)
1263 (,bibtex-key-in-head font-lock-constant-face nil t))
1264 ;; optional field names (treated as comments)
1265 (,(concat "^[ \t]*\\(OPT" bibtex-field-name "\\)[ \t]*=")
1266 1 font-lock-comment-face)
1267 ;; field names
1268 (,(concat "^[ \t]*\\(" bibtex-field-name "\\)[ \t]*=")
1269 1 font-lock-variable-name-face)
1270 ;; url
1271 (bibtex-font-lock-url) (bibtex-font-lock-crossref)
1272 ;; cite
1273 ,@(mapcar (lambda (matcher)
1274 `((lambda (bound) (bibtex-font-lock-cite ',matcher bound))))
1275 bibtex-cite-matcher-alist))
1276 "*Default expressions to highlight in BibTeX mode.")
1277
1278 (defvar bibtex-font-lock-url-regexp
1279 ;; Assume that field names begin at the beginning of a line.
1280 (concat "^[ \t]*"
1281 (regexp-opt (delete-dups (mapcar 'caar bibtex-generate-url-list)) t)
1282 "[ \t]*=[ \t]*")
1283 "Regexp for `bibtex-font-lock-url' derived from `bibtex-generate-url-list'.")
1284
1285 (defvar bibtex-string-empty-key nil
1286 "If non-nil, `bibtex-parse-string' accepts empty key.")
1287
1288 (defvar bibtex-sort-entry-class-alist nil
1289 "Alist mapping entry types to their sorting index.
1290 Auto-generated from `bibtex-sort-entry-class'.
1291 Used when `bibtex-maintain-sorted-entries' is `entry-class'.")
1292
1293 \f
1294 (defun bibtex-parse-association (parse-lhs parse-rhs)
1295 "Parse a string of the format <left-hand-side = right-hand-side>.
1296 The functions PARSE-LHS and PARSE-RHS are used to parse the corresponding
1297 substrings. These functions are expected to return nil if parsing is not
1298 successful. If the returned values of both functions are non-nil,
1299 return a cons pair of these values. Do not move point."
1300 (save-match-data
1301 (save-excursion
1302 (let ((left (funcall parse-lhs))
1303 right)
1304 (if (and left
1305 (looking-at "[ \t\n]*=[ \t\n]*")
1306 (goto-char (match-end 0))
1307 (setq right (funcall parse-rhs)))
1308 (cons left right))))))
1309
1310 (defun bibtex-parse-field-name ()
1311 "Parse the name part of a BibTeX field.
1312 If the field name is found, return a triple consisting of the position of the
1313 very first character of the match, the actual starting position of the name
1314 part and end position of the match. Move point to end of field name.
1315 If `bibtex-autoadd-commas' is non-nil add missing comma at end of preceding
1316 BibTeX field as necessary."
1317 (cond ((looking-at bibtex-name-part)
1318 (goto-char (match-end 0))
1319 (list (match-beginning 0) (match-beginning 1) (match-end 0)))
1320 ;; Maybe add a missing comma.
1321 ((and bibtex-autoadd-commas
1322 (looking-at (concat "[ \t\n]*\\(?:" bibtex-field-name
1323 "\\)[ \t\n]*=")))
1324 (skip-chars-backward " \t\n")
1325 ;; It can be confusing if non-editing commands try to
1326 ;; modify the buffer.
1327 (if buffer-read-only
1328 (error "Comma missing at buffer position %s" (point)))
1329 (insert ",")
1330 (forward-char -1)
1331 ;; Now try again.
1332 (bibtex-parse-field-name))))
1333
1334 (defconst bibtex-braced-string-syntax-table
1335 (let ((st (make-syntax-table)))
1336 (modify-syntax-entry ?\{ "(}" st)
1337 (modify-syntax-entry ?\} "){" st)
1338 (modify-syntax-entry ?\[ "." st)
1339 (modify-syntax-entry ?\] "." st)
1340 (modify-syntax-entry ?\( "." st)
1341 (modify-syntax-entry ?\) "." st)
1342 (modify-syntax-entry ?\\ "." st)
1343 (modify-syntax-entry ?\" "." st)
1344 st)
1345 "Syntax-table to parse matched braces.")
1346
1347 (defconst bibtex-quoted-string-syntax-table
1348 (let ((st (make-syntax-table)))
1349 (modify-syntax-entry ?\\ "\\" st)
1350 (modify-syntax-entry ?\" "\"" st)
1351 st)
1352 "Syntax-table to parse matched quotes.")
1353
1354 (defun bibtex-parse-field-string ()
1355 "Parse a BibTeX field string enclosed by braces or quotes.
1356 If a syntactically correct string is found, a pair containing the start and
1357 end position of the field string is returned, nil otherwise.
1358 Do not move point."
1359 (let ((end-point
1360 (or (and (eq (following-char) ?\")
1361 (save-excursion
1362 (with-syntax-table bibtex-quoted-string-syntax-table
1363 (forward-sexp 1))
1364 (point)))
1365 (and (eq (following-char) ?\{)
1366 (save-excursion
1367 (with-syntax-table bibtex-braced-string-syntax-table
1368 (forward-sexp 1))
1369 (point))))))
1370 (if end-point
1371 (cons (point) end-point))))
1372
1373 (defun bibtex-parse-field-text ()
1374 "Parse the text part of a BibTeX field.
1375 The text part is either a string, or an empty string, or a constant followed
1376 by one or more <# (string|constant)> pairs. If a syntactically correct text
1377 is found, a pair containing the start and end position of the text is
1378 returned, nil otherwise. Move point to end of field text."
1379 (let ((starting-point (point))
1380 end-point failure boundaries)
1381 (while (not (or end-point failure))
1382 (cond ((looking-at bibtex-field-const)
1383 (goto-char (match-end 0)))
1384 ((setq boundaries (bibtex-parse-field-string))
1385 (goto-char (cdr boundaries)))
1386 ((setq failure t)))
1387 (if (looking-at "[ \t\n]*#[ \t\n]*")
1388 (goto-char (match-end 0))
1389 (setq end-point (point))))
1390 (skip-chars-forward " \t\n")
1391 (if (and (not failure)
1392 end-point)
1393 (list starting-point end-point (point)))))
1394
1395 (defun bibtex-parse-field ()
1396 "Parse the BibTeX field beginning at the position of point.
1397 If a syntactically correct field is found, return a cons pair containing
1398 the boundaries of the name and text parts of the field. Do not move point."
1399 (bibtex-parse-association 'bibtex-parse-field-name
1400 'bibtex-parse-field-text))
1401
1402 (defsubst bibtex-start-of-field (bounds)
1403 (nth 0 (car bounds)))
1404 (defsubst bibtex-start-of-name-in-field (bounds)
1405 (nth 1 (car bounds)))
1406 (defsubst bibtex-end-of-name-in-field (bounds)
1407 (nth 2 (car bounds)))
1408 (defsubst bibtex-start-of-text-in-field (bounds)
1409 (nth 1 bounds))
1410 (defsubst bibtex-end-of-text-in-field (bounds)
1411 (nth 2 bounds))
1412 (defsubst bibtex-end-of-field (bounds)
1413 (nth 3 bounds))
1414
1415 (defun bibtex-search-forward-field (name &optional bound)
1416 "Search forward to find a BibTeX field of name NAME.
1417 If a syntactically correct field is found, return a pair containing
1418 the boundaries of the name and text parts of the field. The search
1419 is limited by optional arg BOUND. If BOUND is t the search is limited
1420 by the end of the current entry. Do not move point."
1421 (save-match-data
1422 (save-excursion
1423 (if (eq bound t)
1424 (let ((regexp (concat bibtex-name-part "[ \t\n]*=\\|"
1425 bibtex-any-entry-maybe-empty-head))
1426 (case-fold-search t) bounds)
1427 (catch 'done
1428 (if (looking-at "[ \t]*@") (goto-char (match-end 0)))
1429 (while (and (not bounds)
1430 (re-search-forward regexp nil t))
1431 (if (match-beginning 2)
1432 ;; We found a new entry
1433 (throw 'done nil)
1434 ;; We found a field
1435 (goto-char (match-beginning 0))
1436 (setq bounds (bibtex-parse-field))))
1437 ;; Step through all fields so that we cannot overshoot.
1438 (while bounds
1439 (goto-char (bibtex-start-of-name-in-field bounds))
1440 (if (looking-at name) (throw 'done bounds))
1441 (goto-char (bibtex-end-of-field bounds))
1442 (setq bounds (bibtex-parse-field)))))
1443 ;; Bounded search or bound is nil (i.e. we cannot overshoot).
1444 ;; Indeed, the search is bounded when `bibtex-search-forward-field'
1445 ;; is called many times. So we optimize this part of this function.
1446 (let ((name-part (concat ",[ \t\n]*\\(" name "\\)[ \t\n]*=[ \t\n]*"))
1447 (case-fold-search t) left right)
1448 (while (and (not right)
1449 (re-search-forward name-part bound t))
1450 (setq left (list (match-beginning 0) (match-beginning 1)
1451 (match-end 1))
1452 ;; Don't worry that the field text could be past bound.
1453 right (bibtex-parse-field-text)))
1454 (if right (cons left right)))))))
1455
1456 (defun bibtex-search-backward-field (name &optional bound)
1457 "Search backward to find a BibTeX field of name NAME.
1458 If a syntactically correct field is found, return a pair containing
1459 the boundaries of the name and text parts of the field. The search
1460 is limited by the optional arg BOUND. If BOUND is t the search is
1461 limited by the beginning of the current entry. Do not move point."
1462 (save-match-data
1463 (if (eq bound t)
1464 (setq bound (save-excursion (bibtex-beginning-of-entry))))
1465 (let ((name-part (concat ",[ \t\n]*\\(" name "\\)[ \t\n]*=[ \t\n]*"))
1466 (case-fold-search t) left right)
1467 (save-excursion
1468 ;; the parsing functions are not designed for parsing backwards :-(
1469 (when (search-backward "," bound t)
1470 (or (save-excursion
1471 (when (looking-at name-part)
1472 (setq left (list (match-beginning 0) (match-beginning 1)
1473 (match-end 1)))
1474 (goto-char (match-end 0))
1475 (setq right (bibtex-parse-field-text))))
1476 (while (and (not right)
1477 (re-search-backward name-part bound t))
1478 (setq left (list (match-beginning 0) (match-beginning 1)
1479 (match-end 1)))
1480 (save-excursion
1481 (goto-char (match-end 0))
1482 (setq right (bibtex-parse-field-text)))))
1483 (if right (cons left right)))))))
1484
1485 (defun bibtex-name-in-field (bounds &optional remove-opt-alt)
1486 "Get content of name in BibTeX field defined via BOUNDS.
1487 If optional arg REMOVE-OPT-ALT is non-nil remove \"OPT\" and \"ALT\"."
1488 (let ((name (buffer-substring-no-properties
1489 (bibtex-start-of-name-in-field bounds)
1490 (bibtex-end-of-name-in-field bounds))))
1491 (if (and remove-opt-alt
1492 (string-match "\\`\\(OPT\\|ALT\\)" name))
1493 (substring name 3)
1494 name)))
1495
1496 (defun bibtex-text-in-field-bounds (bounds &optional content)
1497 "Get text in BibTeX field defined via BOUNDS.
1498 If optional arg CONTENT is non-nil extract content of field
1499 by removing field delimiters and concatenating the resulting string.
1500 If `bibtex-expand-strings' is non-nil, also expand BibTeX strings."
1501 (if content
1502 (save-excursion
1503 (goto-char (bibtex-start-of-text-in-field bounds))
1504 (let ((epoint (bibtex-end-of-text-in-field bounds))
1505 content opoint)
1506 (while (< (setq opoint (point)) epoint)
1507 (if (looking-at bibtex-field-const)
1508 (let ((mtch (match-string-no-properties 0)))
1509 (push (or (if bibtex-expand-strings
1510 (cdr (assoc-string mtch (bibtex-strings) t)))
1511 mtch) content)
1512 (goto-char (match-end 0)))
1513 (let ((bounds (bibtex-parse-field-string)))
1514 (push (buffer-substring-no-properties
1515 (1+ (car bounds)) (1- (cdr bounds))) content)
1516 (goto-char (cdr bounds))))
1517 (re-search-forward "\\=[ \t\n]*#[ \t\n]*" nil t))
1518 (apply 'concat (nreverse content))))
1519 (buffer-substring-no-properties (bibtex-start-of-text-in-field bounds)
1520 (bibtex-end-of-text-in-field bounds))))
1521
1522 (defun bibtex-text-in-field (field &optional follow-crossref)
1523 "Get content of field FIELD of current BibTeX entry.
1524 Return nil if not found.
1525 If optional arg FOLLOW-CROSSREF is non-nil, follow crossref."
1526 (save-excursion
1527 (let* ((end (if follow-crossref (bibtex-end-of-entry) t))
1528 (beg (bibtex-beginning-of-entry)) ; move point
1529 (bounds (bibtex-search-forward-field field end)))
1530 (cond (bounds (bibtex-text-in-field-bounds bounds t))
1531 ((and follow-crossref
1532 (progn (goto-char beg)
1533 (setq bounds (bibtex-search-forward-field
1534 "\\(OPT\\)?crossref" end))))
1535 (let ((crossref-field (bibtex-text-in-field-bounds bounds t)))
1536 (if (bibtex-search-crossref crossref-field)
1537 ;; Do not pass FOLLOW-CROSSREF because we want
1538 ;; to follow crossrefs only one level of recursion.
1539 (bibtex-text-in-field field))))))))
1540
1541 (defun bibtex-parse-string-prefix ()
1542 "Parse the prefix part of a BibTeX string entry, including reference key.
1543 If the string prefix is found, return a triple consisting of the position of
1544 the very first character of the match, the actual starting position of the
1545 reference key and the end position of the match.
1546 If `bibtex-string-empty-key' is non-nil accept empty string key."
1547 (let ((case-fold-search t))
1548 (if (looking-at bibtex-string-type)
1549 (let ((start (point)))
1550 (goto-char (match-end 0))
1551 (cond ((looking-at bibtex-reference-key)
1552 (goto-char (match-end 0))
1553 (list start
1554 (match-beginning 0)
1555 (match-end 0)))
1556 ((and bibtex-string-empty-key
1557 (looking-at "="))
1558 (skip-chars-backward " \t\n")
1559 (list start (point) (point))))))))
1560
1561 (defun bibtex-parse-string-postfix ()
1562 "Parse the postfix part of a BibTeX string entry, including the text.
1563 If the string postfix is found, return a triple consisting of the position of
1564 the actual starting and ending position of the text and the very last
1565 character of the string entry. Move point past BibTeX string entry."
1566 (let* ((case-fold-search t)
1567 (bounds (bibtex-parse-field-text)))
1568 (when bounds
1569 (goto-char (nth 1 bounds))
1570 (when (looking-at "[ \t\n]*[})]")
1571 (goto-char (match-end 0))
1572 (list (car bounds)
1573 (nth 1 bounds)
1574 (match-end 0))))))
1575
1576 (defun bibtex-parse-string (&optional empty-key)
1577 "Parse a BibTeX string entry beginning at the position of point.
1578 If a syntactically correct entry is found, return a cons pair containing
1579 the boundaries of the reference key and text parts of the entry.
1580 If EMPTY-KEY is non-nil, key may be empty. Do not move point."
1581 (let ((bibtex-string-empty-key empty-key))
1582 (bibtex-parse-association 'bibtex-parse-string-prefix
1583 'bibtex-parse-string-postfix)))
1584
1585 (defun bibtex-search-forward-string (&optional empty-key)
1586 "Search forward to find a BibTeX string entry.
1587 If a syntactically correct entry is found, a pair containing the boundaries of
1588 the reference key and text parts of the string is returned.
1589 If EMPTY-KEY is non-nil, key may be empty. Do not move point."
1590 (save-excursion
1591 (save-match-data
1592 (let ((case-fold-search t) bounds)
1593 (while (and (not bounds)
1594 (search-forward-regexp bibtex-string-type nil t))
1595 (save-excursion (goto-char (match-beginning 0))
1596 (setq bounds (bibtex-parse-string empty-key))))
1597 bounds))))
1598
1599 (defun bibtex-reference-key-in-string (bounds)
1600 "Return the key part of a BibTeX string defined via BOUNDS."
1601 (buffer-substring-no-properties (nth 1 (car bounds))
1602 (nth 2 (car bounds))))
1603
1604 (defun bibtex-text-in-string (bounds &optional content)
1605 "Get text in BibTeX string field defined via BOUNDS.
1606 If optional arg CONTENT is non-nil extract content
1607 by removing field delimiters and concatenating the resulting string.
1608 If `bibtex-expand-strings' is non-nil, also expand BibTeX strings."
1609 (bibtex-text-in-field-bounds bounds content))
1610
1611 (defsubst bibtex-start-of-text-in-string (bounds)
1612 (nth 0 (cdr bounds)))
1613 (defsubst bibtex-end-of-text-in-string (bounds)
1614 (nth 1 (cdr bounds)))
1615 (defsubst bibtex-end-of-string (bounds)
1616 (nth 2 (cdr bounds)))
1617
1618 (defsubst bibtex-type-in-head ()
1619 "Extract BibTeX type in head."
1620 ;; ignore @
1621 (buffer-substring-no-properties (1+ (match-beginning bibtex-type-in-head))
1622 (match-end bibtex-type-in-head)))
1623
1624 (defsubst bibtex-key-in-head (&optional empty)
1625 "Extract BibTeX key in head. Return optional arg EMPTY if key is empty."
1626 (or (match-string-no-properties bibtex-key-in-head)
1627 empty))
1628
1629 (defun bibtex-parse-preamble ()
1630 "Parse BibTeX preamble.
1631 Point must be at beginning of preamble. Do not move point."
1632 (let ((case-fold-search t))
1633 (when (looking-at bibtex-preamble-prefix)
1634 (let ((start (match-beginning 0)) (pref-start (match-beginning 1))
1635 (bounds (save-excursion (goto-char (match-end 0))
1636 (bibtex-parse-string-postfix))))
1637 (if bounds (cons (list start pref-start) bounds))))))
1638
1639 ;; Helper Functions
1640
1641 (defsubst bibtex-string= (str1 str2)
1642 "Return t if STR1 and STR2 are equal, ignoring case."
1643 (eq t (compare-strings str1 0 nil str2 0 nil t)))
1644
1645 (defun bibtex-delete-whitespace ()
1646 "Delete all whitespace starting at point."
1647 (if (looking-at "[ \t\n]+")
1648 (delete-region (point) (match-end 0))))
1649
1650 (defun bibtex-current-line ()
1651 "Compute line number of point regardless whether the buffer is narrowed."
1652 (+ (count-lines 1 (point))
1653 (if (bolp) 1 0)))
1654
1655 (defun bibtex-valid-entry (&optional empty-key)
1656 "Parse a valid BibTeX entry (maybe without key if EMPTY-KEY is t).
1657 A valid entry is a syntactical correct one with type contained in
1658 `bibtex-entry-field-alist'. Ignore @String and @Preamble entries.
1659 Return a cons pair with buffer positions of beginning and end of entry
1660 if a valid entry is found, nil otherwise. Do not move point.
1661 After a call to this function `match-data' corresponds to the header
1662 of the entry, see regexp `bibtex-entry-head'."
1663 (let ((case-fold-search t) end)
1664 (if (looking-at (if empty-key bibtex-entry-maybe-empty-head
1665 bibtex-entry-head))
1666 (save-excursion
1667 (save-match-data
1668 (goto-char (match-end 0))
1669 (let ((entry-closer
1670 (if (save-excursion
1671 (goto-char (match-end bibtex-type-in-head))
1672 (looking-at "[ \t]*("))
1673 ",?[ \t\n]*)" ; entry opened with `('
1674 ",?[ \t\n]*}")) ; entry opened with `{'
1675 bounds)
1676 (skip-chars-forward " \t\n")
1677 ;; loop over all BibTeX fields
1678 (while (setq bounds (bibtex-parse-field))
1679 (goto-char (bibtex-end-of-field bounds)))
1680 ;; This matches the infix* part.
1681 (if (looking-at entry-closer) (setq end (match-end 0)))))
1682 (if end (cons (match-beginning 0) end))))))
1683
1684 (defun bibtex-skip-to-valid-entry (&optional backward)
1685 "Move point to beginning of the next valid BibTeX entry.
1686 Do not move if we are already at beginning of a valid BibTeX entry.
1687 With optional argument BACKWARD non-nil, move backward to
1688 beginning of previous valid one. A valid entry is a syntactical correct one
1689 with type contained in `bibtex-entry-field-alist' or, if
1690 `bibtex-sort-ignore-string-entries' is nil, a syntactical correct string
1691 entry. Return buffer position of beginning and end of entry if a valid
1692 entry is found, nil otherwise."
1693 (interactive "P")
1694 (let ((case-fold-search t)
1695 found bounds)
1696 (beginning-of-line)
1697 ;; Loop till we look at a valid entry.
1698 (while (not (or found (if backward (bobp) (eobp))))
1699 (cond ((setq found (or (bibtex-valid-entry)
1700 (and (not bibtex-sort-ignore-string-entries)
1701 (setq bounds (bibtex-parse-string))
1702 (cons (bibtex-start-of-field bounds)
1703 (bibtex-end-of-string bounds))))))
1704 (backward (re-search-backward "^[ \t]*@" nil 'move))
1705 (t (if (re-search-forward "\n\\([ \t]*@\\)" nil 'move)
1706 (goto-char (match-beginning 1))))))
1707 found))
1708
1709 (defun bibtex-map-entries (fun)
1710 "Call FUN for each BibTeX entry in buffer (possibly narrowed).
1711 FUN is called with three arguments, the key of the entry and the buffer
1712 positions of beginning and end of entry. Also, point is at beginning of
1713 entry and `match-data' corresponds to the header of the entry,
1714 see regexp `bibtex-entry-head'. If `bibtex-sort-ignore-string-entries'
1715 is non-nil, FUN is not called for @String entries."
1716 (let ((case-fold-search t)
1717 found)
1718 (save-excursion
1719 (goto-char (point-min))
1720 (while (setq found (bibtex-skip-to-valid-entry))
1721 (looking-at bibtex-any-entry-maybe-empty-head)
1722 (funcall fun (bibtex-key-in-head "") (car found) (cdr found))
1723 (goto-char (cdr found))))))
1724
1725 (defun bibtex-progress-message (&optional flag interval)
1726 "Echo a message about progress of current buffer.
1727 If FLAG is a string, the message is initialized (in this case a
1728 value for INTERVAL may be given as well (if not this is set to 5)).
1729 If FLAG is `done', the message is deinitialized.
1730 If FLAG is nil, a message is echoed if point was incremented at least
1731 `bibtex-progress-interval' percent since last message was echoed."
1732 (cond ((stringp flag)
1733 (setq bibtex-progress-lastmes flag
1734 bibtex-progress-interval (or interval 5)
1735 bibtex-progress-lastperc 0))
1736 ((eq flag 'done)
1737 (message "%s (done)" bibtex-progress-lastmes)
1738 (setq bibtex-progress-lastmes nil))
1739 (t
1740 (let* ((size (- (point-max) (point-min)))
1741 (perc (if (= size 0)
1742 100
1743 (/ (* 100 (- (point) (point-min))) size))))
1744 (when (>= perc (+ bibtex-progress-lastperc
1745 bibtex-progress-interval))
1746 (setq bibtex-progress-lastperc perc)
1747 (message "%s (%d%%)" bibtex-progress-lastmes perc))))))
1748
1749 (defun bibtex-field-left-delimiter ()
1750 "Return a string dependent on `bibtex-field-delimiters'."
1751 (if (eq bibtex-field-delimiters 'braces)
1752 "{"
1753 "\""))
1754
1755 (defun bibtex-field-right-delimiter ()
1756 "Return a string dependent on `bibtex-field-delimiters'."
1757 (if (eq bibtex-field-delimiters 'braces)
1758 "}"
1759 "\""))
1760
1761 (defun bibtex-entry-left-delimiter ()
1762 "Return a string dependent on `bibtex-entry-delimiters'."
1763 (if (eq bibtex-entry-delimiters 'braces)
1764 "{"
1765 "("))
1766
1767 (defun bibtex-entry-right-delimiter ()
1768 "Return a string dependent on `bibtex-entry-delimiters'."
1769 (if (eq bibtex-entry-delimiters 'braces)
1770 "}"
1771 ")"))
1772
1773 (defun bibtex-flash-head (prompt)
1774 "Flash at BibTeX entry head before point, if it exists."
1775 (let ((case-fold-search t)
1776 (pnt (point)))
1777 (save-excursion
1778 (bibtex-beginning-of-entry)
1779 (when (and (looking-at bibtex-any-entry-maybe-empty-head)
1780 (< (point) pnt))
1781 (goto-char (match-beginning bibtex-type-in-head))
1782 (if (and (< 0 blink-matching-delay)
1783 (pos-visible-in-window-p (point)))
1784 (sit-for blink-matching-delay)
1785 (message "%s%s" prompt (buffer-substring-no-properties
1786 (point) (match-end bibtex-key-in-head))))))))
1787
1788 (defun bibtex-make-optional-field (field)
1789 "Make an optional field named FIELD in current BibTeX entry."
1790 (if (consp field)
1791 (bibtex-make-field (cons (concat "OPT" (car field)) (cdr field)))
1792 (bibtex-make-field (concat "OPT" field))))
1793
1794 (defun bibtex-move-outside-of-entry ()
1795 "Make sure point is outside of a BibTeX entry."
1796 (let ((orig-point (point)))
1797 (bibtex-end-of-entry)
1798 (when (< (point) orig-point)
1799 ;; We moved backward, so we weren't inside an entry to begin with.
1800 ;; Leave point at the beginning of a line, and preferably
1801 ;; at the beginning of a paragraph.
1802 (goto-char orig-point)
1803 (beginning-of-line 1)
1804 (unless (= ?\n (char-before (1- (point))))
1805 (re-search-forward "^[ \t]*[@\n]" nil 'move)
1806 (backward-char 1)))
1807 (skip-chars-forward " \t\n")))
1808
1809 (defun bibtex-beginning-of-first-entry ()
1810 "Go to beginning of line of first BibTeX entry in buffer.
1811 If `bibtex-sort-ignore-string-entries' is non-nil, @String entries
1812 are ignored. Return point"
1813 (goto-char (point-min))
1814 (bibtex-skip-to-valid-entry)
1815 (point))
1816
1817 (defun bibtex-enclosing-field (&optional comma noerr)
1818 "Search for BibTeX field enclosing point.
1819 For `bibtex-mode''s internal algorithms, a field begins at the comma
1820 following the preceding field. Usually, this is not what the user expects.
1821 Thus if COMMA is non-nil, the \"current field\" includes the terminating comma.
1822 Unless NOERR is non-nil, signal an error if no enclosing field is found.
1823 On success return bounds, nil otherwise. Do not move point."
1824 (save-excursion
1825 (when comma
1826 (end-of-line)
1827 (skip-chars-backward " \t")
1828 (if (= (preceding-char) ?,) (forward-char -1)))
1829
1830 (let ((bounds (bibtex-search-backward-field bibtex-field-name t)))
1831 (cond ((and bounds
1832 (<= (bibtex-start-of-field bounds) (point))
1833 (>= (bibtex-end-of-field bounds) (point)))
1834 bounds)
1835 ((not noerr)
1836 (error "Can't find enclosing BibTeX field"))))))
1837
1838 (defun bibtex-beginning-first-field (&optional beg)
1839 "Move point to beginning of first field.
1840 Optional arg BEG is beginning of entry."
1841 (if beg (goto-char beg) (bibtex-beginning-of-entry))
1842 (looking-at bibtex-any-entry-maybe-empty-head)
1843 (goto-char (match-end 0)))
1844
1845 (defun bibtex-insert-kill (n &optional comma)
1846 "Reinsert the Nth stretch of killed BibTeX text (field or entry).
1847 Optional arg COMMA is as in `bibtex-enclosing-field'."
1848 (unless bibtex-last-kill-command (error "BibTeX kill ring is empty"))
1849 (let ((fun (lambda (kryp kr) ; adapted from `current-kill'
1850 (car (set kryp (nthcdr (mod (- n (length (eval kryp)))
1851 (length kr)) kr))))))
1852 (if (eq bibtex-last-kill-command 'field)
1853 (progn
1854 ;; insert past the current field
1855 (goto-char (bibtex-end-of-field (bibtex-enclosing-field comma)))
1856 (push-mark)
1857 (bibtex-make-field (funcall fun 'bibtex-field-kill-ring-yank-pointer
1858 bibtex-field-kill-ring) t nil t))
1859 ;; insert past the current entry
1860 (bibtex-skip-to-valid-entry)
1861 (push-mark)
1862 (insert (funcall fun 'bibtex-entry-kill-ring-yank-pointer
1863 bibtex-entry-kill-ring)))))
1864
1865 (defun bibtex-format-entry ()
1866 "Helper function for `bibtex-clean-entry'.
1867 Formats current entry according to variable `bibtex-entry-format'."
1868 ;; initialize `bibtex-field-braces-opt' if necessary
1869 (if (and bibtex-field-braces-alist (not bibtex-field-braces-opt))
1870 (setq bibtex-field-braces-opt
1871 (bibtex-field-re-init bibtex-field-braces-alist 'braces)))
1872 ;; initialize `bibtex-field-strings-opt' if necessary
1873 (if (and bibtex-field-strings-alist (not bibtex-field-strings-opt))
1874 (setq bibtex-field-strings-opt
1875 (bibtex-field-re-init bibtex-field-strings-alist 'strings)))
1876
1877 (let ((case-fold-search t)
1878 (format (if (eq bibtex-entry-format t)
1879 '(realign opts-or-alts required-fields numerical-fields
1880 page-dashes whitespace inherit-booktitle
1881 last-comma delimiters unify-case braces
1882 strings)
1883 bibtex-entry-format))
1884 bounds crossref-key req-field-list default-field-list field-list
1885 alt-fields error-field-name)
1886 (unwind-protect
1887 ;; formatting (undone if error occurs)
1888 (atomic-change-group
1889 (save-excursion
1890 (save-restriction
1891 (bibtex-narrow-to-entry)
1892
1893 ;; There are more elegant high-level functions for several tasks
1894 ;; done by `bibtex-format-entry'. However, they contain some
1895 ;; redundancy compared with what we need to do anyway.
1896 ;; So for speed-up we avoid using them.
1897 ;; (`bibtex-format-entry' is called often by `bibtex-reformat'.)
1898
1899 ;; identify entry type
1900 (goto-char (point-min))
1901 (or (re-search-forward bibtex-entry-type nil t)
1902 (error "Not inside a BibTeX entry"))
1903 (let* ((beg-type (1+ (match-beginning 0)))
1904 (end-type (match-end 0))
1905 (entry-list (assoc-string (buffer-substring-no-properties
1906 beg-type end-type)
1907 bibtex-entry-field-alist t)))
1908
1909 ;; unify case of entry type
1910 (when (memq 'unify-case format)
1911 (delete-region beg-type end-type)
1912 (insert (car entry-list)))
1913
1914 ;; update left entry delimiter
1915 (when (memq 'delimiters format)
1916 (goto-char end-type)
1917 (skip-chars-forward " \t\n")
1918 (delete-char 1)
1919 (insert (bibtex-entry-left-delimiter)))
1920
1921 ;; Do we have a crossref key?
1922 (goto-char (point-min))
1923 (if (setq bounds (bibtex-search-forward-field "crossref"))
1924 (let ((text (bibtex-text-in-field-bounds bounds t)))
1925 (unless (equal "" text)
1926 (setq crossref-key text))))
1927
1928 ;; list of required fields appropriate for an entry with
1929 ;; or without crossref key.
1930 (setq req-field-list (if (and crossref-key (nth 2 entry-list))
1931 (car (nth 2 entry-list))
1932 (car (nth 1 entry-list)))
1933 ;; default list of fields that may appear in this entry
1934 default-field-list (append (nth 0 (nth 1 entry-list))
1935 (nth 1 (nth 1 entry-list))
1936 bibtex-user-optional-fields)))
1937
1938 ;; process all fields
1939 (bibtex-beginning-first-field (point-min))
1940 (while (setq bounds (bibtex-parse-field))
1941 (let* ((beg-field (copy-marker (bibtex-start-of-field bounds)))
1942 (end-field (copy-marker (bibtex-end-of-field bounds) t))
1943 (beg-name (copy-marker (bibtex-start-of-name-in-field bounds)))
1944 (end-name (copy-marker (bibtex-end-of-name-in-field bounds)))
1945 (beg-text (copy-marker (bibtex-start-of-text-in-field bounds)))
1946 (end-text (copy-marker (bibtex-end-of-text-in-field bounds) t))
1947 (opt-alt (string-match "OPT\\|ALT"
1948 (buffer-substring-no-properties
1949 beg-name (+ beg-name 3))))
1950 (field-name (buffer-substring-no-properties
1951 (if opt-alt (+ beg-name 3) beg-name) end-name))
1952 (empty-field (equal "" (bibtex-text-in-field-bounds bounds t)))
1953 deleted)
1954
1955 ;; keep track of alternatives
1956 (if (nth 3 (assoc-string field-name req-field-list t))
1957 (push field-name alt-fields))
1958
1959 (if (memq 'opts-or-alts format)
1960 ;; delete empty optional and alternative fields
1961 ;; (but keep empty required fields)
1962 (cond ((and empty-field
1963 (or opt-alt
1964 (let ((field (assoc-string
1965 field-name req-field-list t)))
1966 (or (not field) ; OPT field
1967 (nth 3 field))))) ; ALT field
1968 (delete-region beg-field end-field)
1969 (setq deleted t))
1970 ;; otherwise nonempty field: delete "OPT" or "ALT"
1971 (opt-alt
1972 (goto-char beg-name)
1973 (delete-char 3))))
1974
1975 (unless deleted
1976 (push field-name field-list)
1977
1978 ;; remove delimiters from purely numerical fields
1979 (when (and (memq 'numerical-fields format)
1980 (progn (goto-char beg-text)
1981 (looking-at "\\(\"[0-9]+\"\\)\\|\\({[0-9]+}\\)")))
1982 (goto-char end-text)
1983 (delete-char -1)
1984 (goto-char beg-text)
1985 (delete-char 1))
1986
1987 ;; update delimiters
1988 (when (memq 'delimiters format)
1989 (goto-char beg-text)
1990 (when (looking-at "[{\"]")
1991 (delete-char 1)
1992 (insert (bibtex-field-left-delimiter)))
1993 (goto-char (1- (marker-position end-text)))
1994 (when (looking-at "[}\"]")
1995 (delete-char 1)
1996 (insert (bibtex-field-right-delimiter))))
1997
1998 ;; update page dashes
1999 (if (and (memq 'page-dashes format)
2000 (bibtex-string= field-name "pages")
2001 (progn (goto-char beg-text)
2002 (looking-at
2003 "\\([\"{][0-9]+\\)[ \t\n]*--?[ \t\n]*\\([0-9]+[\"}]\\)")))
2004 (replace-match "\\1-\\2"))
2005
2006 ;; remove whitespace at beginning and end of field
2007 (when (memq 'whitespace format)
2008 (goto-char beg-text)
2009 (if (looking-at "\\([{\"]\\)[ \t\n]+")
2010 (replace-match "\\1"))
2011 (goto-char end-text)
2012 (if (looking-back "[ \t\n]+\\([}\"]\\)" beg-text t)
2013 (replace-match "\\1")))
2014
2015 ;; enclose field text by braces according to
2016 ;; `bibtex-field-braces-alist'.
2017 (let (case-fold-search temp) ; Case-sensitive search
2018 (when (and (memq 'braces format)
2019 (setq temp (cdr (assoc-string field-name
2020 bibtex-field-braces-opt t))))
2021 (goto-char beg-text)
2022 (while (re-search-forward temp end-text t)
2023 (let ((beg (match-beginning 0))
2024 (bounds (bibtex-find-text-internal nil t)))
2025 (unless (or (nth 4 bounds) ; string constant
2026 ;; match already surrounded by braces
2027 ;; (braces are inside field delimiters)
2028 (and (< (point) (1- (nth 2 bounds)))
2029 (< (1+ (nth 1 bounds)) beg)
2030 (looking-at "}")
2031 (save-excursion (goto-char (1- beg))
2032 (looking-at "{"))))
2033 (insert "}")
2034 (goto-char beg)
2035 (insert "{")))))
2036
2037 ;; replace field text by BibTeX string constants
2038 ;; according to `bibtex-field-strings-alist'.
2039 (when (and (memq 'strings format)
2040 (setq temp (cdr (assoc-string field-name
2041 bibtex-field-strings-opt t))))
2042 (goto-char beg-text)
2043 (dolist (re temp)
2044 (while (re-search-forward (car re) end-text t)
2045 (let ((bounds (save-match-data
2046 (bibtex-find-text-internal nil t))))
2047 (unless (nth 4 bounds)
2048 ;; if match not at right subfield boundary...
2049 (if (< (match-end 0) (1- (nth 2 bounds)))
2050 (insert " # " (bibtex-field-left-delimiter))
2051 (delete-char 1))
2052 (replace-match (cdr re))
2053 (goto-char (match-beginning 0))
2054 ;; if match not at left subfield boundary...
2055 (if (< (1+ (nth 1 bounds)) (match-beginning 0))
2056 (insert (bibtex-field-right-delimiter) " # ")
2057 (delete-backward-char 1))))))))
2058
2059 ;; use book title of crossref'd entry
2060 (if (and (memq 'inherit-booktitle format)
2061 empty-field
2062 (bibtex-string= field-name "booktitle")
2063 crossref-key)
2064 (let ((title (save-excursion
2065 (save-restriction
2066 (widen)
2067 (if (bibtex-search-entry crossref-key t)
2068 (bibtex-text-in-field "title"))))))
2069 (when title
2070 (setq empty-field nil)
2071 (goto-char (1+ beg-text))
2072 (insert title))))
2073
2074 ;; if empty field is a required field, complain
2075 (when (and empty-field
2076 (memq 'required-fields format)
2077 (assoc-string field-name req-field-list t))
2078 (setq error-field-name field-name)
2079 (error "Mandatory field `%s' is empty" field-name))
2080
2081 ;; unify case of field name
2082 (if (memq 'unify-case format)
2083 (let ((fname (car (assoc-string field-name
2084 default-field-list t))))
2085 (if fname
2086 (progn
2087 (delete-region beg-name end-name)
2088 (goto-char beg-name)
2089 (insert fname))
2090 ;; there are no rules we could follow
2091 (downcase-region beg-name end-name))))
2092
2093 ;; update point
2094 (goto-char end-field))))
2095
2096 ;; check whether all required fields are present
2097 (if (memq 'required-fields format)
2098 (let ((found 0) alt-list)
2099 (dolist (fname req-field-list)
2100 (cond ((nth 3 fname) ; t if field has alternative flag
2101 (push (car fname) alt-list)
2102 (if (member-ignore-case (car fname) field-list)
2103 (setq found (1+ found))))
2104 ((not (member-ignore-case (car fname) field-list))
2105 ;; If we use the crossref field, a required field
2106 ;; can have the OPT prefix. So if it was empty,
2107 ;; we have deleted by now. Nonetheless we can
2108 ;; move point on this empty field.
2109 (setq error-field-name (car fname))
2110 (error "Mandatory field `%s' is missing" (car fname)))))
2111 (if alt-list
2112 (cond ((= found 0)
2113 (if alt-fields
2114 (setq error-field-name (car (last alt-fields))))
2115 (error "Alternative mandatory field `%s' is missing"
2116 alt-list))
2117 ((> found 1)
2118 (if alt-fields
2119 (setq error-field-name (car (last alt-fields))))
2120 (error "Alternative fields `%s' are defined %s times"
2121 alt-list found))))))
2122
2123 ;; update comma after last field
2124 (if (memq 'last-comma format)
2125 (cond ((and bibtex-comma-after-last-field
2126 (not (looking-at ",")))
2127 (insert ","))
2128 ((and (not bibtex-comma-after-last-field)
2129 (looking-at ","))
2130 (delete-char 1))))
2131
2132 ;; update right entry delimiter
2133 (if (looking-at ",")
2134 (forward-char))
2135 (when (memq 'delimiters format)
2136 (skip-chars-forward " \t\n")
2137 (delete-char 1)
2138 (insert (bibtex-entry-right-delimiter)))
2139
2140 ;; realign and fill entry
2141 (if (memq 'realign format)
2142 (bibtex-fill-entry)))))
2143
2144 ;; Unwindform: move point to location where error occured if possible
2145 (if error-field-name
2146 (let (bounds)
2147 (when (save-excursion
2148 (bibtex-beginning-of-entry)
2149 (setq bounds
2150 (bibtex-search-forward-field
2151 ;; If we use the crossref field, a required field
2152 ;; can have the OPT prefix
2153 (concat "\\(OPT\\|ALT\\)?" error-field-name) t)))
2154 (goto-char (bibtex-start-of-text-in-field bounds))
2155 (bibtex-find-text)))))))
2156
2157 (defun bibtex-field-re-init (regexp-alist type)
2158 "Calculate optimized value for bibtex-regexp-TYPE-opt.
2159 This value is based on bibtex-regexp-TYPE-alist. TYPE is 'braces or 'strings.
2160 Return optimized value to be used by `bibtex-format-entry'."
2161 (setq regexp-alist
2162 (mapcar (lambda (e)
2163 (list (car e)
2164 (replace-regexp-in-string "[ \t\n]+" "[ \t\n]+" (nth 1 e))
2165 (nth 2 e))) ; nil for 'braces'.
2166 regexp-alist))
2167 (let (opt-list)
2168 ;; Loop over field names
2169 (dolist (field (delete-dups (apply 'append (mapcar 'car regexp-alist))))
2170 (let (rules)
2171 ;; Collect all matches we have for this field name
2172 (dolist (e regexp-alist)
2173 (if (assoc-string field (car e) t)
2174 (push (cons (nth 1 e) (nth 2 e)) rules)))
2175 (if (eq type 'braces)
2176 ;; concatenate all regexps to a single regexp
2177 (setq rules (concat "\\(?:" (mapconcat 'car rules "\\|") "\\)")))
2178 ;; create list of replacement rules.
2179 (push (cons field rules) opt-list)))
2180 opt-list))
2181
2182 \f
2183 (defun bibtex-autokey-abbrev (string len)
2184 "Return an abbreviation of STRING with at least LEN characters.
2185 If LEN is positive the abbreviation is terminated only after a consonant
2186 or at the word end. If LEN is negative the abbreviation is strictly
2187 enforced using abs (LEN) characters. If LEN is not a number, STRING
2188 is returned unchanged."
2189 (cond ((or (not (numberp len))
2190 (<= (length string) (abs len)))
2191 string)
2192 ((equal len 0)
2193 "")
2194 ((< len 0)
2195 (substring string 0 (abs len)))
2196 (t (let* ((case-fold-search t)
2197 (abort-char (string-match "[^aeiou]" string (1- len))))
2198 (if abort-char
2199 (substring string 0 (1+ abort-char))
2200 string)))))
2201
2202 (defun bibtex-autokey-get-field (field &optional change-list)
2203 "Get content of BibTeX field FIELD. Return empty string if not found.
2204 Optional arg CHANGE-LIST is a list of substitution patterns that is
2205 applied to the content of FIELD. It is an alist with pairs
2206 \(OLD-REGEXP . NEW-STRING\)."
2207 (let* ((bibtex-expand-strings bibtex-autokey-expand-strings)
2208 (content (bibtex-text-in-field field bibtex-autokey-use-crossref))
2209 case-fold-search)
2210 (unless content (setq content ""))
2211 (dolist (pattern change-list content)
2212 (setq content (replace-regexp-in-string (car pattern)
2213 (cdr pattern)
2214 content t)))))
2215
2216 (defun bibtex-autokey-get-names ()
2217 "Get contents of the name field of the current entry.
2218 Do some modifications based on `bibtex-autokey-name-change-strings'.
2219 Return the names as a concatenated string obeying `bibtex-autokey-names'
2220 and `bibtex-autokey-names-stretch'."
2221 (let ((names (bibtex-autokey-get-field "author\\|editor"
2222 bibtex-autokey-name-change-strings)))
2223 ;; Some entries do not have a name field.
2224 (if (string= "" names)
2225 names
2226 (let* ((case-fold-search t)
2227 (name-list (mapcar 'bibtex-autokey-demangle-name
2228 (split-string names "[ \t\n]+and[ \t\n]+")))
2229 additional-names)
2230 (unless (or (not (numberp bibtex-autokey-names))
2231 (<= (length name-list)
2232 (+ bibtex-autokey-names
2233 bibtex-autokey-names-stretch)))
2234 ;; Take `bibtex-autokey-names' elements from beginning of name-list
2235 (setq name-list (nreverse (nthcdr (- (length name-list)
2236 bibtex-autokey-names)
2237 (nreverse name-list)))
2238 additional-names bibtex-autokey-additional-names))
2239 (concat (mapconcat 'identity name-list
2240 bibtex-autokey-name-separator)
2241 additional-names)))))
2242
2243 (defun bibtex-autokey-demangle-name (fullname)
2244 "Get the last part from a well-formed FULLNAME and perform abbreviations."
2245 (let* (case-fold-search
2246 (name (cond ((string-match "\\([[:upper:]][^, ]*\\)[^,]*," fullname)
2247 ;; Name is of the form "von Last, First" or
2248 ;; "von Last, Jr, First"
2249 ;; --> Take the first capital part before the comma
2250 (match-string 1 fullname))
2251 ((string-match "\\([^, ]*\\)," fullname)
2252 ;; Strange name: we have a comma, but nothing capital
2253 ;; So we accept even lowercase names
2254 (match-string 1 fullname))
2255 ((string-match "\\(\\<[[:lower:]][^ ]* +\\)+\\([[:upper:]][^ ]*\\)"
2256 fullname)
2257 ;; name is of the form "First von Last", "von Last",
2258 ;; "First von von Last", or "d'Last"
2259 ;; --> take the first capital part after the "von" parts
2260 (match-string 2 fullname))
2261 ((string-match "\\([^ ]+\\) *\\'" fullname)
2262 ;; name is of the form "First Middle Last" or "Last"
2263 ;; --> take the last token
2264 (match-string 1 fullname))
2265 (t (error "Name `%s' is incorrectly formed" fullname)))))
2266 (funcall bibtex-autokey-name-case-convert-function
2267 (bibtex-autokey-abbrev name bibtex-autokey-name-length))))
2268
2269 (defun bibtex-autokey-get-year ()
2270 "Return year field contents as a string obeying `bibtex-autokey-year-length'."
2271 (let ((yearfield (bibtex-autokey-get-field "year")))
2272 (substring yearfield (max 0 (- (length yearfield)
2273 bibtex-autokey-year-length)))))
2274
2275 (defun bibtex-autokey-get-title ()
2276 "Get title field contents up to a terminator.
2277 Return the result as a string"
2278 (let ((case-fold-search t)
2279 (titlestring
2280 (bibtex-autokey-get-field "title"
2281 bibtex-autokey-titleword-change-strings)))
2282 ;; ignore everything past a terminator
2283 (if (string-match bibtex-autokey-title-terminators titlestring)
2284 (setq titlestring (substring titlestring 0 (match-beginning 0))))
2285 ;; gather words from titlestring into a list. Ignore
2286 ;; specific words and use only a specific amount of words.
2287 (let ((counter 0)
2288 titlewords titlewords-extra word)
2289 (while (and (or (not (numberp bibtex-autokey-titlewords))
2290 (< counter (+ bibtex-autokey-titlewords
2291 bibtex-autokey-titlewords-stretch)))
2292 (string-match "\\b\\w+" titlestring))
2293 (setq word (match-string 0 titlestring)
2294 titlestring (substring titlestring (match-end 0)))
2295 ;; Ignore words matched by one of the elements of
2296 ;; `bibtex-autokey-titleword-ignore'
2297 (unless (let ((lst bibtex-autokey-titleword-ignore))
2298 (while (and lst
2299 (not (string-match (concat "\\`\\(?:" (car lst)
2300 "\\)\\'") word)))
2301 (setq lst (cdr lst)))
2302 lst)
2303 (setq counter (1+ counter))
2304 (if (or (not (numberp bibtex-autokey-titlewords))
2305 (<= counter bibtex-autokey-titlewords))
2306 (push word titlewords)
2307 (push word titlewords-extra))))
2308 ;; Obey `bibtex-autokey-titlewords-stretch':
2309 ;; If by now we have processed all words in titlestring, we include
2310 ;; titlewords-extra in titlewords. Otherwise, we ignore titlewords-extra.
2311 (unless (string-match "\\b\\w+" titlestring)
2312 (setq titlewords (append titlewords-extra titlewords)))
2313 (mapconcat 'bibtex-autokey-demangle-title (nreverse titlewords)
2314 bibtex-autokey-titleword-separator))))
2315
2316 (defun bibtex-autokey-demangle-title (titleword)
2317 "Do some abbreviations on TITLEWORD.
2318 The rules are defined in `bibtex-autokey-titleword-abbrevs'
2319 and `bibtex-autokey-titleword-length'."
2320 (let ((case-fold-search t)
2321 (alist bibtex-autokey-titleword-abbrevs))
2322 (while (and alist
2323 (not (string-match (concat "\\`\\(?:" (caar alist) "\\)\\'")
2324 titleword)))
2325 (setq alist (cdr alist)))
2326 (if alist
2327 (cdar alist)
2328 (funcall bibtex-autokey-titleword-case-convert-function
2329 (bibtex-autokey-abbrev titleword bibtex-autokey-titleword-length)))))
2330
2331 (defun bibtex-generate-autokey ()
2332 "Generate automatically a key for a BibTeX entry.
2333 Use the author/editor, the year and the title field.
2334 The algorithm works as follows.
2335
2336 The name part:
2337 1. Use the author or editor field to generate the name part of the key.
2338 Expand BibTeX strings if `bibtex-autokey-expand-strings' is non-nil.
2339 2. Change the content of the name field according to
2340 `bibtex-autokey-name-change-strings' (see there for further detail).
2341 3. Use the first `bibtex-autokey-names' names in the name field. If there
2342 are up to `bibtex-autokey-names' + `bibtex-autokey-names-stretch' names,
2343 use all names.
2344 4. Use only the last names to form the name part. From these last names,
2345 take at least `bibtex-autokey-name-length' characters (truncate only
2346 after a consonant or at a word end).
2347 5. Convert all last names using the function
2348 `bibtex-autokey-name-case-convert-function'.
2349 6. Build the name part of the key by concatenating all abbreviated last
2350 names with the string `bibtex-autokey-name-separator' between any two.
2351 If there are more names in the name field than names used in the name
2352 part, append the string `bibtex-autokey-additional-names'.
2353
2354 The year part:
2355 1. Build the year part of the key by truncating the content of the year
2356 field to the rightmost `bibtex-autokey-year-length' digits (useful
2357 values are 2 and 4).
2358 2. If the year field (or any other field required to generate the key)
2359 is absent, but the entry has a valid crossref field and
2360 `bibtex-autokey-use-crossref' is non-nil, use the field of the
2361 crossreferenced entry instead.
2362
2363 The title part
2364 1. Change the content of the title field according to
2365 `bibtex-autokey-titleword-change-strings' (see there for further detail).
2366 2. Truncate the title before the first match of
2367 `bibtex-autokey-title-terminators' and delete those words which appear
2368 in `bibtex-autokey-titleword-ignore'. Build the title part using the
2369 first `bibtex-autokey-titlewords' words from this truncated title.
2370 If the truncated title ends after up to `bibtex-autokey-titlewords' +
2371 `bibtex-autokey-titlewords-stretch' words, use all words from the
2372 truncated title.
2373 3. For every title word that appears in `bibtex-autokey-titleword-abbrevs'
2374 use the corresponding abbreviation (see documentation of this variable
2375 for further detail).
2376 4. From every title word not generated by an abbreviation, take at least
2377 `bibtex-autokey-titleword-length' characters (truncate only after
2378 a consonant or at a word end).
2379 5. Convert all title words using the function
2380 `bibtex-autokey-titleword-case-convert-function'.
2381 6. Build the title part by concatenating all abbreviated title words with
2382 the string `bibtex-autokey-titleword-separator' between any two.
2383
2384 Concatenate the key:
2385 1. Concatenate `bibtex-autokey-prefix-string', the name part, the year
2386 part and the title part. If the name part and the year part are both
2387 non-empty insert `bibtex-autokey-name-year-separator' between the two.
2388 If the title part and the year (or name) part are non-empty, insert
2389 `bibtex-autokey-year-title-separator' between the two.
2390 2. If `bibtex-autokey-before-presentation-function' is non-nil, it must be
2391 a function taking one argument. Call this function with the generated
2392 key as the argument. Use the return value of this function (a string)
2393 as the key.
2394 3. If `bibtex-autokey-edit-before-use' is non-nil, present the key in the
2395 minibuffer to the user for editing. Insert the key given by the user."
2396 (let* ((names (bibtex-autokey-get-names))
2397 (year (bibtex-autokey-get-year))
2398 (title (bibtex-autokey-get-title))
2399 (autokey (concat bibtex-autokey-prefix-string
2400 names
2401 (unless (or (equal names "")
2402 (equal year ""))
2403 bibtex-autokey-name-year-separator)
2404 year
2405 (unless (or (and (equal names "")
2406 (equal year ""))
2407 (equal title ""))
2408 bibtex-autokey-year-title-separator)
2409 title)))
2410 (if bibtex-autokey-before-presentation-function
2411 (funcall bibtex-autokey-before-presentation-function autokey)
2412 autokey)))
2413
2414 \f
2415 (defun bibtex-global-key-alist ()
2416 "Return global key alist based on `bibtex-files'."
2417 (if bibtex-files
2418 (apply 'append
2419 (mapcar (lambda (buf)
2420 (with-current-buffer buf bibtex-reference-keys))
2421 (bibtex-initialize t)))
2422 bibtex-reference-keys))
2423
2424 (defun bibtex-read-key (prompt &optional key global)
2425 "Read BibTeX key from minibuffer using PROMPT and default KEY.
2426 If optional arg GLOBAL is non-nil, completion is based on the keys in
2427 `bibtex-reference-keys' of `bibtex-files',"
2428 (let (completion-ignore-case)
2429 (completing-read prompt (if global (bibtex-global-key-alist)
2430 bibtex-reference-keys)
2431 nil nil key 'bibtex-key-history)))
2432
2433 (defun bibtex-read-string-key (&optional key)
2434 "Read BibTeX string key from minibuffer using default KEY."
2435 (let ((completion-ignore-case t))
2436 (completing-read "String key: " bibtex-strings
2437 nil nil key 'bibtex-key-history)))
2438
2439 (defun bibtex-parse-keys (&optional abortable verbose)
2440 "Set `bibtex-reference-keys' to the keys used in the whole buffer.
2441 Find both entry keys and crossref entries. If ABORTABLE is non-nil abort
2442 on user input. If VERBOSE is non-nil give messages about progress.
2443 Return alist of keys if parsing was completed, `aborted' otherwise.
2444 If `bibtex-parse-keys-fast' is non-nil, use fast but simplified algorithm
2445 for parsing BibTeX keys. If parsing fails, try to set this variable to nil."
2446 (if (eq major-mode 'bibtex-mode)
2447 (let (ref-keys crossref-keys)
2448 (save-excursion
2449 (save-match-data
2450 (if verbose
2451 (bibtex-progress-message
2452 (concat (buffer-name) ": parsing reference keys")))
2453 (catch 'userkey
2454 (goto-char (point-min))
2455 (if bibtex-parse-keys-fast
2456 (let ((case-fold-search t)
2457 (re (concat bibtex-entry-head "\\|"
2458 ",[ \t\n]*crossref[ \t\n]*=[ \t\n]*"
2459 "\\(\"[^\"]*\"\\|{[^}]*}\\)[ \t\n]*[,})]")))
2460 (while (re-search-forward re nil t)
2461 (if (and abortable (input-pending-p))
2462 ;; user has aborted by typing a key: return `aborted'
2463 (throw 'userkey 'aborted))
2464 (cond ((match-end 3)
2465 ;; This is a crossref.
2466 (let ((key (buffer-substring-no-properties
2467 (1+ (match-beginning 3)) (1- (match-end 3)))))
2468 (unless (assoc key crossref-keys)
2469 (push (list key) crossref-keys))))
2470 ;; only keys of known entries
2471 ((assoc-string (bibtex-type-in-head)
2472 bibtex-entry-field-alist t)
2473 ;; This is an entry.
2474 (let ((key (bibtex-key-in-head)))
2475 (unless (assoc key ref-keys)
2476 (push (cons key t) ref-keys)))))))
2477
2478 (let (;; ignore @String entries because they are handled
2479 ;; separately by `bibtex-parse-strings'
2480 (bibtex-sort-ignore-string-entries t)
2481 bounds)
2482 (bibtex-map-entries
2483 (lambda (key beg end)
2484 (if (and abortable
2485 (input-pending-p))
2486 ;; user has aborted by typing a key: return `aborted'
2487 (throw 'userkey 'aborted))
2488 (if verbose (bibtex-progress-message))
2489 (unless (assoc key ref-keys)
2490 (push (cons key t) ref-keys))
2491 (if (and (setq bounds (bibtex-search-forward-field "crossref" end))
2492 (setq key (bibtex-text-in-field-bounds bounds t))
2493 (not (assoc key crossref-keys)))
2494 (push (list key) crossref-keys))))))
2495
2496 (dolist (key crossref-keys)
2497 (unless (assoc (car key) ref-keys) (push key ref-keys)))
2498 (if verbose
2499 (bibtex-progress-message 'done))
2500 ;; successful operation --> return `bibtex-reference-keys'
2501 (setq bibtex-reference-keys ref-keys)))))))
2502
2503 (defun bibtex-parse-strings (&optional add abortable)
2504 "Set `bibtex-strings' to the string definitions in the whole buffer.
2505 If ADD is non-nil add the new strings to `bibtex-strings' instead of
2506 simply resetting it. If ADD is an alist of strings, also add ADD to
2507 `bibtex-strings'. If ABORTABLE is non-nil abort on user input.
2508 Return alist of strings if parsing was completed, `aborted' otherwise."
2509 (save-excursion
2510 (save-match-data
2511 (goto-char (point-min))
2512 (let ((strings (if (and add
2513 (listp bibtex-strings))
2514 bibtex-strings))
2515 bounds key)
2516 (if (listp add)
2517 (dolist (string add)
2518 (unless (assoc-string (car string) strings t)
2519 (push string strings))))
2520 (catch 'userkey
2521 (while (setq bounds (bibtex-search-forward-string))
2522 (if (and abortable
2523 (input-pending-p))
2524 ;; user has aborted by typing a key --> return `aborted'
2525 (throw 'userkey 'aborted))
2526 (setq key (bibtex-reference-key-in-string bounds))
2527 (unless (assoc-string key strings t)
2528 (push (cons key (bibtex-text-in-string bounds t))
2529 strings))
2530 (goto-char (bibtex-end-of-text-in-string bounds)))
2531 ;; successful operation --> return `bibtex-strings'
2532 (setq bibtex-strings strings))))))
2533
2534 (defun bibtex-strings ()
2535 "Return `bibtex-strings'. Initialize this variable if necessary."
2536 (if (listp bibtex-strings) bibtex-strings
2537 (bibtex-parse-strings (bibtex-string-files-init))))
2538
2539 (defun bibtex-string-files-init ()
2540 "Return initialization for `bibtex-strings'.
2541 Use `bibtex-predefined-strings' and BibTeX files `bibtex-string-files'."
2542 (save-match-data
2543 (let ((dirlist (split-string (or bibtex-string-file-path default-directory)
2544 ":+"))
2545 (case-fold-search)
2546 string-files fullfilename compl bounds found)
2547 ;; collect absolute file names of valid string files
2548 (dolist (filename bibtex-string-files)
2549 (unless (string-match "\\.bib\\'" filename)
2550 (setq filename (concat filename ".bib")))
2551 ;; test filenames
2552 (if (file-name-absolute-p filename)
2553 (if (file-readable-p filename)
2554 (push filename string-files)
2555 (error "BibTeX strings file %s not found" filename))
2556 (dolist (dir dirlist)
2557 (when (file-readable-p
2558 (setq fullfilename (expand-file-name filename dir)))
2559 (push fullfilename string-files)
2560 (setq found t)))
2561 (unless found
2562 (error "File %s not in paths defined via bibtex-string-file-path"
2563 filename))))
2564 ;; parse string files
2565 (dolist (filename string-files)
2566 (with-temp-buffer
2567 (insert-file-contents filename)
2568 (goto-char (point-min))
2569 (while (setq bounds (bibtex-search-forward-string))
2570 (push (cons (bibtex-reference-key-in-string bounds)
2571 (bibtex-text-in-string bounds t))
2572 compl)
2573 (goto-char (bibtex-end-of-string bounds)))))
2574 (append bibtex-predefined-strings (nreverse compl)))))
2575
2576 (defun bibtex-parse-buffers-stealthily ()
2577 "Parse buffer in the background during idle time.
2578 Called by `run-with-idle-timer'. Whenever Emacs has been idle
2579 for `bibtex-parse-keys-timeout' seconds, parse all BibTeX buffers
2580 which have been modified after last parsing.
2581 Parsing initializes `bibtex-reference-keys' and `bibtex-strings'."
2582 (save-excursion
2583 (let ((buffers (buffer-list))
2584 (strings-init (bibtex-string-files-init)))
2585 (while (and buffers (not (input-pending-p)))
2586 (set-buffer (car buffers))
2587 (if (and (eq major-mode 'bibtex-mode)
2588 (not (eq (buffer-modified-tick)
2589 bibtex-buffer-last-parsed-tick)))
2590 (save-restriction
2591 (widen)
2592 ;; Output no progress messages in `bibtex-parse-keys'
2593 ;; because when in `y-or-n-p' that can hide the question.
2594 (if (and (listp (bibtex-parse-keys t))
2595 ;; update `bibtex-strings'
2596 (listp (bibtex-parse-strings strings-init t)))
2597
2598 ;; remember that parsing was successful
2599 (setq bibtex-buffer-last-parsed-tick (buffer-modified-tick)))))
2600 (setq buffers (cdr buffers))))))
2601
2602 ;;;###autoload
2603 (defun bibtex-initialize (&optional current force select)
2604 "(Re)Initialize BibTeX buffers.
2605 Visit the BibTeX files defined by `bibtex-files' and return a list
2606 of corresponding buffers.
2607 Initialize in these buffers `bibtex-reference-keys' if not yet set.
2608 List of BibTeX buffers includes current buffer if CURRENT is non-nil.
2609 If FORCE is non-nil, (re)initialize `bibtex-reference-keys' even if
2610 already set. If SELECT is non-nil interactively select a BibTeX buffer.
2611 When called interactively, FORCE is t, CURRENT is t if current buffer uses
2612 `bibtex-mode', and SELECT is t if current buffer does not use `bibtex-mode',"
2613 (interactive (list (eq major-mode 'bibtex-mode) t
2614 (not (eq major-mode 'bibtex-mode))))
2615 (let ((file-path (split-string (or bibtex-file-path default-directory) ":+"))
2616 file-list dir-list buffer-list)
2617 ;; generate list of BibTeX files
2618 (dolist (file bibtex-files)
2619 (cond ((eq file 'bibtex-file-path)
2620 (setq dir-list (append dir-list file-path)))
2621 ((file-accessible-directory-p file)
2622 (push file dir-list))
2623 ((progn (unless (string-match "\\.bib\\'" file)
2624 (setq file (concat file ".bib")))
2625 (file-name-absolute-p file))
2626 (push file file-list))
2627 (t
2628 (let (expanded-file-name found)
2629 (dolist (dir file-path)
2630 (when (file-readable-p
2631 (setq expanded-file-name (expand-file-name file dir)))
2632 (push expanded-file-name file-list)
2633 (setq found t)))
2634 (unless found
2635 (error "File `%s' not in paths defined via bibtex-file-path"
2636 file))))))
2637 (dolist (file file-list)
2638 (unless (file-readable-p file)
2639 (error "BibTeX file `%s' not found" file)))
2640 ;; expand dir-list
2641 (dolist (dir dir-list)
2642 (setq file-list
2643 (append file-list (directory-files dir t "\\.bib\\'" t))))
2644 (delete-dups file-list)
2645 ;; visit files in FILE-LIST
2646 (dolist (file file-list)
2647 (if (file-readable-p file)
2648 (push (find-file-noselect file) buffer-list)))
2649 ;; include current buffer iff we want it
2650 (cond ((and current (not (memq (current-buffer) buffer-list)))
2651 (push (current-buffer) buffer-list))
2652 ((and (not current) (memq (current-buffer) buffer-list))
2653 (setq buffer-list (delq (current-buffer) buffer-list))))
2654 ;; parse keys
2655 (dolist (buffer buffer-list)
2656 (with-current-buffer buffer
2657 (if (or force (nlistp bibtex-reference-keys))
2658 (bibtex-parse-keys))))
2659 ;; select BibTeX buffer
2660 (if select
2661 (if buffer-list
2662 (switch-to-buffer
2663 (completing-read "Switch to BibTeX buffer: "
2664 (mapcar 'buffer-name buffer-list)
2665 nil t
2666 (if current (buffer-name (current-buffer)))))
2667 (message "No BibTeX buffers defined")))
2668 buffer-list))
2669
2670 (defun bibtex-complete-internal (completions)
2671 "Complete word fragment before point to longest prefix of COMPLETIONS.
2672 COMPLETIONS is an alist of strings. If point is not after the part
2673 of a word, all strings are listed. Return completion."
2674 ;; Return value is used by cleanup functions.
2675 ;; Code inspired by `lisp-complete-symbol'.
2676 (let* ((case-fold-search t)
2677 (beg (save-excursion
2678 (re-search-backward "[ \t{\"]")
2679 (forward-char)
2680 (point)))
2681 (end (point))
2682 (pattern (buffer-substring-no-properties beg end))
2683 (completion (try-completion pattern completions)))
2684 (cond ((not completion)
2685 (error "Can't find completion for `%s'" pattern))
2686 ((eq completion t)
2687 pattern)
2688 ((not (string= pattern completion))
2689 (delete-region beg end)
2690 (insert completion)
2691 ;; Don't leave around a completions buffer that's out of date.
2692 (let ((win (get-buffer-window "*Completions*" 0)))
2693 (if win (with-selected-window win (bury-buffer))))
2694 completion)
2695 (t
2696 (let ((minibuf-is-in-use
2697 (eq (minibuffer-window) (selected-window))))
2698 (unless minibuf-is-in-use (message "Making completion list..."))
2699 (with-output-to-temp-buffer "*Completions*"
2700 (display-completion-list
2701 (sort (all-completions pattern completions) 'string<) pattern))
2702 (unless minibuf-is-in-use
2703 (message "Making completion list...done")))
2704 nil))))
2705
2706 (defun bibtex-complete-string-cleanup (str compl)
2707 "Cleanup after inserting string STR.
2708 Remove enclosing field delimiters for STR. Display message with
2709 expansion of STR using expansion list COMPL."
2710 ;; point is at position inside field where completion was requested
2711 (save-excursion
2712 (let ((abbr (cdr (if (stringp str)
2713 (assoc-string str compl t)))))
2714 (if abbr (message "Abbreviation for `%s'" abbr))
2715 (bibtex-remove-delimiters))))
2716
2717 (defun bibtex-complete-crossref-cleanup (key)
2718 "Display summary message on entry KEY after completion of a crossref key.
2719 Use `bibtex-summary-function' to generate summary."
2720 (save-excursion
2721 (if (and (stringp key)
2722 (bibtex-search-entry key t))
2723 (message "Ref: %s" (funcall bibtex-summary-function)))))
2724
2725 (defun bibtex-copy-summary-as-kill (&optional arg)
2726 "Push summery of current BibTeX entry to kill ring.
2727 Use `bibtex-summary-function' to generate summary.
2728 If prefix ARG is non-nil push BibTeX entry's URL to kill ring
2729 that is generated by calling `bibtex-url'."
2730 (interactive "P")
2731 (if arg (let ((url (bibtex-url nil t)))
2732 (if url (kill-new (message "%s" url))
2733 (message "No URL known")))
2734 (save-excursion
2735 (bibtex-beginning-of-entry)
2736 (if (looking-at bibtex-entry-maybe-empty-head)
2737 (kill-new (message "%s" (funcall bibtex-summary-function)))
2738 (error "No entry found")))))
2739
2740 (defun bibtex-summary ()
2741 "Return summary of current BibTeX entry.
2742 Used as default value of `bibtex-summary-function'."
2743 ;; It would be neat to make this function customizable. How?
2744 (if (looking-at bibtex-entry-maybe-empty-head)
2745 (let* ((bibtex-autokey-name-case-convert-function 'identity)
2746 (bibtex-autokey-name-length 'infty)
2747 (bibtex-autokey-names 1)
2748 (bibtex-autokey-names-stretch 0)
2749 (bibtex-autokey-name-separator " ")
2750 (bibtex-autokey-additional-names " etal")
2751 (names (bibtex-autokey-get-names))
2752 (bibtex-autokey-year-length 4)
2753 (year (bibtex-autokey-get-year))
2754 (bibtex-autokey-titlewords 5)
2755 (bibtex-autokey-titlewords-stretch 2)
2756 (bibtex-autokey-titleword-case-convert-function 'identity)
2757 (bibtex-autokey-titleword-length 5)
2758 (bibtex-autokey-titleword-separator " ")
2759 (title (bibtex-autokey-get-title))
2760 (journal (bibtex-autokey-get-field
2761 "journal" bibtex-autokey-transcriptions))
2762 (volume (bibtex-autokey-get-field "volume"))
2763 (pages (bibtex-autokey-get-field "pages" '(("-.*\\'" . "")))))
2764 (mapconcat (lambda (arg)
2765 (if (not (string= "" (cdr arg)))
2766 (concat (car arg) (cdr arg))))
2767 `((" " . ,names) (" " . ,year) (": " . ,title)
2768 (", " . ,journal) (" " . ,volume) (":" . ,pages))
2769 ""))
2770 (error "Entry not found")))
2771
2772 (defun bibtex-pop (arg direction)
2773 "Fill current field from the ARGth same field's text in DIRECTION.
2774 Generic function used by `bibtex-pop-previous' and `bibtex-pop-next'."
2775 ;; parse current field
2776 (let* ((bounds (bibtex-enclosing-field t))
2777 (start-old-field (bibtex-start-of-field bounds))
2778 (start-old-text (bibtex-start-of-text-in-field bounds))
2779 (end-old-text (bibtex-end-of-text-in-field bounds))
2780 (field-name (bibtex-name-in-field bounds t))
2781 failure)
2782 (save-excursion
2783 ;; if executed several times in a row, start each search where
2784 ;; the last one was finished
2785 (cond ((eq last-command 'bibtex-pop)
2786 (goto-char (if (eq direction 'previous)
2787 bibtex-pop-previous-search-point
2788 bibtex-pop-next-search-point)))
2789 ((eq direction 'previous)
2790 (bibtex-beginning-of-entry))
2791 (t (bibtex-end-of-entry)))
2792 ;; Search for arg'th previous/next similar field
2793 (while (and (not failure)
2794 (>= (setq arg (1- arg)) 0))
2795 ;; The search of BibTeX fields is not bounded by entry boundaries
2796 (if (eq direction 'previous)
2797 (if (setq bounds (bibtex-search-backward-field field-name))
2798 (goto-char (bibtex-start-of-field bounds))
2799 (setq failure t))
2800 (if (setq bounds (bibtex-search-forward-field field-name))
2801 (goto-char (bibtex-end-of-field bounds))
2802 (setq failure t))))
2803 (if failure
2804 (error "No %s matching BibTeX field"
2805 (if (eq direction 'previous) "previous" "next"))
2806 ;; Found a matching field. Remember boundaries.
2807 (let ((new-text (bibtex-text-in-field-bounds bounds))
2808 (nbeg (copy-marker (bibtex-start-of-field bounds)))
2809 (nend (copy-marker (bibtex-end-of-field bounds))))
2810 (bibtex-flash-head "From: ")
2811 ;; Go back to where we started, delete old text, and pop new.
2812 (goto-char end-old-text)
2813 (delete-region start-old-text end-old-text)
2814 (if (= nbeg start-old-field)
2815 (insert (bibtex-field-left-delimiter)
2816 (bibtex-field-right-delimiter))
2817 (insert new-text))
2818 (setq bibtex-pop-previous-search-point (marker-position nbeg)
2819 bibtex-pop-next-search-point (marker-position nend))))))
2820 (bibtex-find-text nil nil nil t)
2821 (setq this-command 'bibtex-pop))
2822
2823 (defun bibtex-beginning-of-field ()
2824 "Move point backward to beginning of field.
2825 This function uses a simple, fast algorithm assuming that the field
2826 begins at the beginning of a line. We use this function for font-locking."
2827 (let ((field-reg (concat "^[ \t]*" bibtex-field-name "[ \t]*=")))
2828 (beginning-of-line)
2829 (unless (looking-at field-reg)
2830 (re-search-backward field-reg nil t))))
2831
2832 (defun bibtex-font-lock-url (bound &optional no-button)
2833 "Font-lock for URLs. BOUND limits the search.
2834 If NO-BUTTON is non-nil do not generate buttons."
2835 (let ((case-fold-search t)
2836 (pnt (point))
2837 name bounds start end found)
2838 (bibtex-beginning-of-field)
2839 (while (and (not found)
2840 (<= (point) bound)
2841 (prog1 (re-search-forward bibtex-font-lock-url-regexp bound t)
2842 (setq name (match-string-no-properties 1)))
2843 (setq bounds (bibtex-parse-field-text))
2844 (progn
2845 (setq start (car bounds) end (nth 1 bounds))
2846 ;; Always ignore field delimiters
2847 (if (memq (char-before end) '(?\} ?\"))
2848 (setq end (1- end)))
2849 (if (memq (char-after start) '(?\{ ?\"))
2850 (setq start (1+ start)))
2851 (if (< start pnt) (setq start (min pnt end)))
2852 (<= start bound)))
2853 (if (<= pnt start)
2854 (let ((lst bibtex-generate-url-list) url)
2855 (while (and (not found) (setq url (car (pop lst))))
2856 (goto-char start)
2857 (setq found (and (bibtex-string= name (car url))
2858 (re-search-forward (cdr url) end t))))))
2859 (unless found (goto-char end)))
2860 (if (and found (not no-button))
2861 (bibtex-button (match-beginning 0) (match-end 0)
2862 'bibtex-url (match-beginning 0)))
2863 found))
2864
2865 (defun bibtex-font-lock-crossref (bound)
2866 "Font-lock for crossref fields. BOUND limits the search."
2867 (let ((case-fold-search t)
2868 (pnt (point))
2869 (crossref-reg (concat "^[ \t]*crossref[ \t]*=[ \t\n]*"
2870 "\\(\"[^\"]*\"\\|{[^}]*}\\)[ \t\n]*[,})]"))
2871 start end found)
2872 (bibtex-beginning-of-field)
2873 (while (and (not found)
2874 (re-search-forward crossref-reg bound t))
2875 (setq start (1+ (match-beginning 1))
2876 end (1- (match-end 1))
2877 found (>= start pnt)))
2878 (if found (bibtex-button start end 'bibtex-search-crossref
2879 (buffer-substring-no-properties start end)
2880 start t))
2881 found))
2882
2883 (defun bibtex-font-lock-cite (matcher bound)
2884 "Font-lock for cited keys.
2885 MATCHER identifies the cited key, see `bibtex-cite-matcher-alist'.
2886 BOUND limits the search."
2887 (let (case-fold-search)
2888 (if (re-search-forward (car matcher) bound t)
2889 (let ((start (match-beginning (cdr matcher)))
2890 (end (match-end (cdr matcher))))
2891 (bibtex-button start end 'bibtex-search-crossref
2892 (buffer-substring-no-properties start end)
2893 start t t)
2894 t))))
2895
2896 (defun bibtex-button-action (button)
2897 "Call BUTTON's BibTeX function."
2898 (apply (button-get button 'bibtex-function)
2899 (button-get button 'bibtex-args)))
2900
2901 (define-button-type 'bibtex-url
2902 'action 'bibtex-button-action
2903 'bibtex-function 'bibtex-url
2904 'help-echo (purecopy "mouse-2, RET: follow URL"))
2905
2906 (define-button-type 'bibtex-search-crossref
2907 'action 'bibtex-button-action
2908 'bibtex-function 'bibtex-search-crossref
2909 'help-echo (purecopy "mouse-2, RET: follow crossref"))
2910
2911 (defun bibtex-button (beg end type &rest args)
2912 "Make a BibTeX button from BEG to END of type TYPE in the current buffer."
2913 (make-text-button beg end 'type type 'bibtex-args args))
2914
2915 \f
2916 ;; Interactive Functions:
2917
2918 ;;;###autoload
2919 (defun bibtex-mode ()
2920 "Major mode for editing BibTeX files.
2921
2922 General information on working with BibTeX mode:
2923
2924 Use commands such as \\[bibtex-Book] to get a template for a specific entry.
2925 Then fill in all desired fields using \\[bibtex-next-field] to jump from field
2926 to field. After having filled in all desired fields in the entry, clean the
2927 new entry with the command \\[bibtex-clean-entry].
2928
2929 Some features of BibTeX mode are available only by setting the variable
2930 `bibtex-maintain-sorted-entries' to non-nil. However, then BibTeX mode
2931 works only with buffers containing valid (syntactical correct) and sorted
2932 entries. This is usually the case, if you have created a buffer completely
2933 with BibTeX mode and finished every new entry with \\[bibtex-clean-entry].
2934
2935 For third party BibTeX files, call the command \\[bibtex-convert-alien]
2936 to fully take advantage of all features of BibTeX mode.
2937
2938
2939 Special information:
2940
2941 A command such as \\[bibtex-Book] outlines the fields for a BibTeX book entry.
2942
2943 The names of optional fields start with the string OPT, and are thus ignored
2944 by BibTeX. The names of alternative fields from which only one is required
2945 start with the string ALT. The OPT or ALT string may be removed from
2946 the name of a field with \\[bibtex-remove-OPT-or-ALT].
2947 \\[bibtex-make-field] inserts a new field after the current one.
2948 \\[bibtex-kill-field] kills the current field entirely.
2949 \\[bibtex-yank] yanks the last recently killed field after the current field.
2950 \\[bibtex-remove-delimiters] removes the double-quotes or braces around the text of the current field.
2951 \\[bibtex-empty-field] replaces the text of the current field with the default \"\" or {}.
2952 \\[bibtex-find-text] moves point to the end of the current field.
2953 \\[bibtex-complete] completes word fragment before point according to context.
2954
2955 The command \\[bibtex-clean-entry] cleans the current entry, i.e. it removes OPT/ALT
2956 from the names of all non-empty optional or alternative fields, checks that
2957 no required fields are empty, and does some formatting dependent on the value
2958 of `bibtex-entry-format'. Furthermore, it can automatically generate a key
2959 for the BibTeX entry, see `bibtex-generate-autokey'.
2960 Note: some functions in BibTeX mode depend on entries being in a special
2961 format (all fields beginning on separate lines), so it is usually a bad
2962 idea to remove `realign' from `bibtex-entry-format'.
2963
2964 BibTeX mode supports Imenu and hideshow minor mode (`hs-minor-mode').
2965
2966 ----------------------------------------------------------
2967 Entry to BibTeX mode calls the value of `bibtex-mode-hook'
2968 if that value is non-nil.
2969
2970 \\{bibtex-mode-map}"
2971 (interactive)
2972 (kill-all-local-variables)
2973 (use-local-map bibtex-mode-map)
2974 (setq major-mode 'bibtex-mode)
2975 (setq mode-name "BibTeX")
2976 (set-syntax-table bibtex-mode-syntax-table)
2977 (make-local-variable 'bibtex-buffer-last-parsed-tick)
2978 ;; Install stealthy parse function if not already installed
2979 (unless bibtex-parse-idle-timer
2980 (setq bibtex-parse-idle-timer (run-with-idle-timer
2981 bibtex-parse-keys-timeout t
2982 'bibtex-parse-buffers-stealthily)))
2983 (set (make-local-variable 'paragraph-start) "[ \f\n\t]*$")
2984 (set (make-local-variable 'comment-start) bibtex-comment-start)
2985 (set (make-local-variable 'comment-start-skip)
2986 (concat (regexp-quote bibtex-comment-start) "\\>[ \t]*"))
2987 (set (make-local-variable 'comment-column) 0)
2988 (set (make-local-variable 'defun-prompt-regexp) "^[ \t]*@[[:alnum:]]+[ \t]*")
2989 (set (make-local-variable 'outline-regexp) "[ \t]*@")
2990 (set (make-local-variable 'fill-paragraph-function) 'bibtex-fill-field)
2991 (set (make-local-variable 'fill-prefix) (make-string (+ bibtex-entry-offset
2992 bibtex-contline-indentation)
2993 ?\s))
2994 (set (make-local-variable 'font-lock-defaults)
2995 '(bibtex-font-lock-keywords
2996 nil t ((?$ . "\"")
2997 ;; Mathematical expressions should be fontified as strings
2998 (?\" . ".")
2999 ;; Quotes are field delimiters and quote-delimited
3000 ;; entries should be fontified in the same way as
3001 ;; brace-delimited ones
3002 )
3003 nil
3004 (font-lock-syntactic-keywords . bibtex-font-lock-syntactic-keywords)
3005 (font-lock-extra-managed-props . (category))
3006 (font-lock-mark-block-function
3007 . (lambda ()
3008 (set-mark (bibtex-end-of-entry))
3009 (bibtex-beginning-of-entry)))))
3010 (setq imenu-generic-expression
3011 (list (list nil bibtex-entry-head bibtex-key-in-head))
3012 imenu-case-fold-search t)
3013 (make-local-variable 'choose-completion-string-functions)
3014 ;; XEmacs needs `easy-menu-add', Emacs does not care
3015 (easy-menu-add bibtex-edit-menu)
3016 (easy-menu-add bibtex-entry-menu)
3017 (run-mode-hooks 'bibtex-mode-hook))
3018
3019 (defun bibtex-field-list (entry-type)
3020 "Return list of allowed fields for entry ENTRY-TYPE.
3021 More specifically, the return value is a cons pair (REQUIRED . OPTIONAL),
3022 where REQUIRED and OPTIONAL are lists of the required and optional field
3023 names for ENTRY-TYPE according to `bibtex-entry-field-alist',
3024 `bibtex-include-OPTkey', `bibtex-include-OPTcrossref',
3025 and `bibtex-user-optional-fields'."
3026 (let ((e (assoc-string entry-type bibtex-entry-field-alist t))
3027 required optional)
3028 (unless e
3029 (error "Fields for BibTeX entry type %s not defined" entry-type))
3030 (if (and (member-ignore-case entry-type bibtex-include-OPTcrossref)
3031 (nth 2 e))
3032 (setq required (nth 0 (nth 2 e))
3033 optional (nth 1 (nth 2 e)))
3034 (setq required (nth 0 (nth 1 e))
3035 optional (nth 1 (nth 1 e))))
3036 (if bibtex-include-OPTkey
3037 (push (list "key"
3038 "Used for reference key creation if author and editor fields are missing"
3039 (if (or (stringp bibtex-include-OPTkey)
3040 (functionp bibtex-include-OPTkey))
3041 bibtex-include-OPTkey))
3042 optional))
3043 (if (member-ignore-case entry-type bibtex-include-OPTcrossref)
3044 (push '("crossref" "Reference key of the cross-referenced entry")
3045 optional))
3046 (setq optional (append optional bibtex-user-optional-fields))
3047 (cons required optional)))
3048
3049 (defun bibtex-entry (entry-type)
3050 "Insert a new BibTeX entry of type ENTRY-TYPE.
3051 After insertion call the value of `bibtex-add-entry-hook' if that value
3052 is non-nil."
3053 (interactive
3054 (let ((completion-ignore-case t))
3055 (list (completing-read "Entry Type: " bibtex-entry-field-alist
3056 nil t nil 'bibtex-entry-type-history))))
3057 (let ((key (if bibtex-maintain-sorted-entries
3058 (bibtex-read-key (format "%s key: " entry-type))))
3059 (field-list (bibtex-field-list entry-type)))
3060 (unless (bibtex-prepare-new-entry (list key nil entry-type))
3061 (error "Entry with key `%s' already exists" key))
3062 (indent-to-column bibtex-entry-offset)
3063 (insert "@" entry-type (bibtex-entry-left-delimiter))
3064 (if key (insert key))
3065 (save-excursion
3066 (mapc 'bibtex-make-field (car field-list))
3067 (mapc 'bibtex-make-optional-field (cdr field-list))
3068 (if bibtex-comma-after-last-field
3069 (insert ","))
3070 (insert "\n")
3071 (indent-to-column bibtex-entry-offset)
3072 (insert (bibtex-entry-right-delimiter) "\n\n"))
3073 (bibtex-next-field t)
3074 (if (member-ignore-case entry-type bibtex-autofill-types)
3075 (bibtex-autofill-entry))
3076 (run-hooks 'bibtex-add-entry-hook)))
3077
3078 (defun bibtex-entry-update (&optional entry-type)
3079 "Update an existing BibTeX entry.
3080 In the BibTeX entry at point, make new fields for those items that may occur
3081 according to `bibtex-field-list', but are not yet present.
3082 Also, add field delimiters to numerical fields if they are not present.
3083 If ENTRY-TYPE is non-nil, change first the entry type to ENTRY-TYPE.
3084 When called interactively with a prefix arg, query for a value of ENTRY-TYPE."
3085 (interactive
3086 (list (if current-prefix-arg
3087 (let ((completion-ignore-case t))
3088 (completing-read "New entry type: " bibtex-entry-field-alist
3089 nil t nil 'bibtex-entry-type-history)))))
3090 (save-excursion
3091 (bibtex-beginning-of-entry)
3092 (when (looking-at bibtex-entry-maybe-empty-head)
3093 (goto-char (match-end 0))
3094 (if entry-type
3095 (save-excursion
3096 (replace-match (concat "@" entry-type) nil nil nil 1))
3097 (setq entry-type (bibtex-type-in-head)))
3098 (let* ((field-list (bibtex-field-list entry-type))
3099 (required (copy-tree (car field-list)))
3100 (optional (copy-tree (cdr field-list)))
3101 bounds)
3102 (while (setq bounds (bibtex-parse-field))
3103 (let ((fname (bibtex-name-in-field bounds t))
3104 (end (copy-marker (bibtex-end-of-field bounds) t)))
3105 (setq required (delete (assoc-string fname required t) required)
3106 optional (delete (assoc-string fname optional t) optional))
3107 (when (string-match "\\`[0-9]+\\'"
3108 (bibtex-text-in-field-bounds bounds))
3109 (goto-char (bibtex-end-of-text-in-field bounds))
3110 (insert (bibtex-field-right-delimiter))
3111 (goto-char (bibtex-start-of-text-in-field bounds))
3112 (insert (bibtex-field-left-delimiter)))
3113 (goto-char end)))
3114 (skip-chars-backward " \t\n")
3115 (dolist (field required) (bibtex-make-field field))
3116 (dolist (field optional) (bibtex-make-optional-field field))))))
3117
3118 (defun bibtex-parse-entry (&optional content)
3119 "Parse entry at point, return an alist.
3120 The alist elements have the form (FIELD . TEXT), where FIELD can also be
3121 the special strings \"=type=\" and \"=key=\". For the FIELD \"=key=\"
3122 TEXT may be nil. Remove \"OPT\" and \"ALT\" from FIELD.
3123 Move point to the end of the last field.
3124 If optional arg CONTENT is non-nil extract content of text fields."
3125 (let (alist bounds)
3126 (when (looking-at bibtex-entry-maybe-empty-head)
3127 (push (cons "=type=" (bibtex-type-in-head)) alist)
3128 (push (cons "=key=" (bibtex-key-in-head)) alist)
3129 (goto-char (match-end 0))
3130 (while (setq bounds (bibtex-parse-field))
3131 (push (cons (bibtex-name-in-field bounds t)
3132 (bibtex-text-in-field-bounds bounds content))
3133 alist)
3134 (goto-char (bibtex-end-of-field bounds))))
3135 alist))
3136
3137 (defun bibtex-autofill-entry ()
3138 "Try to fill fields of current BibTeX entry based on neighboring entries.
3139 The current entry must have a key. Determine the neighboring entry
3140 \(previouse or next\) whose key is more similar to the key of the current
3141 entry. For all empty fields of the current entry insert the corresponding
3142 field contents of the neighboring entry. Finally try to update the text
3143 based on the difference between the keys of the neighboring and the current
3144 entry (for example, the year parts of the keys)."
3145 (interactive)
3146 (bibtex-beginning-of-entry)
3147 (when (looking-at bibtex-entry-head)
3148 (let ((type (bibtex-type-in-head))
3149 (key (bibtex-key-in-head))
3150 (key-end (match-end bibtex-key-in-head))
3151 (case-fold-search t)
3152 (bibtex-sort-ignore-string-entries t)
3153 tmp other-key other bounds)
3154 ;; The fields we want to change start right after the key.
3155 (goto-char key-end)
3156 ;; First see whether to use the previous or the next entry
3157 ;; for "inspiration".
3158 (save-excursion
3159 (goto-char (1- (match-beginning 0)))
3160 (bibtex-beginning-of-entry)
3161 (if (and (looking-at bibtex-entry-head)
3162 (bibtex-string= type (bibtex-type-in-head))
3163 ;; In case we found ourselves :-(
3164 (not (equal key (setq tmp (bibtex-key-in-head)))))
3165 (setq other-key tmp
3166 other (point))))
3167 (save-excursion
3168 (bibtex-end-of-entry)
3169 (bibtex-skip-to-valid-entry)
3170 (if (and (looking-at bibtex-entry-head)
3171 (bibtex-string= type (bibtex-type-in-head))
3172 ;; In case we found ourselves :-(
3173 (not (equal key (setq tmp (bibtex-key-in-head))))
3174 (or (not other-key)
3175 ;; Check which is the best match.
3176 (< (length (try-completion "" (list key other-key)))
3177 (length (try-completion "" (list key tmp))))))
3178 (setq other-key tmp
3179 other (point))))
3180 ;; Then fill the new entry's fields with the chosen other entry.
3181 (when other
3182 (setq other (save-excursion (goto-char other) (bibtex-parse-entry)))
3183 (setq key-end (point)) ;In case parse-entry changed the buffer.
3184 (while (setq bounds (bibtex-parse-field))
3185 (let ((text (assoc-string (bibtex-name-in-field bounds t)
3186 other t)))
3187 (if (not (and text
3188 (equal "" (bibtex-text-in-field-bounds bounds t))))
3189 (goto-char (bibtex-end-of-field bounds))
3190 (goto-char (bibtex-start-of-text-in-field bounds))
3191 (delete-region (point) (bibtex-end-of-text-in-field bounds))
3192 (insert (cdr text)))))
3193 ;; Finally try to update the text based on the difference between
3194 ;; the two keys.
3195 (let* ((prefix (try-completion "" (list key other-key)))
3196 ;; If the keys are foo91 and foo92, don't replace 1 for 2
3197 ;; but 91 for 92 instead.
3198 (_ (if (string-match "[0-9]+\\'" prefix)
3199 (setq prefix (substring prefix 0 (match-beginning 0)))))
3200 (suffix (substring key (length prefix)))
3201 (other-suffix (substring other-key (length prefix))))
3202 (while (re-search-backward (regexp-quote other-suffix) key-end 'move)
3203 (replace-match suffix)))))))
3204
3205 (defun bibtex-print-help-message (&optional field comma)
3206 "Print helpful information about current FIELD in current BibTeX entry.
3207 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3208 interactive calls."
3209 (interactive (list nil t))
3210 (unless field (setq field (car (bibtex-find-text-internal nil nil comma))))
3211 (if (string-match "@" field)
3212 (cond ((bibtex-string= field "@string")
3213 (message "String definition"))
3214 ((bibtex-string= field "@preamble")
3215 (message "Preamble definition"))
3216 (t (message "Entry key")))
3217 (let* ((case-fold-search t)
3218 (type (save-excursion
3219 (bibtex-beginning-of-entry)
3220 (looking-at bibtex-entry-maybe-empty-head)
3221 (bibtex-type-in-head)))
3222 (field-list (bibtex-field-list type))
3223 (comment (assoc-string field (append (car field-list)
3224 (cdr field-list)) t)))
3225 (if comment (message "%s" (nth 1 comment))
3226 (message "No comment available")))))
3227
3228 (defun bibtex-make-field (field &optional move interactive nodelim)
3229 "Make a field named FIELD in current BibTeX entry.
3230 FIELD is either a string or a list of the form
3231 \(FIELD-NAME COMMENT-STRING INIT ALTERNATIVE-FLAG) as in
3232 `bibtex-entry-field-alist'.
3233 If MOVE is non-nil, move point past the present field before making
3234 the new field. If INTERACTIVE is non-nil, move point to the end of
3235 the new field. Otherwise move point past the new field.
3236 MOVE and INTERACTIVE are t when called interactively.
3237 INIT is surrounded by field delimiters, unless NODELIM is non-nil."
3238 (interactive
3239 (list (let ((completion-ignore-case t)
3240 (field-list (bibtex-field-list
3241 (save-excursion
3242 (bibtex-beginning-of-entry)
3243 (looking-at bibtex-any-entry-maybe-empty-head)
3244 (bibtex-type-in-head)))))
3245 (completing-read "BibTeX field name: "
3246 (append (car field-list) (cdr field-list))
3247 nil nil nil bibtex-field-history))
3248 t t))
3249 (unless (consp field)
3250 (setq field (list field)))
3251 (when move
3252 (bibtex-find-text)
3253 (if (looking-at "[}\"]")
3254 (forward-char)))
3255 (insert ",\n")
3256 (indent-to-column (+ bibtex-entry-offset bibtex-field-indentation))
3257 (if (nth 3 field) (insert "ALT"))
3258 (insert (car field) " ")
3259 (if bibtex-align-at-equal-sign
3260 (indent-to-column (+ bibtex-entry-offset
3261 (- bibtex-text-indentation 2))))
3262 (insert "= ")
3263 (unless bibtex-align-at-equal-sign
3264 (indent-to-column (+ bibtex-entry-offset
3265 bibtex-text-indentation)))
3266 (let ((init (nth 2 field)))
3267 (if (not init) (setq init "")
3268 (if (functionp init) (setq init (funcall init)))
3269 (unless (stringp init) (error "`%s' is not a string" init)))
3270 ;; NODELIM is required by `bibtex-insert-kill'
3271 (if nodelim (insert init)
3272 (insert (bibtex-field-left-delimiter) init
3273 (bibtex-field-right-delimiter))))
3274 (when interactive
3275 ;; (bibtex-find-text nil nil bibtex-help-message)
3276 (if (memq (preceding-char) '(?} ?\")) (forward-char -1))
3277 (if bibtex-help-message (bibtex-print-help-message (car field)))))
3278
3279 (defun bibtex-beginning-of-entry ()
3280 "Move to beginning of BibTeX entry (beginning of line).
3281 If inside an entry, move to the beginning of it, otherwise move to the
3282 beginning of the previous entry. If point is ahead of all BibTeX entries
3283 move point to the beginning of buffer. Return the new location of point."
3284 (interactive)
3285 (skip-chars-forward " \t")
3286 (if (looking-at "@")
3287 (forward-char))
3288 (re-search-backward "^[ \t]*@" nil 'move)
3289 (point))
3290
3291 (defun bibtex-end-of-entry ()
3292 "Move to end of BibTeX entry (past the closing brace).
3293 If inside an entry, move to the end of it, otherwise move to the end
3294 of the previous entry. Do not move if ahead of first entry.
3295 Return the new location of point."
3296 (interactive)
3297 (let ((case-fold-search t)
3298 (pnt (point))
3299 (_ (bibtex-beginning-of-entry))
3300 (bounds (bibtex-valid-entry t)))
3301 (cond (bounds (goto-char (cdr bounds))) ; regular entry
3302 ;; @String or @Preamble
3303 ((setq bounds (or (bibtex-parse-string t) (bibtex-parse-preamble)))
3304 (goto-char (bibtex-end-of-string bounds)))
3305 ((looking-at bibtex-any-valid-entry-type)
3306 ;; Parsing of entry failed
3307 (error "Syntactically incorrect BibTeX entry starts here"))
3308 (t (if (interactive-p) (message "Not on a known BibTeX entry."))
3309 (goto-char pnt)))
3310 (point)))
3311
3312 (defun bibtex-goto-line (arg)
3313 "Goto line ARG, counting from beginning of (narrowed) buffer."
3314 ;; code adapted from `goto-line'
3315 (goto-char (point-min))
3316 (if (eq selective-display t)
3317 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
3318 (forward-line (1- arg))))
3319
3320 (defun bibtex-reposition-window ()
3321 "Make the current BibTeX entry visible.
3322 If entry is smaller than `window-body-height', entry is centered in window.
3323 Otherwise display the beginning of entry."
3324 (interactive)
3325 (let ((pnt (point))
3326 (beg (line-number-at-pos (bibtex-beginning-of-entry)))
3327 (end (line-number-at-pos (bibtex-end-of-entry))))
3328 (if (> (window-body-height) (- end beg))
3329 ;; entry fits in current window
3330 (progn
3331 (bibtex-goto-line (/ (+ 1 beg end) 2))
3332 (recenter)
3333 (goto-char pnt))
3334 ;; entry too large for current window
3335 (bibtex-goto-line beg)
3336 (recenter 0)
3337 (if (> (1+ (- (line-number-at-pos pnt) beg))
3338 (window-body-height))
3339 (bibtex-goto-line beg)
3340 (goto-char pnt)))))
3341
3342 (defun bibtex-mark-entry ()
3343 "Put mark at beginning, point at end of current BibTeX entry."
3344 (interactive)
3345 (push-mark (bibtex-beginning-of-entry))
3346 (bibtex-end-of-entry))
3347
3348 (defun bibtex-count-entries (&optional count-string-entries)
3349 "Count number of entries in current buffer or region.
3350 With prefix argument COUNT-STRING-ENTRIES count all entries,
3351 otherwise count all entries except @String entries.
3352 If mark is active count entries in region, if not in whole buffer."
3353 (interactive "P")
3354 (let ((number 0)
3355 (bibtex-sort-ignore-string-entries (not count-string-entries)))
3356 (save-restriction
3357 (if mark-active (narrow-to-region (region-beginning) (region-end)))
3358 (bibtex-map-entries (lambda (key beg end) (setq number (1+ number)))))
3359 (message "%s contains %d entries."
3360 (if mark-active "Region" "Buffer")
3361 number)))
3362
3363 (defun bibtex-ispell-entry ()
3364 "Check BibTeX entry for spelling errors."
3365 (interactive)
3366 (ispell-region (save-excursion (bibtex-beginning-of-entry))
3367 (save-excursion (bibtex-end-of-entry))))
3368
3369 (defun bibtex-ispell-abstract ()
3370 "Check abstract of BibTeX entry for spelling errors."
3371 (interactive)
3372 (let ((bounds (save-excursion
3373 (bibtex-beginning-of-entry)
3374 (bibtex-search-forward-field "abstract" t))))
3375 (if bounds
3376 (ispell-region (bibtex-start-of-text-in-field bounds)
3377 (bibtex-end-of-text-in-field bounds))
3378 (error "No abstract in entry"))))
3379
3380 (defun bibtex-narrow-to-entry ()
3381 "Narrow buffer to current BibTeX entry."
3382 (interactive)
3383 (save-excursion
3384 (widen)
3385 (narrow-to-region (bibtex-beginning-of-entry)
3386 (bibtex-end-of-entry))))
3387
3388 (defun bibtex-entry-index ()
3389 "Return index of BibTeX entry head at or past position of point.
3390 The index is a list (KEY CROSSREF-KEY ENTRY-TYPE) that is used for sorting
3391 the entries of the BibTeX buffer. CROSSREF-KEY is nil unless the value
3392 of `bibtex-maintain-sorted-entries' is `crossref'. Move point to the end
3393 of the head of the entry found. Return nil if no entry found."
3394 (let ((case-fold-search t))
3395 (if (re-search-forward bibtex-entry-maybe-empty-head nil t)
3396 (let ((key (bibtex-key-in-head))
3397 ;; all entry types should be downcase (for ease of comparison)
3398 (entry-type (downcase (bibtex-type-in-head))))
3399 ;; Don't search CROSSREF-KEY if we don't need it.
3400 (if (eq bibtex-maintain-sorted-entries 'crossref)
3401 (let ((bounds (bibtex-search-forward-field
3402 "\\(OPT\\)?crossref" t)))
3403 (list key
3404 (if bounds (bibtex-text-in-field-bounds bounds t))
3405 entry-type))
3406 (list key nil entry-type))))))
3407
3408 (defun bibtex-init-sort-entry-class-alist ()
3409 "Initialize `bibtex-sort-entry-class-alist' (buffer-local)."
3410 (unless (local-variable-p 'bibtex-sort-entry-class-alist)
3411 (set (make-local-variable 'bibtex-sort-entry-class-alist)
3412 (let ((i -1) alist)
3413 (dolist (class bibtex-sort-entry-class alist)
3414 (setq i (1+ i))
3415 (dolist (entry class)
3416 ;; All entry types should be downcase (for ease of comparison).
3417 (push (cons (if (stringp entry) (downcase entry) entry) i)
3418 alist)))))))
3419
3420 (defun bibtex-lessp (index1 index2)
3421 "Predicate for sorting BibTeX entries with indices INDEX1 and INDEX2.
3422 Each index is a list (KEY CROSSREF-KEY ENTRY-TYPE).
3423 The predicate depends on the variable `bibtex-maintain-sorted-entries'.
3424 If its value is nil use plain sorting."
3425 (cond ((not index1) (not index2)) ; indices can be nil
3426 ((not index2) nil)
3427 ((eq bibtex-maintain-sorted-entries 'crossref)
3428 ;; CROSSREF-KEY may be nil or it can point to an entry
3429 ;; in another BibTeX file. In both cases we ignore CROSSREF-KEY.
3430 (if (and (nth 1 index1)
3431 (cdr (assoc-string (nth 1 index1) bibtex-reference-keys)))
3432 (if (and (nth 1 index2)
3433 (cdr (assoc-string (nth 1 index2) bibtex-reference-keys)))
3434 (or (string-lessp (nth 1 index1) (nth 1 index2))
3435 (and (string-equal (nth 1 index1) (nth 1 index2))
3436 (string-lessp (nth 0 index1) (nth 0 index2))))
3437 (not (string-lessp (nth 0 index2) (nth 1 index1))))
3438 (if (and (nth 1 index2)
3439 (cdr (assoc-string (nth 1 index2) bibtex-reference-keys)))
3440 (string-lessp (nth 0 index1) (nth 1 index2))
3441 (string-lessp (nth 0 index1) (nth 0 index2)))))
3442 ((eq bibtex-maintain-sorted-entries 'entry-class)
3443 (let ((n1 (cdr (or (assoc (nth 2 index1) bibtex-sort-entry-class-alist)
3444 (assoc 'catch-all bibtex-sort-entry-class-alist)
3445 '(nil . 1000)))) ; if there is nothing else
3446 (n2 (cdr (or (assoc (nth 2 index2) bibtex-sort-entry-class-alist)
3447 (assoc 'catch-all bibtex-sort-entry-class-alist)
3448 '(nil . 1000))))) ; if there is nothing else
3449 (or (< n1 n2)
3450 (and (= n1 n2)
3451 (string-lessp (car index1) (car index2))))))
3452 (t ; (eq bibtex-maintain-sorted-entries 'plain)
3453 (string-lessp (car index1) (car index2)))))
3454
3455 (defun bibtex-sort-buffer ()
3456 "Sort BibTeX buffer alphabetically by key.
3457 The predicate for sorting is defined via `bibtex-maintain-sorted-entries'.
3458 If its value is nil use plain sorting. Text outside of BibTeX entries is not
3459 affected. If `bibtex-sort-ignore-string-entries' is non-nil, @String entries
3460 are ignored."
3461 (interactive)
3462 (bibtex-beginning-of-first-entry) ; Needed by `sort-subr'
3463 (bibtex-init-sort-entry-class-alist) ; Needed by `bibtex-lessp'.
3464 (if (and (eq bibtex-maintain-sorted-entries 'crossref)
3465 (nlistp bibtex-reference-keys))
3466 (bibtex-parse-keys)) ; Needed by `bibtex-lessp'.
3467 (sort-subr nil
3468 'bibtex-skip-to-valid-entry ; NEXTREC function
3469 'bibtex-end-of-entry ; ENDREC function
3470 'bibtex-entry-index ; STARTKEY function
3471 nil ; ENDKEY function
3472 'bibtex-lessp)) ; PREDICATE
3473
3474 (defun bibtex-search-crossref (crossref-key &optional pnt split noerror)
3475 "Move point to the beginning of BibTeX entry CROSSREF-KEY.
3476 If `bibtex-files' is non-nil, search all these files.
3477 Otherwise the search is limited to the current buffer.
3478 Return position of entry if CROSSREF-KEY is found or nil otherwise.
3479 If CROSSREF-KEY is in the same buffer like current entry but before it
3480 an error is signaled. If NOERRER is non-nil this error is suppressed.
3481 Optional arg PNT is the position of the referencing entry. It defaults
3482 to position of point. If optional arg SPLIT is non-nil, split window
3483 so that both the referencing and the crossrefed entry are displayed.
3484
3485 If called interactively, CROSSREF-KEY defaults to either the crossref key
3486 of current entry or a key matched by `bibtex-cite-matcher-alist',
3487 whatever is nearer to the position of point. SPLIT is t. NOERROR is nil
3488 for a crossref key, t otherwise."
3489 (interactive
3490 (save-excursion
3491 (let* ((pnt (point))
3492 (_ (bibtex-beginning-of-entry))
3493 (end (cdr (bibtex-valid-entry t)))
3494 (_ (unless end (error "Not inside valid entry")))
3495 (beg (match-end 0)) ; set by `bibtex-valid-entry'
3496 (bounds (bibtex-search-forward-field "crossref" end))
3497 case-fold-search best temp crossref-key)
3498 (if bounds
3499 (setq crossref-key (bibtex-text-in-field-bounds bounds t)
3500 best (cons (bibtex-dist pnt (bibtex-end-of-field bounds)
3501 (bibtex-start-of-field bounds))
3502 crossref-key)))
3503 (dolist (matcher bibtex-cite-matcher-alist)
3504 (goto-char beg)
3505 (while (re-search-forward (car matcher) end t)
3506 (setq temp (bibtex-dist pnt (match-end (cdr matcher))
3507 (match-beginning (cdr matcher))))
3508 ;; Accept the key closest to the position of point.
3509 (if (or (not best) (< temp (car best)))
3510 (setq best (cons temp (match-string-no-properties
3511 (cdr matcher)))))))
3512 (goto-char pnt)
3513 (setq temp (bibtex-read-key "Find crossref key: " (cdr best) t))
3514 (list temp (point) t (not (and crossref-key
3515 (string= temp crossref-key)))))))
3516
3517 (let (buffer pos eqb)
3518 (save-excursion
3519 (setq pos (bibtex-search-entry crossref-key t)
3520 buffer (current-buffer)))
3521 (setq eqb (eq buffer (current-buffer)))
3522 (cond ((not pos)
3523 (if split (message "Crossref key `%s' not found" crossref-key)))
3524 (split ; called (quasi) interactively
3525 (unless pnt (setq pnt (point)))
3526 (goto-char pnt)
3527 (if (and eqb (= pos (save-excursion (bibtex-beginning-of-entry))))
3528 (message "Key `%s' is current entry" crossref-key)
3529 (if eqb (select-window (split-window))
3530 (pop-to-buffer buffer))
3531 (goto-char pos)
3532 (bibtex-reposition-window)
3533 (beginning-of-line)
3534 (if (and eqb (> pnt pos) (not noerror))
3535 (error "The referencing entry must precede the crossrefed entry!"))))
3536 ;; `bibtex-search-crossref' is called noninteractively during
3537 ;; clean-up of an entry. Then it is not possible to check
3538 ;; whether the current entry and the crossrefed entry have
3539 ;; the correct sorting order.
3540 (eqb (goto-char pos))
3541 (t (set-buffer buffer) (goto-char pos)))
3542 pos))
3543 ;; backward compatibility
3544 (defalias 'bibtex-find-crossref 'bibtex-search-crossref)
3545
3546 (defun bibtex-dist (pos beg end)
3547 "Return distance between POS and region delimited by BEG and END."
3548 (cond ((and (<= beg pos) (<= pos end)) 0)
3549 ((< pos beg) (- beg pos))
3550 (t (- pos end))))
3551
3552 ;;;###autoload
3553 (defun bibtex-search-entry (key &optional global start display)
3554 "Move point to the beginning of BibTeX entry named KEY.
3555 Return position of entry if KEY is found or nil if not found.
3556 With GLOBAL non-nil, search KEY in `bibtex-files'. Otherwise the search
3557 is limited to the current buffer. Optional arg START is buffer position
3558 where the search starts. If it is nil, start search at beginning of buffer.
3559 If DISPLAY is non-nil, display the buffer containing KEY.
3560 Otherwise, use `set-buffer'.
3561 When called interactively, GLOBAL is t if there is a prefix arg or the current
3562 mode is not `bibtex-mode', START is nil, and DISPLAY is t."
3563 (interactive
3564 (let ((global (or current-prefix-arg (not (eq major-mode 'bibtex-mode)))))
3565 (list (bibtex-read-key "Find key: " nil global) global nil t)))
3566 (if (and global bibtex-files)
3567 (let ((buffer-list (bibtex-initialize t))
3568 buffer found)
3569 (while (and (not found)
3570 (setq buffer (pop buffer-list)))
3571 (with-current-buffer buffer
3572 (if (and (listp bibtex-reference-keys)
3573 (cdr (assoc-string key bibtex-reference-keys)))
3574 ;; `bibtex-search-entry' moves point if key found
3575 (setq found (bibtex-search-entry key)))))
3576 (cond ((and found display)
3577 (let ((same-window-buffer-names
3578 (cons (buffer-name buffer) same-window-buffer-names)))
3579 (pop-to-buffer buffer)
3580 (bibtex-reposition-window)))
3581 (found (set-buffer buffer))
3582 (display (message "Key `%s' not found" key)))
3583 found)
3584
3585 (let* ((case-fold-search t)
3586 (pnt (save-excursion
3587 (goto-char (or start (point-min)))
3588 (if (re-search-forward (concat "^[ \t]*\\("
3589 bibtex-entry-type
3590 "\\)[ \t]*[({][ \t\n]*\\("
3591 (regexp-quote key)
3592 "\\)[ \t\n]*[,=]")
3593 nil t)
3594 (match-beginning 0)))))
3595 (cond (pnt
3596 (goto-char pnt)
3597 (if display (bibtex-reposition-window)))
3598 (display (message "Key `%s' not found" key)))
3599 pnt)))
3600 ;; backward compatibility
3601 (defalias 'bibtex-find-entry 'bibtex-search-entry)
3602
3603 (defun bibtex-prepare-new-entry (index)
3604 "Prepare a new BibTeX entry with index INDEX.
3605 INDEX is a list (KEY CROSSREF-KEY ENTRY-TYPE).
3606 Move point where the entry KEY should be placed.
3607 If `bibtex-maintain-sorted-entries' is non-nil, perform a binary
3608 search to look for place for KEY. This requires that buffer is sorted,
3609 see `bibtex-validate'.
3610 Return t if preparation was successful or nil if entry KEY already exists."
3611 (bibtex-init-sort-entry-class-alist) ; Needed by `bibtex-lessp'.
3612 (if (and (eq bibtex-maintain-sorted-entries 'crossref)
3613 (nlistp bibtex-reference-keys))
3614 (bibtex-parse-keys)) ; Needed by `bibtex-lessp'.
3615 (let ((key (nth 0 index))
3616 key-exist)
3617 (cond ((or (null key)
3618 (and (stringp key)
3619 (string-equal key ""))
3620 (and (not (setq key-exist (bibtex-search-entry key)))
3621 (not bibtex-maintain-sorted-entries)))
3622 (bibtex-move-outside-of-entry))
3623 ;; if key-exist is non-nil due to the previous cond clause
3624 ;; then point will be at beginning of entry named key.
3625 (key-exist)
3626 (t ; `bibtex-maintain-sorted-entries' is non-nil
3627 (let* ((case-fold-search t)
3628 (left (save-excursion (bibtex-beginning-of-first-entry)))
3629 (bounds (save-excursion (goto-char (point-max))
3630 (bibtex-skip-to-valid-entry t)))
3631 (right (if bounds (cdr bounds) (point-min)))
3632 (found (if (>= left right) left))
3633 actual-index new)
3634 (save-excursion
3635 ;; Binary search
3636 (while (not found)
3637 (goto-char (/ (+ left right) 2))
3638 (bibtex-skip-to-valid-entry t)
3639 (setq actual-index (bibtex-entry-index))
3640 (cond ((bibtex-lessp index actual-index)
3641 (setq new (bibtex-beginning-of-entry))
3642 (if (equal right new)
3643 (setq found right)
3644 (setq right new)))
3645 (t
3646 (bibtex-end-of-entry)
3647 (bibtex-skip-to-valid-entry)
3648 (setq new (point))
3649 (if (equal left new)
3650 (setq found right)
3651 (setq left new))))))
3652 (goto-char found)
3653 (bibtex-beginning-of-entry)
3654 (setq actual-index (save-excursion (bibtex-entry-index)))
3655 (when (or (not actual-index)
3656 (bibtex-lessp actual-index index))
3657 ;; buffer contains no valid entries or
3658 ;; greater than last entry --> append
3659 (bibtex-end-of-entry)
3660 (unless (bobp) (newline (forward-line 2)))
3661 (beginning-of-line)))))
3662 (unless key-exist t)))
3663
3664 (defun bibtex-validate (&optional test-thoroughly)
3665 "Validate if buffer or region is syntactically correct.
3666 Check also for duplicate keys and correct sort order provided
3667 `bibtex-maintain-sorted-entries' is non-nil.
3668 With optional argument TEST-THOROUGHLY non-nil check also for
3669 the absence of required fields and for questionable month fields.
3670 If mark is active, validate current region, if not the whole buffer.
3671 Only check known entry types, so you can put comments outside of entries.
3672 Return t if test was successful, nil otherwise."
3673 (interactive "P")
3674 (let* ((case-fold-search t)
3675 error-list syntax-error)
3676 (save-excursion
3677 (save-restriction
3678 (if mark-active (narrow-to-region (region-beginning) (region-end)))
3679
3680 ;; Check syntactical structure of entries
3681 (goto-char (point-min))
3682 (bibtex-progress-message "Checking syntactical structure")
3683 (let (bounds end)
3684 (while (setq end (re-search-forward "^[ \t]*@" nil t))
3685 (bibtex-progress-message)
3686 (goto-char (match-beginning 0))
3687 (cond ((setq bounds (bibtex-valid-entry))
3688 (goto-char (cdr bounds)))
3689 ((setq bounds (or (bibtex-parse-string)
3690 (bibtex-parse-preamble)))
3691 (goto-char (bibtex-end-of-string bounds)))
3692 ((looking-at bibtex-any-valid-entry-type)
3693 (push (cons (bibtex-current-line)
3694 "Syntax error (check esp. commas, braces, and quotes)")
3695 error-list)
3696 (goto-char (match-end 0)))
3697 (t (goto-char end)))))
3698 (bibtex-progress-message 'done)
3699
3700 (if error-list
3701 ;; Continue only if there were no syntax errors.
3702 (setq syntax-error t)
3703
3704 ;; Check for duplicate keys and correct sort order
3705 (bibtex-init-sort-entry-class-alist) ; Needed by `bibtex-lessp'.
3706 (bibtex-parse-keys) ; Possibly needed by `bibtex-lessp'.
3707 ; Always needed by subsequent global key check.
3708 (let (previous current key-list)
3709 (bibtex-progress-message "Checking for duplicate keys")
3710 (bibtex-map-entries
3711 (lambda (key beg end)
3712 (bibtex-progress-message)
3713 (setq current (bibtex-entry-index))
3714 (cond ((not previous))
3715 ((member key key-list)
3716 (push (cons (bibtex-current-line)
3717 (format "Duplicate key `%s'" key))
3718 error-list))
3719 ((and bibtex-maintain-sorted-entries
3720 (not (bibtex-lessp previous current)))
3721 (push (cons (bibtex-current-line)
3722 "Entries out of order")
3723 error-list)))
3724 (push key key-list)
3725 (setq previous current)))
3726 (bibtex-progress-message 'done))
3727
3728 ;; Check for duplicate keys in `bibtex-files'.
3729 ;; `bibtex-validate' only compares keys in current buffer with keys
3730 ;; in `bibtex-files'. `bibtex-validate-globally' compares keys for
3731 ;; each file in `bibtex-files' with keys of all other files in
3732 ;; `bibtex-files'.
3733 ;; We don't want to be fooled by outdated `bibtex-reference-keys'.
3734 (dolist (buffer (bibtex-initialize nil t))
3735 (dolist (key (with-current-buffer buffer bibtex-reference-keys))
3736 (when (and (cdr key)
3737 (cdr (assoc-string (car key) bibtex-reference-keys)))
3738 (bibtex-search-entry (car key))
3739 (push (cons (bibtex-current-line)
3740 (format "Duplicate key `%s' in %s" (car key)
3741 (abbreviate-file-name (buffer-file-name buffer))))
3742 error-list))))
3743
3744 (when test-thoroughly
3745 (bibtex-progress-message
3746 "Checking required fields and month fields")
3747 (let ((bibtex-sort-ignore-string-entries t))
3748 (bibtex-map-entries
3749 (lambda (key beg end)
3750 (bibtex-progress-message)
3751 (let* ((entry-list (assoc-string (bibtex-type-in-head)
3752 bibtex-entry-field-alist t))
3753 (req (copy-sequence (elt (elt entry-list 1) 0)))
3754 (creq (copy-sequence (elt (elt entry-list 2) 0)))
3755 crossref-there bounds alt-there field)
3756 (bibtex-beginning-first-field beg)
3757 (while (setq bounds (bibtex-parse-field))
3758 (let ((field-name (bibtex-name-in-field bounds)))
3759 (if (and (bibtex-string= field-name "month")
3760 ;; Check only abbreviated month fields.
3761 (let ((month (bibtex-text-in-field-bounds bounds)))
3762 (not (or (string-match "\\`[\"{].+[\"}]\\'" month)
3763 (assoc-string
3764 month
3765 bibtex-predefined-month-strings t)))))
3766 (push (cons (bibtex-current-line)
3767 "Questionable month field")
3768 error-list))
3769 (setq field (assoc-string field-name req t)
3770 req (delete field req)
3771 creq (delete (assoc-string field-name creq t) creq))
3772 (if (nth 3 field)
3773 (if alt-there
3774 (push (cons (bibtex-current-line)
3775 "More than one non-empty alternative")
3776 error-list)
3777 (setq alt-there t)))
3778 (if (bibtex-string= field-name "crossref")
3779 (setq crossref-there t)))
3780 (goto-char (bibtex-end-of-field bounds)))
3781 (if crossref-there (setq req creq))
3782 (let (alt)
3783 (dolist (field req)
3784 (if (nth 3 field)
3785 (push (car field) alt)
3786 (push (cons (save-excursion (goto-char beg)
3787 (bibtex-current-line))
3788 (format "Required field `%s' missing"
3789 (car field)))
3790 error-list)))
3791 ;; The following fails if there are more than two
3792 ;; alternatives in a BibTeX entry, which isn't
3793 ;; the case momentarily.
3794 (if (cdr alt)
3795 (push (cons (save-excursion (goto-char beg)
3796 (bibtex-current-line))
3797 (format "Alternative fields `%s'/`%s' missing"
3798 (car alt) (cadr alt)))
3799 error-list)))))))
3800 (bibtex-progress-message 'done)))))
3801
3802 (if error-list
3803 (let ((file (file-name-nondirectory (buffer-file-name)))
3804 (dir default-directory)
3805 (err-buf "*BibTeX validation errors*"))
3806 (setq error-list (sort error-list 'car-less-than-car))
3807 (with-current-buffer (get-buffer-create err-buf)
3808 (setq default-directory dir)
3809 (unless (eq major-mode 'compilation-mode) (compilation-mode))
3810 (toggle-read-only -1)
3811 (delete-region (point-min) (point-max))
3812 (insert "BibTeX mode command `bibtex-validate'\n"
3813 (if syntax-error
3814 "Maybe undetected errors due to syntax errors. Correct and validate again.\n"
3815 "\n"))
3816 (dolist (err error-list)
3817 (insert (format "%s:%d: %s\n" file (car err) (cdr err))))
3818 (set-buffer-modified-p nil)
3819 (toggle-read-only 1)
3820 (goto-line 3)) ; first error message
3821 (display-buffer err-buf)
3822 nil) ; return `nil' (i.e., buffer is invalid)
3823 (message "%s is syntactically correct"
3824 (if mark-active "Region" "Buffer"))
3825 t))) ; return `t' (i.e., buffer is valid)
3826
3827 (defun bibtex-validate-globally (&optional strings)
3828 "Check for duplicate keys in `bibtex-files'.
3829 With optional prefix arg STRINGS, check for duplicate strings, too.
3830 Return t if test was successful, nil otherwise."
3831 (interactive "P")
3832 (let ((buffer-list (bibtex-initialize t))
3833 buffer-key-list current-buf current-keys error-list)
3834 ;; Check for duplicate keys within BibTeX buffer
3835 (dolist (buffer buffer-list)
3836 (save-excursion
3837 (set-buffer buffer)
3838 (let (entry-type key key-list)
3839 (goto-char (point-min))
3840 (while (re-search-forward bibtex-entry-head nil t)
3841 (setq entry-type (bibtex-type-in-head)
3842 key (bibtex-key-in-head))
3843 (if (or (and strings (bibtex-string= entry-type "string"))
3844 (assoc-string entry-type bibtex-entry-field-alist t))
3845 (if (member key key-list)
3846 (push (format "%s:%d: Duplicate key `%s'\n"
3847 (buffer-file-name)
3848 (bibtex-current-line) key)
3849 error-list)
3850 (push key key-list))))
3851 (push (cons buffer key-list) buffer-key-list))))
3852
3853 ;; Check for duplicate keys among BibTeX buffers
3854 (while (setq current-buf (pop buffer-list))
3855 (setq current-keys (cdr (assq current-buf buffer-key-list)))
3856 (with-current-buffer current-buf
3857 (dolist (buffer buffer-list)
3858 (dolist (key (cdr (assq buffer buffer-key-list)))
3859 (when (assoc-string key current-keys)
3860 (bibtex-search-entry key)
3861 (push (format "%s:%d: Duplicate key `%s' in %s\n"
3862 (buffer-file-name) (bibtex-current-line) key
3863 (abbreviate-file-name (buffer-file-name buffer)))
3864 error-list))))))
3865
3866 ;; Process error list
3867 (if error-list
3868 (let ((err-buf "*BibTeX validation errors*"))
3869 (with-current-buffer (get-buffer-create err-buf)
3870 (unless (eq major-mode 'compilation-mode) (compilation-mode))
3871 (toggle-read-only -1)
3872 (delete-region (point-min) (point-max))
3873 (insert "BibTeX mode command `bibtex-validate-globally'\n\n")
3874 (dolist (err (sort error-list 'string-lessp)) (insert err))
3875 (set-buffer-modified-p nil)
3876 (toggle-read-only 1)
3877 (goto-line 3)) ; first error message
3878 (display-buffer err-buf)
3879 nil) ; return `nil' (i.e., buffer is invalid)
3880 (message "No duplicate keys.")
3881 t))) ; return `t' (i.e., buffer is valid)
3882
3883 (defun bibtex-next-field (begin &optional comma)
3884 "Move point to end of text of next BibTeX field or entry head.
3885 With prefix BEGIN non-nil, move point to its beginning. Optional arg COMMA
3886 is as in `bibtex-enclosing-field'. It is t for interactive calls."
3887 (interactive (list current-prefix-arg t))
3888 (let ((bounds (bibtex-find-text-internal t nil comma))
3889 end-of-entry)
3890 (if (not bounds)
3891 (setq end-of-entry t)
3892 (goto-char (nth 3 bounds))
3893 (if (assoc-string (car bounds) '("@String" "@Preamble") t)
3894 (setq end-of-entry t)
3895 ;; BibTeX key or field
3896 (if (looking-at ",[ \t\n]*") (goto-char (match-end 0)))
3897 ;; end of entry
3898 (if (looking-at "[)}][ \t\n]*") (setq end-of-entry t))))
3899 (if (and end-of-entry
3900 (re-search-forward bibtex-any-entry-maybe-empty-head nil t))
3901 (goto-char (match-beginning 0)))
3902 (bibtex-find-text begin nil bibtex-help-message)))
3903
3904 (defun bibtex-find-text (&optional begin noerror help comma)
3905 "Move point to end of text of current BibTeX field or entry head.
3906 With optional prefix BEGIN non-nil, move point to its beginning.
3907 Unless NOERROR is non-nil, an error is signaled if point is not
3908 on a BibTeX field. If optional arg HELP is non-nil print help message.
3909 When called interactively, the value of HELP is `bibtex-help-message'.
3910 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3911 interactive calls."
3912 (interactive (list current-prefix-arg nil bibtex-help-message t))
3913 (let ((bounds (bibtex-find-text-internal t nil comma)))
3914 (cond (bounds
3915 (if begin
3916 (progn (goto-char (nth 1 bounds))
3917 (if (looking-at "[{\"]")
3918 (forward-char)))
3919 (goto-char (nth 2 bounds))
3920 (if (memq (preceding-char) '(?} ?\"))
3921 (forward-char -1)))
3922 (if help (bibtex-print-help-message (car bounds))))
3923 ((not noerror) (error "Not on BibTeX field")))))
3924
3925 (defun bibtex-find-text-internal (&optional noerror subfield comma)
3926 "Find text part of current BibTeX field or entry head.
3927 Return list (NAME START-TEXT END-TEXT END STRING-CONST) with field name
3928 or entry type, start and end of text, and end of field or entry head.
3929 STRING-CONST is a flag which is non-nil if current subfield delimited by #
3930 is a BibTeX string constant. Return value is nil if field or entry head
3931 are not found.
3932 If optional arg NOERROR is non-nil, an error message is suppressed
3933 if text is not found. If optional arg SUBFIELD is non-nil START-TEXT
3934 and END-TEXT correspond to the current subfield delimited by #.
3935 Optional arg COMMA is as in `bibtex-enclosing-field'."
3936 (save-excursion
3937 (let ((pnt (point))
3938 (bounds (bibtex-enclosing-field comma t))
3939 (case-fold-search t)
3940 name start-text end-text end failure done no-sub string-const)
3941 (bibtex-beginning-of-entry)
3942 (cond (bounds
3943 (setq name (bibtex-name-in-field bounds t)
3944 start-text (bibtex-start-of-text-in-field bounds)
3945 end-text (bibtex-end-of-text-in-field bounds)
3946 end (bibtex-end-of-field bounds)))
3947 ;; @String
3948 ((setq bounds (bibtex-parse-string t))
3949 (if (<= pnt (bibtex-end-of-string bounds))
3950 (setq name "@String" ;; not a field name!
3951 start-text (bibtex-start-of-text-in-string bounds)
3952 end-text (bibtex-end-of-text-in-string bounds)
3953 end (bibtex-end-of-string bounds))
3954 (setq failure t)))
3955 ;; @Preamble
3956 ((setq bounds (bibtex-parse-preamble))
3957 (if (<= pnt (bibtex-end-of-string bounds))
3958 (setq name "@Preamble" ;; not a field name!
3959 start-text (bibtex-start-of-text-in-string bounds)
3960 end-text (bibtex-end-of-text-in-string bounds)
3961 end (bibtex-end-of-string bounds))
3962 (setq failure t)))
3963 ;; BibTeX head
3964 ((looking-at bibtex-entry-maybe-empty-head)
3965 (goto-char (match-end 0))
3966 (if comma (save-match-data
3967 (re-search-forward "\\=[ \t\n]*," nil t)))
3968 (if (<= pnt (point))
3969 (setq name (match-string-no-properties bibtex-type-in-head)
3970 start-text (or (match-beginning bibtex-key-in-head)
3971 (match-end 0))
3972 end-text (or (match-end bibtex-key-in-head)
3973 (match-end 0))
3974 end end-text
3975 no-sub t) ; subfields do not make sense
3976 (setq failure t)))
3977 (t (setq failure t)))
3978 (when (and subfield (not failure))
3979 (setq failure no-sub)
3980 (unless failure
3981 (goto-char start-text)
3982 (while (not done)
3983 (if (or (prog1 (looking-at bibtex-field-const)
3984 (setq end-text (match-end 0)
3985 string-const t))
3986 (prog1 (setq bounds (bibtex-parse-field-string))
3987 (setq end-text (cdr bounds)
3988 string-const nil)))
3989 (progn
3990 (if (and (<= start-text pnt) (<= pnt end-text))
3991 (setq done t)
3992 (goto-char end-text))
3993 (if (looking-at "[ \t\n]*#[ \t\n]*")
3994 (setq start-text (goto-char (match-end 0)))))
3995 (setq done t failure t)))))
3996 (cond ((not failure)
3997 (list name start-text end-text end string-const))
3998 ((and no-sub (not noerror))
3999 (error "Not on text part of BibTeX field"))
4000 ((not noerror) (error "Not on BibTeX field"))))))
4001
4002 (defun bibtex-remove-OPT-or-ALT (&optional comma)
4003 "Remove the string starting optional/alternative fields.
4004 Align text and go thereafter to end of text. Optional arg COMMA
4005 is as in `bibtex-enclosing-field'. It is t for interactive calls."
4006 (interactive (list t))
4007 (let ((case-fold-search t)
4008 (bounds (bibtex-enclosing-field comma)))
4009 (save-excursion
4010 (goto-char (bibtex-start-of-name-in-field bounds))
4011 (when (looking-at "OPT\\|ALT")
4012 (delete-region (match-beginning 0) (match-end 0))
4013 ;; make field non-OPT
4014 (search-forward "=")
4015 (forward-char -1)
4016 (delete-horizontal-space)
4017 (if bibtex-align-at-equal-sign
4018 (indent-to-column (- bibtex-text-indentation 2))
4019 (insert " "))
4020 (search-forward "=")
4021 (delete-horizontal-space)
4022 (if bibtex-align-at-equal-sign
4023 (insert " ")
4024 (indent-to-column bibtex-text-indentation))))))
4025
4026 (defun bibtex-remove-delimiters (&optional comma)
4027 "Remove \"\" or {} around current BibTeX field text.
4028 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
4029 interactive calls."
4030 (interactive (list t))
4031 (let ((bounds (bibtex-find-text-internal nil t comma)))
4032 (unless (nth 4 bounds)
4033 (delete-region (1- (nth 2 bounds)) (nth 2 bounds))
4034 (delete-region (nth 1 bounds) (1+ (nth 1 bounds))))))
4035
4036 (defun bibtex-kill-field (&optional copy-only comma)
4037 "Kill the entire enclosing BibTeX field.
4038 With prefix arg COPY-ONLY, copy the current field to `bibtex-field-kill-ring',
4039 but do not actually kill it. Optional arg COMMA is as in
4040 `bibtex-enclosing-field'. It is t for interactive calls."
4041 (interactive (list current-prefix-arg t))
4042 (save-excursion
4043 (let* ((case-fold-search t)
4044 (bounds (bibtex-enclosing-field comma))
4045 (end (bibtex-end-of-field bounds))
4046 (beg (bibtex-start-of-field bounds)))
4047 (goto-char end)
4048 (skip-chars-forward ",")
4049 (push (list (bibtex-name-in-field bounds) nil
4050 (bibtex-text-in-field-bounds bounds))
4051 bibtex-field-kill-ring)
4052 (if (> (length bibtex-field-kill-ring) bibtex-field-kill-ring-max)
4053 (setcdr (nthcdr (1- bibtex-field-kill-ring-max)
4054 bibtex-field-kill-ring)
4055 nil))
4056 (setq bibtex-field-kill-ring-yank-pointer bibtex-field-kill-ring)
4057 (unless copy-only
4058 (delete-region beg end))))
4059 (setq bibtex-last-kill-command 'field))
4060
4061 (defun bibtex-copy-field-as-kill (&optional comma)
4062 "Copy the BibTeX field at point to the kill ring.
4063 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
4064 interactive calls."
4065 (interactive (list t))
4066 (bibtex-kill-field t comma))
4067
4068 (defun bibtex-kill-entry (&optional copy-only)
4069 "Kill the entire enclosing BibTeX entry.
4070 With prefix arg COPY-ONLY, copy the current entry to `bibtex-entry-kill-ring',
4071 but do not actually kill it."
4072 (interactive "P")
4073 (save-excursion
4074 (let* ((case-fold-search t)
4075 (beg (bibtex-beginning-of-entry))
4076 (end (progn (bibtex-end-of-entry)
4077 (if (re-search-forward
4078 bibtex-any-entry-maybe-empty-head nil 'move)
4079 (goto-char (match-beginning 0)))
4080 (point))))
4081 (push (buffer-substring-no-properties beg end)
4082 bibtex-entry-kill-ring)
4083 (if (> (length bibtex-entry-kill-ring) bibtex-entry-kill-ring-max)
4084 (setcdr (nthcdr (1- bibtex-entry-kill-ring-max)
4085 bibtex-entry-kill-ring)
4086 nil))
4087 (setq bibtex-entry-kill-ring-yank-pointer bibtex-entry-kill-ring)
4088 (unless copy-only
4089 (delete-region beg end))))
4090 (setq bibtex-last-kill-command 'entry))
4091
4092 (defun bibtex-copy-entry-as-kill ()
4093 "Copy the entire enclosing BibTeX entry to `bibtex-entry-kill-ring'."
4094 (interactive)
4095 (bibtex-kill-entry t))
4096
4097 (defun bibtex-yank (&optional n)
4098 "Reinsert the last BibTeX item.
4099 More precisely, reinsert the field or entry killed or yanked most recently.
4100 With argument N, reinsert the Nth most recently killed BibTeX item.
4101 See also the command \\[bibtex-yank-pop]."
4102 (interactive "*p")
4103 (bibtex-insert-kill (1- n) t)
4104 (setq this-command 'bibtex-yank))
4105
4106 (defun bibtex-yank-pop (n)
4107 "Replace just-yanked killed BibTeX item with a different item.
4108 This command is allowed only immediately after a `bibtex-yank' or a
4109 `bibtex-yank-pop'. In this case, the region contains a reinserted
4110 previously killed BibTeX item. `bibtex-yank-pop' deletes that item
4111 and inserts in its place a different killed BibTeX item.
4112
4113 With no argument, the previous kill is inserted.
4114 With argument N, insert the Nth previous kill.
4115 If N is negative, this is a more recent kill.
4116
4117 The sequence of kills wraps around, so that after the oldest one
4118 comes the newest one."
4119 (interactive "*p")
4120 (unless (eq last-command 'bibtex-yank)
4121 (error "Previous command was not a BibTeX yank"))
4122 (setq this-command 'bibtex-yank)
4123 (let ((inhibit-read-only t))
4124 (delete-region (point) (mark t))
4125 (bibtex-insert-kill n t)))
4126
4127 (defun bibtex-empty-field (&optional comma)
4128 "Delete the text part of the current field, replace with empty text.
4129 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
4130 interactive calls."
4131 (interactive (list t))
4132 (let ((bounds (bibtex-enclosing-field comma)))
4133 (goto-char (bibtex-start-of-text-in-field bounds))
4134 (delete-region (point) (bibtex-end-of-text-in-field bounds))
4135 (insert (bibtex-field-left-delimiter)
4136 (bibtex-field-right-delimiter))
4137 (bibtex-find-text t nil bibtex-help-message)))
4138
4139 (defun bibtex-pop-previous (arg)
4140 "Replace text of current field with the similar field in previous entry.
4141 With arg, goes up ARG entries. Repeated, goes up so many times. May be
4142 intermixed with \\[bibtex-pop-next] (bibtex-pop-next)."
4143 (interactive "p")
4144 (bibtex-pop arg 'previous))
4145
4146 (defun bibtex-pop-next (arg)
4147 "Replace text of current field with the text of similar field in next entry.
4148 With arg, goes down ARG entries. Repeated, goes down so many times. May be
4149 intermixed with \\[bibtex-pop-previous] (bibtex-pop-previous)."
4150 (interactive "p")
4151 (bibtex-pop arg 'next))
4152
4153 (defun bibtex-clean-entry (&optional new-key called-by-reformat)
4154 "Finish editing the current BibTeX entry and clean it up.
4155 Check that no required fields are empty and formats entry dependent
4156 on the value of `bibtex-entry-format'.
4157 If the reference key of the entry is empty or a prefix argument is given,
4158 calculate a new reference key. (Note: this works only if fields in entry
4159 begin on separate lines prior to calling `bibtex-clean-entry' or if
4160 'realign is contained in `bibtex-entry-format'.)
4161 Don't call `bibtex-clean-entry' on @Preamble entries.
4162 At end of the cleaning process, the functions in
4163 `bibtex-clean-entry-hook' are called with region narrowed to entry."
4164 ;; Opt. arg CALLED-BY-REFORMAT is t if `bibtex-clean-entry'
4165 ;; is called by `bibtex-reformat'
4166 (interactive "P")
4167 (let ((case-fold-search t)
4168 (start (bibtex-beginning-of-entry))
4169 (_ (or (looking-at bibtex-any-entry-maybe-empty-head)
4170 (error "Not inside a BibTeX entry")))
4171 (entry-type (bibtex-type-in-head))
4172 (key (bibtex-key-in-head)))
4173 (cond ((bibtex-string= entry-type "preamble")
4174 ;; (bibtex-format-preamble)
4175 (error "No clean up of @Preamble entries"))
4176 ((bibtex-string= entry-type "string")
4177 (setq entry-type 'string))
4178 ;; (bibtex-format-string)
4179 (t (bibtex-format-entry)))
4180 ;; set key
4181 (when (or new-key (not key))
4182 (setq key (bibtex-generate-autokey))
4183 ;; Sometimes `bibtex-generate-autokey' returns an empty string
4184 (if (or bibtex-autokey-edit-before-use (string= "" key))
4185 (setq key (if (eq entry-type 'string)
4186 (bibtex-read-string-key key)
4187 (bibtex-read-key "Key to use: " key))))
4188 (save-excursion
4189 (re-search-forward (if (eq entry-type 'string)
4190 bibtex-string-maybe-empty-head
4191 bibtex-entry-maybe-empty-head))
4192 (if (match-beginning bibtex-key-in-head)
4193 (delete-region (match-beginning bibtex-key-in-head)
4194 (match-end bibtex-key-in-head)))
4195 (insert key)))
4196
4197 (unless called-by-reformat
4198 (let* ((end (save-excursion
4199 (bibtex-end-of-entry)
4200 (if (re-search-forward
4201 bibtex-entry-maybe-empty-head nil 'move)
4202 (goto-char (match-beginning 0)))
4203 (point)))
4204 (entry (buffer-substring start end))
4205 ;; include the crossref key in index
4206 (index (let ((bibtex-maintain-sorted-entries 'crossref))
4207 (bibtex-entry-index))) ; moves point to end of head
4208 error)
4209 ;; sorting
4210 (if (and bibtex-maintain-sorted-entries
4211 (not (and bibtex-sort-ignore-string-entries
4212 (eq entry-type 'string))))
4213 (progn
4214 (delete-region start end)
4215 (setq error (not (bibtex-prepare-new-entry index))
4216 start (point)) ; update start
4217 (save-excursion (insert entry)))
4218 (bibtex-search-entry key)
4219 (setq error (or (/= (point) start)
4220 (bibtex-search-entry key nil end))))
4221 (if error
4222 (error "New inserted entry yields duplicate key"))
4223 (dolist (buffer (bibtex-initialize))
4224 (with-current-buffer buffer
4225 (if (cdr (assoc-string key bibtex-reference-keys))
4226 (error "Duplicate key in %s" (buffer-file-name)))))
4227
4228 ;; Only update the list of keys if it has been built already.
4229 (cond ((eq entry-type 'string)
4230 (if (and (listp bibtex-strings)
4231 (not (assoc key bibtex-strings)))
4232 (push (cons key (bibtex-text-in-string
4233 (bibtex-parse-string) t))
4234 bibtex-strings)))
4235 ;; We have a normal entry.
4236 ((listp bibtex-reference-keys)
4237 (cond ((not (assoc key bibtex-reference-keys))
4238 (push (cons key t) bibtex-reference-keys))
4239 ((not (cdr (assoc key bibtex-reference-keys)))
4240 ;; Turn a crossref key into a header key
4241 (setq bibtex-reference-keys
4242 (cons (cons key t)
4243 (delete (list key) bibtex-reference-keys)))))
4244 ;; Handle crossref key.
4245 (if (and (nth 1 index)
4246 (not (assoc (nth 1 index) bibtex-reference-keys)))
4247 (push (list (nth 1 index)) bibtex-reference-keys)))))
4248
4249 ;; final clean up
4250 (if bibtex-clean-entry-hook
4251 (save-excursion
4252 (save-restriction
4253 (bibtex-narrow-to-entry)
4254 (run-hooks 'bibtex-clean-entry-hook)))))))
4255
4256 (defun bibtex-fill-field-bounds (bounds justify &optional move)
4257 "Fill BibTeX field delimited by BOUNDS.
4258 If JUSTIFY is non-nil justify as well.
4259 If optional arg MOVE is non-nil move point to end of field."
4260 (let ((end-field (copy-marker (bibtex-end-of-field bounds))))
4261 (if (not justify)
4262 (goto-char (bibtex-start-of-text-in-field bounds))
4263 (goto-char (bibtex-start-of-field bounds))
4264 (forward-char) ; leading comma
4265 (bibtex-delete-whitespace)
4266 (open-line 1)
4267 (forward-char)
4268 (indent-to-column (+ bibtex-entry-offset
4269 bibtex-field-indentation))
4270 (re-search-forward "[ \t\n]*=" end-field)
4271 (replace-match "=")
4272 (forward-char -1)
4273 (if bibtex-align-at-equal-sign
4274 (indent-to-column
4275 (+ bibtex-entry-offset (- bibtex-text-indentation 2)))
4276 (insert " "))
4277 (forward-char)
4278 (bibtex-delete-whitespace)
4279 (if bibtex-align-at-equal-sign
4280 (insert " ")
4281 (indent-to-column bibtex-text-indentation)))
4282 ;; Paragraphs within fields are not preserved. Bother?
4283 (fill-region-as-paragraph (line-beginning-position) end-field
4284 default-justification nil (point))
4285 (if move (goto-char end-field))))
4286
4287 (defun bibtex-fill-field (&optional justify)
4288 "Like \\[fill-paragraph], but fill current BibTeX field.
4289 If optional prefix JUSTIFY is non-nil justify as well.
4290 In BibTeX mode this function is bound to `fill-paragraph-function'."
4291 (interactive "*P")
4292 (let ((pnt (copy-marker (point)))
4293 (bounds (bibtex-enclosing-field t)))
4294 (bibtex-fill-field-bounds bounds justify)
4295 (goto-char pnt)))
4296
4297 (defun bibtex-fill-entry ()
4298 "Fill current BibTeX entry.
4299 Realign entry, so that every field starts on a separate line. Field
4300 names appear in column `bibtex-field-indentation', field text starts in
4301 column `bibtex-text-indentation' and continuation lines start here, too.
4302 If `bibtex-align-at-equal-sign' is non-nil, align equal signs, too."
4303 (interactive "*")
4304 (let ((pnt (copy-marker (point)))
4305 (end (copy-marker (bibtex-end-of-entry)))
4306 (beg (bibtex-beginning-of-entry)) ; move point
4307 bounds)
4308 (bibtex-delete-whitespace)
4309 (indent-to-column bibtex-entry-offset)
4310 (bibtex-beginning-first-field beg)
4311 (while (setq bounds (bibtex-parse-field))
4312 (bibtex-fill-field-bounds bounds t t))
4313 (if (looking-at ",")
4314 (forward-char))
4315 (skip-chars-backward " \t\n")
4316 (bibtex-delete-whitespace)
4317 (open-line 1)
4318 (forward-char)
4319 (indent-to-column bibtex-entry-offset)
4320 (goto-char pnt)))
4321
4322 (defun bibtex-realign ()
4323 "Realign BibTeX entries such that they are separated by one blank line."
4324 (goto-char (point-min))
4325 (let ((case-fold-search t)
4326 (entry-type (concat "[ \t\n]*\\(" bibtex-entry-type "\\)")))
4327 ;; No blank lines prior to the first entry if there no
4328 ;; non-white characters in front of it.
4329 (when (looking-at entry-type)
4330 (replace-match "\\1"))
4331 ;; Entries are separated by one blank line.
4332 (while (re-search-forward entry-type nil t)
4333 (replace-match "\n\n\\1"))
4334 ;; One blank line past the last entry if it is followed by
4335 ;; non-white characters, no blank line otherwise.
4336 (beginning-of-line)
4337 (when (re-search-forward bibtex-entry-type nil t)
4338 (bibtex-end-of-entry)
4339 (bibtex-delete-whitespace)
4340 (open-line (if (eobp) 1 2)))))
4341
4342 (defun bibtex-reformat (&optional read-options)
4343 "Reformat all BibTeX entries in buffer or region.
4344 Without prefix argument, reformatting is based on `bibtex-entry-format'.
4345 With prefix argument, read options for reformatting from minibuffer.
4346 With \\[universal-argument] \\[universal-argument] prefix argument, reuse previous answers (if any) again.
4347 If mark is active reformat entries in region, if not in whole buffer."
4348 (interactive "*P")
4349 (let* ((pnt (point))
4350 (use-previous-options
4351 (and (equal (prefix-numeric-value read-options) 16)
4352 (or bibtex-reformat-previous-options
4353 bibtex-reformat-previous-reference-keys)))
4354 (bibtex-entry-format
4355 (cond (read-options
4356 (if use-previous-options
4357 bibtex-reformat-previous-options
4358 (setq bibtex-reformat-previous-options
4359 (mapcar (lambda (option)
4360 (if (y-or-n-p (car option)) (cdr option)))
4361 `(("Realign entries (recommended)? " . 'realign)
4362 ("Remove empty optional and alternative fields? " . 'opts-or-alts)
4363 ("Remove delimiters around pure numerical fields? " . 'numerical-fields)
4364 (,(concat (if bibtex-comma-after-last-field "Insert" "Remove")
4365 " comma at end of entry? ") . 'last-comma)
4366 ("Replace double page dashes by single ones? " . 'page-dashes)
4367 ("Delete whitespace at the beginning and end of fields? " . 'whitespace)
4368 ("Inherit booktitle? " . 'inherit-booktitle)
4369 ("Force delimiters? " . 'delimiters)
4370 ("Unify case of entry types and field names? " . 'unify-case)
4371 ("Enclose parts of field entries by braces? " . 'braces)
4372 ("Replace parts of field entries by string constants? " . 'strings))))))
4373 ;; Do not include required-fields because `bibtex-reformat'
4374 ;; cannot handle the error messages of `bibtex-format-entry'.
4375 ;; Use `bibtex-validate' to check for required fields.
4376 ((eq t bibtex-entry-format)
4377 '(realign opts-or-alts numerical-fields delimiters
4378 last-comma page-dashes unify-case inherit-booktitle
4379 whitespace braces strings))
4380 (t
4381 (remove 'required-fields (push 'realign bibtex-entry-format)))))
4382 (reformat-reference-keys
4383 (if read-options
4384 (if use-previous-options
4385 bibtex-reformat-previous-reference-keys
4386 (setq bibtex-reformat-previous-reference-keys
4387 (y-or-n-p "Generate new reference keys automatically? ")))))
4388 (bibtex-sort-ignore-string-entries t)
4389 bibtex-autokey-edit-before-use)
4390
4391 (save-restriction
4392 (if mark-active (narrow-to-region (region-beginning) (region-end)))
4393 (if (memq 'realign bibtex-entry-format)
4394 (bibtex-realign))
4395 (bibtex-progress-message "Formatting" 1)
4396 (bibtex-map-entries (lambda (key beg end)
4397 (bibtex-progress-message)
4398 (bibtex-clean-entry reformat-reference-keys t)))
4399 (bibtex-progress-message 'done))
4400 (when reformat-reference-keys
4401 (kill-local-variable 'bibtex-reference-keys)
4402 (when bibtex-maintain-sorted-entries
4403 (bibtex-progress-message "Sorting" 1)
4404 (bibtex-sort-buffer)
4405 (bibtex-progress-message 'done)))
4406 (goto-char pnt)))
4407
4408 (defun bibtex-convert-alien (&optional read-options)
4409 "Make an alien BibTeX buffer fully usable by BibTeX mode.
4410 If a file does not conform with all standards used by BibTeX mode,
4411 some of the high-level features of BibTeX mode are not available.
4412 This function tries to convert current buffer to conform with these standards.
4413 With prefix argument READ-OPTIONS non-nil, read options for reformatting
4414 entries from minibuffer."
4415 (interactive "*P")
4416 (message "Starting to validate buffer...")
4417 (sit-for 1)
4418 (bibtex-realign)
4419 (deactivate-mark) ; So `bibtex-validate' works on the whole buffer.
4420 (if (not (let (bibtex-maintain-sorted-entries)
4421 (bibtex-validate)))
4422 (message "Correct errors and call `bibtex-convert-alien' again")
4423 (message "Starting to reformat entries...")
4424 (sit-for 2)
4425 (bibtex-reformat read-options)
4426 (goto-char (point-max))
4427 (message "Buffer is now parsable. Please save it.")))
4428
4429 (defun bibtex-complete ()
4430 "Complete word fragment before point according to context.
4431 If point is inside key or crossref field perform key completion based on
4432 `bibtex-reference-keys'. Inside a month field perform key completion
4433 based on `bibtex-predefined-month-strings'. Inside any other field
4434 \(including a String or Preamble definition) perform string completion
4435 based on `bibtex-strings'.
4436 An error is signaled if point is outside key or BibTeX field."
4437 (interactive)
4438 (let ((pnt (point))
4439 (case-fold-search t)
4440 bounds name compl)
4441 (save-excursion
4442 (if (and (setq bounds (bibtex-enclosing-field nil t))
4443 (>= pnt (bibtex-start-of-text-in-field bounds))
4444 (<= pnt (bibtex-end-of-text-in-field bounds)))
4445 (setq name (bibtex-name-in-field bounds t)
4446 compl (cond ((bibtex-string= name "crossref")
4447 ;; point is in crossref field
4448 'crossref-key)
4449 ((bibtex-string= name "month")
4450 ;; point is in month field
4451 bibtex-predefined-month-strings)
4452 ;; point is in other field
4453 (t (bibtex-strings))))
4454 (bibtex-beginning-of-entry)
4455 (cond ((setq bounds (bibtex-parse-string t))
4456 ;; point is inside a @String key
4457 (cond ((and (>= pnt (nth 1 (car bounds)))
4458 (<= pnt (nth 2 (car bounds))))
4459 (setq compl 'string))
4460 ;; point is inside a @String field
4461 ((and (>= pnt (bibtex-start-of-text-in-string bounds))
4462 (<= pnt (bibtex-end-of-text-in-string bounds)))
4463 (setq compl (bibtex-strings)))))
4464 ;; point is inside a @Preamble field
4465 ((setq bounds (bibtex-parse-preamble))
4466 (if (and (>= pnt (bibtex-start-of-text-in-string bounds))
4467 (<= pnt (bibtex-end-of-text-in-string bounds)))
4468 (setq compl (bibtex-strings))))
4469 ((and (looking-at bibtex-entry-maybe-empty-head)
4470 ;; point is inside a key
4471 (or (and (match-beginning bibtex-key-in-head)
4472 (>= pnt (match-beginning bibtex-key-in-head))
4473 (<= pnt (match-end bibtex-key-in-head)))
4474 ;; or point is on empty key
4475 (and (not (match-beginning bibtex-key-in-head))
4476 (= pnt (match-end 0)))))
4477 (setq compl 'key)))))
4478
4479 (cond ((eq compl 'key)
4480 ;; key completion: no cleanup needed
4481 (setq choose-completion-string-functions nil)
4482 (let (completion-ignore-case)
4483 (bibtex-complete-internal (bibtex-global-key-alist))))
4484
4485 ((eq compl 'crossref-key)
4486 ;; crossref key completion
4487 ;;
4488 ;; If we quit the *Completions* buffer without requesting
4489 ;; a completion, `choose-completion-string-functions' is still
4490 ;; non-nil. Therefore, `choose-completion-string-functions' is
4491 ;; always set (either to non-nil or nil) when a new completion
4492 ;; is requested.
4493 (let (completion-ignore-case)
4494 (setq choose-completion-string-functions
4495 (lambda (choice buffer mini-p base-size)
4496 (setq choose-completion-string-functions nil)
4497 (choose-completion-string choice buffer base-size)
4498 (bibtex-complete-crossref-cleanup choice)
4499 t)) ; needed by choose-completion-string-functions
4500 (bibtex-complete-crossref-cleanup
4501 (bibtex-complete-internal (bibtex-global-key-alist)))))
4502
4503 ((eq compl 'string)
4504 ;; string key completion: no cleanup needed
4505 (setq choose-completion-string-functions nil)
4506 (let ((completion-ignore-case t))
4507 (bibtex-complete-internal bibtex-strings)))
4508
4509 (compl
4510 ;; string completion
4511 (let ((completion-ignore-case t))
4512 (setq choose-completion-string-functions
4513 `(lambda (choice buffer mini-p base-size)
4514 (setq choose-completion-string-functions nil)
4515 (choose-completion-string choice buffer base-size)
4516 (bibtex-complete-string-cleanup choice ',compl)
4517 t)) ; needed by `choose-completion-string-functions'
4518 (bibtex-complete-string-cleanup (bibtex-complete-internal compl)
4519 compl)))
4520
4521 (t (setq choose-completion-string-functions nil)
4522 (error "Point outside key or BibTeX field")))))
4523
4524 (defun bibtex-Article ()
4525 "Insert a new BibTeX @Article entry; see also `bibtex-entry'."
4526 (interactive "*")
4527 (bibtex-entry "Article"))
4528
4529 (defun bibtex-Book ()
4530 "Insert a new BibTeX @Book entry; see also `bibtex-entry'."
4531 (interactive "*")
4532 (bibtex-entry "Book"))
4533
4534 (defun bibtex-Booklet ()
4535 "Insert a new BibTeX @Booklet entry; see also `bibtex-entry'."
4536 (interactive "*")
4537 (bibtex-entry "Booklet"))
4538
4539 (defun bibtex-InBook ()
4540 "Insert a new BibTeX @InBook entry; see also `bibtex-entry'."
4541 (interactive "*")
4542 (bibtex-entry "InBook"))
4543
4544 (defun bibtex-InCollection ()
4545 "Insert a new BibTeX @InCollection entry; see also `bibtex-entry'."
4546 (interactive "*")
4547 (bibtex-entry "InCollection"))
4548
4549 (defun bibtex-InProceedings ()
4550 "Insert a new BibTeX @InProceedings entry; see also `bibtex-entry'."
4551 (interactive "*")
4552 (bibtex-entry "InProceedings"))
4553
4554 (defun bibtex-Manual ()
4555 "Insert a new BibTeX @Manual entry; see also `bibtex-entry'."
4556 (interactive "*")
4557 (bibtex-entry "Manual"))
4558
4559 (defun bibtex-MastersThesis ()
4560 "Insert a new BibTeX @MastersThesis entry; see also `bibtex-entry'."
4561 (interactive "*")
4562 (bibtex-entry "MastersThesis"))
4563
4564 (defun bibtex-Misc ()
4565 "Insert a new BibTeX @Misc entry; see also `bibtex-entry'."
4566 (interactive "*")
4567 (bibtex-entry "Misc"))
4568
4569 (defun bibtex-PhdThesis ()
4570 "Insert a new BibTeX @PhdThesis entry; see also `bibtex-entry'."
4571 (interactive "*")
4572 (bibtex-entry "PhdThesis"))
4573
4574 (defun bibtex-Proceedings ()
4575 "Insert a new BibTeX @Proceedings entry; see also `bibtex-entry'."
4576 (interactive "*")
4577 (bibtex-entry "Proceedings"))
4578
4579 (defun bibtex-TechReport ()
4580 "Insert a new BibTeX @TechReport entry; see also `bibtex-entry'."
4581 (interactive "*")
4582 (bibtex-entry "TechReport"))
4583
4584 (defun bibtex-Unpublished ()
4585 "Insert a new BibTeX @Unpublished entry; see also `bibtex-entry'."
4586 (interactive "*")
4587 (bibtex-entry "Unpublished"))
4588
4589 (defun bibtex-String (&optional key)
4590 "Insert a new BibTeX @String entry with key KEY."
4591 (interactive (list (bibtex-read-string-key)))
4592 (let ((bibtex-maintain-sorted-entries
4593 (unless bibtex-sort-ignore-string-entries
4594 bibtex-maintain-sorted-entries))
4595 endpos)
4596 (unless (bibtex-prepare-new-entry (list key nil "String"))
4597 (error "Entry with key `%s' already exists" key))
4598 (if (zerop (length key)) (setq key nil))
4599 (indent-to-column bibtex-entry-offset)
4600 (insert "@String"
4601 (bibtex-entry-left-delimiter))
4602 (if key
4603 (insert key)
4604 (setq endpos (point)))
4605 (insert " = "
4606 (bibtex-field-left-delimiter))
4607 (if key
4608 (setq endpos (point)))
4609 (insert (bibtex-field-right-delimiter)
4610 (bibtex-entry-right-delimiter)
4611 "\n")
4612 (goto-char endpos)))
4613
4614 (defun bibtex-Preamble ()
4615 "Insert a new BibTeX @Preamble entry."
4616 (interactive "*")
4617 (bibtex-move-outside-of-entry)
4618 (indent-to-column bibtex-entry-offset)
4619 (insert "@Preamble"
4620 (bibtex-entry-left-delimiter)
4621 (bibtex-field-left-delimiter))
4622 (let ((endpos (point)))
4623 (insert (bibtex-field-right-delimiter)
4624 (bibtex-entry-right-delimiter)
4625 "\n")
4626 (goto-char endpos)))
4627
4628 (defun bibtex-url (&optional pos no-browse)
4629 "Browse a URL for the BibTeX entry at point.
4630 Optional POS is the location of the BibTeX entry.
4631 The URL is generated using the schemes defined in `bibtex-generate-url-list'
4632 \(see there\). If multiple schemes match for this entry, or the same scheme
4633 matches more than once, use the one for which the first step's match is the
4634 closest to POS. The URL is passed to `browse-url' unless NO-BROWSE is t.
4635 Return the URL or nil if none can be generated."
4636 (interactive)
4637 (unless pos (setq pos (point)))
4638 (save-excursion
4639 (goto-char pos)
4640 (bibtex-beginning-of-entry)
4641 (let ((end (save-excursion (bibtex-end-of-entry)))
4642 (fields-alist (save-excursion (bibtex-parse-entry t)))
4643 ;; Always ignore case,
4644 (case-fold-search t)
4645 text url scheme obj fmt fl-match step)
4646 ;; The return value of `bibtex-parse-entry' (i.e., FIELDS-ALIST)
4647 ;; is always used to generate the URL. However, if the BibTeX
4648 ;; entry contains more than one URL, we have multiple matches
4649 ;; for the first step defining the generation of the URL.
4650 ;; Therefore, we try to initiate the generation of the URL
4651 ;; based on the match of `bibtex-font-lock-url' that is the
4652 ;; closest to POS. If that fails (no match found) we try to
4653 ;; initiate the generation of the URL based on the properly
4654 ;; concatenated CONTENT of the field as returned by
4655 ;; `bibtex-text-in-field-bounds'. The latter approach can
4656 ;; differ from the former because `bibtex-font-lock-url' uses
4657 ;; the buffer itself.
4658 (while (bibtex-font-lock-url end t)
4659 (push (list (bibtex-dist pos (match-beginning 0) (match-end 0))
4660 (match-beginning 0)
4661 (buffer-substring-no-properties
4662 (match-beginning 0) (match-end 0)))
4663 fl-match)
4664 ;; `bibtex-font-lock-url' moves point to end of match.
4665 (forward-char))
4666 (when fl-match
4667 (setq fl-match (car (sort fl-match (lambda (x y) (< (car x) (car y))))))
4668 (goto-char (nth 1 fl-match))
4669 (bibtex-beginning-of-field) (re-search-backward ",")
4670 (let* ((bounds (bibtex-parse-field))
4671 (name (bibtex-name-in-field bounds))
4672 (content (bibtex-text-in-field-bounds bounds t))
4673 (lst bibtex-generate-url-list))
4674 ;; This match can fail when CONTENT differs from text in buffer.
4675 (when (string-match (regexp-quote (nth 2 fl-match)) content)
4676 ;; TEXT is the part of CONTENT that starts with the match
4677 ;; of `bibtex-font-lock-url' we are looking for.
4678 (setq text (substring content (match-beginning 0)))
4679 (while (and (not url) (setq scheme (pop lst)))
4680 ;; Verify the match of `bibtex-font-lock-url' by
4681 ;; comparing with TEXT.
4682 (when (and (bibtex-string= (caar scheme) name)
4683 (string-match (cdar scheme) text))
4684 (setq url t scheme (cdr scheme)))))))
4685
4686 ;; If the match of `bibtex-font-lock-url' was not approved
4687 ;; parse FIELDS-ALIST, i.e., the output of `bibtex-parse-entry'.
4688 (unless url
4689 (let ((lst bibtex-generate-url-list))
4690 (while (and (not url) (setq scheme (pop lst)))
4691 (when (and (setq text (cdr (assoc-string (caar scheme)
4692 fields-alist t)))
4693 (string-match (cdar scheme) text))
4694 (setq url t scheme (cdr scheme))))))
4695
4696 (when url
4697 (setq url (if (null scheme) (match-string 0 text)
4698 (if (stringp (car scheme))
4699 (setq fmt (pop scheme)))
4700 (dotimes (i (length scheme))
4701 (setq step (nth i scheme))
4702 ;; The first step shall use TEXT as obtained earlier.
4703 (unless (= i 0)
4704 (setq text (cdr (assoc-string (car step) fields-alist t))))
4705 (if (string-match (nth 1 step) text)
4706 (push (cond ((functionp (nth 2 step))
4707 (funcall (nth 2 step) text))
4708 ((numberp (nth 2 step))
4709 (match-string (nth 2 step) text))
4710 (t
4711 (replace-match (nth 2 step) t nil text)))
4712 obj)
4713 ;; If SCHEME is set up correctly,
4714 ;; we should never reach this point
4715 (error "Match failed: %s" text)))
4716 (if fmt (apply 'format fmt (nreverse obj))
4717 (apply 'concat (nreverse obj)))))
4718 (if (interactive-p) (message "%s" url))
4719 (unless no-browse (browse-url url)))
4720 (if (and (not url) (interactive-p)) (message "No URL known."))
4721 url)))
4722
4723 \f
4724 ;; Make BibTeX a Feature
4725
4726 (provide 'bibtex)
4727
4728 ;; arch-tag: ee2be3af-caad-427f-b42a-d20fad630d04
4729 ;;; bibtex.el ends here