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