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