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