1 ;;; bibtex.el --- BibTeX mode for GNU Emacs
3 ;; Copyright (C) 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002,
4 ;; 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
6 ;; Author: Stefan Schoef <schoef@offis.uni-oldenburg.de>
7 ;; Bengt Martensson <bengt@mathematik.uni-Bremen.de>
8 ;; Marc Shapiro <marc.shapiro@acm.org>
9 ;; Mike Newton <newton@gumby.cs.caltech.edu>
10 ;; Aaron Larson <alarson@src.honeywell.com>
11 ;; Dirk Herrmann <D.Herrmann@tu-bs.de>
12 ;; Maintainer: Roland Winkler <roland.winkler@physik.uni-erlangen.de>
13 ;; Keywords: BibTeX, LaTeX, TeX
15 ;; This file is part of GNU Emacs.
17 ;; GNU Emacs is free software; you can redistribute it and/or modify
18 ;; it under the terms of the GNU General Public License as published by
19 ;; the Free Software Foundation; either version 2, or (at your option)
22 ;; GNU Emacs is distributed in the hope that it will be useful,
23 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 ;; GNU General Public License for more details.
27 ;; You should have received a copy of the GNU General Public License
28 ;; along with GNU Emacs; see the file COPYING. If not, write to the
29 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
30 ;; Boston, MA 02110-1301, USA.
34 ;; Major mode for editing and validating BibTeX files.
37 ;; See documentation for function bibtex-mode or type "\M-x describe-mode"
38 ;; when you are in BibTeX mode.
41 ;; Distribute texinfo file.
55 (defgroup bibtex-autokey nil
56 "Generate automatically a key from the author/editor and the title field."
58 :prefix "bibtex-autokey-")
60 (defcustom bibtex-mode-hook nil
61 "List of functions to call on entry to BibTeX mode."
65 (defcustom bibtex-field-delimiters 'braces
66 "Type of field delimiters. Allowed values are `braces' or `double-quotes'."
68 :type '(choice (const braces)
69 (const double-quotes)))
71 (defcustom bibtex-entry-delimiters 'braces
72 "Type of entry delimiters. Allowed values are `braces' or `parentheses'."
74 :type '(choice (const braces)
77 (defcustom bibtex-include-OPTcrossref '("InProceedings" "InCollection")
78 "List of BibTeX entries that get an OPTcrossref field."
80 :type '(repeat string))
82 (defcustom bibtex-include-OPTkey t
83 "If non-nil, all newly created entries get an OPTkey field.
84 If this is a string, use it as the initial field text.
85 If this is a function, call it to generate the initial field text."
87 :type '(choice (const :tag "None" nil)
88 (string :tag "Initial text")
89 (function :tag "Initialize Function" :value fun)
90 (const :tag "Default" t)))
91 (put 'bibtex-include-OPTkey 'risky-local-variable t)
93 (defcustom bibtex-user-optional-fields
94 '(("annote" "Personal annotation (ignored)"))
95 "List of optional fields the user wants to have always present.
96 Entries should be of the same form as the OPTIONAL and
97 CROSSREF-OPTIONAL lists in `bibtex-entry-field-alist' (which see)."
99 :type '(repeat (group (string :tag "Field")
100 (string :tag "Comment")
101 (option (group :inline t
103 (choice :tag "Init" :value ""
106 (put 'bibtex-user-optional-fields 'risky-local-variable t)
108 (defcustom bibtex-entry-format
109 '(opts-or-alts required-fields numerical-fields)
110 "Type of formatting performed by `bibtex-clean-entry'.
111 It may be t, nil, or a list of symbols out of the following:
112 opts-or-alts Delete empty optional and alternative fields and
113 remove OPT and ALT prefixes from used fields.
114 required-fields Signal an error if a required field is missing.
115 numerical-fields Delete delimiters around numeral fields.
116 page-dashes Change double dashes in page field to single dash
117 (for scribe compatibility).
118 inherit-booktitle If entry contains a crossref field and the booktitle
119 field is empty, set the booktitle field to the content
120 of the title field of the crossreferenced entry.
121 realign Realign entries, so that field texts and perhaps equal
122 signs (depending on the value of
123 `bibtex-align-at-equal-sign') begin in the same column.
124 last-comma Add or delete comma on end of last field in entry,
125 according to value of `bibtex-comma-after-last-field'.
126 delimiters Change delimiters according to variables
127 `bibtex-field-delimiters' and `bibtex-entry-delimiters'.
128 unify-case Change case of entry and field names.
130 The value t means do all of the above formatting actions.
131 The value nil means do no formatting at all."
133 :type '(choice (const :tag "None" nil)
135 (set :menu-tag "Some"
137 (const required-fields)
138 (const numerical-fields)
140 (const inherit-booktitle)
144 (const unify-case))))
146 (defcustom bibtex-clean-entry-hook nil
147 "List of functions to call when entry has been cleaned.
148 Functions are called with point inside the cleaned entry, and the buffer
149 narrowed to just the entry."
153 (defcustom bibtex-maintain-sorted-entries nil
154 "If non-nil, BibTeX mode maintains all entries in sorted order.
155 Allowed non-nil values are:
156 plain or t All entries are sorted alphabetically.
157 crossref All entries are sorted alphabetically unless an entry has a
158 crossref field. These crossrefed entries are placed in
159 alphabetical order immediately preceding the main entry.
160 entry-class The entries are divided into classes according to their
161 entry name, see `bibtex-sort-entry-class'. Within each class
162 the entries are sorted alphabetically.
163 See also `bibtex-sort-ignore-string-entries'."
165 :type '(choice (const nil)
170 (put 'bibtex-maintain-sorted-entries 'safe-local-variable
171 '(lambda (a) (memq a '(nil t plain crossref entry-class))))
173 (defcustom bibtex-sort-entry-class
176 ("Book" "Proceedings"))
177 "List of classes of BibTeX entry names, used for sorting entries.
178 If value of `bibtex-maintain-sorted-entries' is `entry-class'
179 entries are ordered according to the classes they belong to. Each
180 class contains a list of entry names. An entry `catch-all' applies
181 to all entries not explicitly mentioned."
183 :type '(repeat (choice :tag "Class"
184 (const :tag "catch-all" (catch-all))
185 (repeat :tag "Entry name" string))))
186 (put 'bibtex-sort-entry-class 'safe-local-variable
187 (lambda (x) (let ((OK t))
192 (unless (or (stringp z) (eq z 'catch-all))
194 (unless (null y) (setq OK nil))))
195 (unless (null x) (setq OK nil))
198 (defcustom bibtex-sort-ignore-string-entries t
199 "If non-nil, BibTeX @String entries are not sort-significant.
200 That means they are ignored when determining ordering of the buffer
201 \(e.g., sorting, locating alphabetical position for new entries, etc.)."
205 (defcustom bibtex-field-kill-ring-max 20
206 "Max length of `bibtex-field-kill-ring' before discarding oldest elements."
210 (defcustom bibtex-entry-kill-ring-max 20
211 "Max length of `bibtex-entry-kill-ring' before discarding oldest elements."
215 (defcustom bibtex-parse-keys-timeout 60
216 "Time interval in seconds for parsing BibTeX buffers during idle time.
217 Parsing initializes `bibtex-reference-keys' and `bibtex-strings'."
221 (defcustom bibtex-parse-keys-fast t
222 "If non-nil, use fast but simplified algorithm for parsing BibTeX keys.
223 If parsing fails, try to set this variable to nil."
227 (defvar bibtex-entry-field-alist
229 ((("author" "Author1 [and Author2 ...] [and others]")
230 ("title" "Title of the article (BibTeX converts it to lowercase)")
231 ("journal" "Name of the journal (use string, remove braces)")
232 ("year" "Year of publication"))
233 (("volume" "Volume of the journal")
234 ("number" "Number of the journal (only allowed if entry contains volume)")
235 ("pages" "Pages in the journal")
236 ("month" "Month of the publication as a string (remove braces)")
237 ("note" "Remarks to be put at the end of the \\bibitem")))
238 ((("author" "Author1 [and Author2 ...] [and others]")
239 ("title" "Title of the article (BibTeX converts it to lowercase)"))
240 (("pages" "Pages in the journal")
241 ("journal" "Name of the journal (use string, remove braces)")
242 ("year" "Year of publication")
243 ("volume" "Volume of the journal")
244 ("number" "Number of the journal")
245 ("month" "Month of the publication as a string (remove braces)")
246 ("note" "Remarks to be put at the end of the \\bibitem"))))
248 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
249 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
250 ("title" "Title of the book")
251 ("publisher" "Publishing company")
252 ("year" "Year of publication"))
253 (("volume" "Volume of the book in the series")
254 ("number" "Number of the book in a small series (overwritten by volume)")
255 ("series" "Series in which the book appeared")
256 ("address" "Address of the publisher")
257 ("edition" "Edition of the book as a capitalized English word")
258 ("month" "Month of the publication as a string (remove braces)")
259 ("note" "Remarks to be put at the end of the \\bibitem")))
260 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
261 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
262 ("title" "Title of the book"))
263 (("publisher" "Publishing company")
264 ("year" "Year of publication")
265 ("volume" "Volume of the book in the series")
266 ("number" "Number of the book in a small series (overwritten by volume)")
267 ("series" "Series in which the book appeared")
268 ("address" "Address of the publisher")
269 ("edition" "Edition of the book as a capitalized English word")
270 ("month" "Month of the publication as a string (remove braces)")
271 ("note" "Remarks to be put at the end of the \\bibitem"))))
273 ((("title" "Title of the booklet (BibTeX converts it to lowercase)"))
274 (("author" "Author1 [and Author2 ...] [and others]")
275 ("howpublished" "The way in which the booklet was published")
276 ("address" "Address of the publisher")
277 ("month" "Month of the publication as a string (remove braces)")
278 ("year" "Year of publication")
279 ("note" "Remarks to be put at the end of the \\bibitem"))))
281 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
282 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
283 ("title" "Title of the book")
284 ("chapter" "Chapter in the book")
285 ("publisher" "Publishing company")
286 ("year" "Year of publication"))
287 (("volume" "Volume of the book in the series")
288 ("number" "Number of the book in a small series (overwritten by volume)")
289 ("series" "Series in which the book appeared")
290 ("type" "Word to use instead of \"chapter\"")
291 ("address" "Address of the publisher")
292 ("edition" "Edition of the book as a capitalized English word")
293 ("month" "Month of the publication as a string (remove braces)")
294 ("pages" "Pages in the book")
295 ("note" "Remarks to be put at the end of the \\bibitem")))
296 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
297 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
298 ("title" "Title of the book")
299 ("chapter" "Chapter in the book"))
300 (("pages" "Pages in the book")
301 ("publisher" "Publishing company")
302 ("year" "Year of publication")
303 ("volume" "Volume of the book in the series")
304 ("number" "Number of the book in a small series (overwritten by volume)")
305 ("series" "Series in which the book appeared")
306 ("type" "Word to use instead of \"chapter\"")
307 ("address" "Address of the publisher")
308 ("edition" "Edition of the book as a capitalized English word")
309 ("month" "Month of the publication as a string (remove braces)")
310 ("note" "Remarks to be put at the end of the \\bibitem"))))
312 ((("author" "Author1 [and Author2 ...] [and others]")
313 ("title" "Title of the article in book (BibTeX converts it to lowercase)")
314 ("booktitle" "Name of the book")
315 ("publisher" "Publishing company")
316 ("year" "Year of publication"))
317 (("editor" "Editor1 [and Editor2 ...] [and others]")
318 ("volume" "Volume of the book in the series")
319 ("number" "Number of the book in a small series (overwritten by volume)")
320 ("series" "Series in which the book appeared")
321 ("type" "Word to use instead of \"chapter\"")
322 ("chapter" "Chapter in the book")
323 ("pages" "Pages in the book")
324 ("address" "Address of the publisher")
325 ("edition" "Edition of the book as a capitalized English word")
326 ("month" "Month of the publication as a string (remove braces)")
327 ("note" "Remarks to be put at the end of the \\bibitem")))
328 ((("author" "Author1 [and Author2 ...] [and others]")
329 ("title" "Title of the article in book (BibTeX converts it to lowercase)")
330 ("booktitle" "Name of the book"))
331 (("pages" "Pages in the book")
332 ("publisher" "Publishing company")
333 ("year" "Year of publication")
334 ("editor" "Editor1 [and Editor2 ...] [and others]")
335 ("volume" "Volume of the book in the series")
336 ("number" "Number of the book in a small series (overwritten by volume)")
337 ("series" "Series in which the book appeared")
338 ("type" "Word to use instead of \"chapter\"")
339 ("chapter" "Chapter in the book")
340 ("address" "Address of the publisher")
341 ("edition" "Edition of the book as a capitalized English word")
342 ("month" "Month of the publication as a string (remove braces)")
343 ("note" "Remarks to be put at the end of the \\bibitem"))))
345 ((("author" "Author1 [and Author2 ...] [and others]")
346 ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)")
347 ("booktitle" "Name of the conference proceedings")
348 ("year" "Year of publication"))
349 (("editor" "Editor1 [and Editor2 ...] [and others]")
350 ("volume" "Volume of the conference proceedings in the series")
351 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
352 ("series" "Series in which the conference proceedings appeared")
353 ("pages" "Pages in the conference proceedings")
354 ("address" "Location of the Proceedings")
355 ("month" "Month of the publication as a string (remove braces)")
356 ("organization" "Sponsoring organization of the conference")
357 ("publisher" "Publishing company, its location")
358 ("note" "Remarks to be put at the end of the \\bibitem")))
359 ((("author" "Author1 [and Author2 ...] [and others]")
360 ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)"))
361 (("booktitle" "Name of the conference proceedings")
362 ("pages" "Pages in the conference proceedings")
363 ("year" "Year of publication")
364 ("editor" "Editor1 [and Editor2 ...] [and others]")
365 ("volume" "Volume of the conference proceedings in the series")
366 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
367 ("series" "Series in which the conference proceedings appeared")
368 ("address" "Location of the Proceedings")
369 ("month" "Month of the publication as a string (remove braces)")
370 ("organization" "Sponsoring organization of the conference")
371 ("publisher" "Publishing company, its location")
372 ("note" "Remarks to be put at the end of the \\bibitem"))))
374 ((("title" "Title of the manual"))
375 (("author" "Author1 [and Author2 ...] [and others]")
376 ("organization" "Publishing organization of the manual")
377 ("address" "Address of the organization")
378 ("edition" "Edition of the manual as a capitalized English word")
379 ("month" "Month of the publication as a string (remove braces)")
380 ("year" "Year of publication")
381 ("note" "Remarks to be put at the end of the \\bibitem"))))
383 ((("author" "Author1 [and Author2 ...] [and others]")
384 ("title" "Title of the master\'s thesis (BibTeX converts it to lowercase)")
385 ("school" "School where the master\'s thesis was written")
386 ("year" "Year of publication"))
387 (("type" "Type of the master\'s thesis (if other than \"Master\'s thesis\")")
388 ("address" "Address of the school (if not part of field \"school\") or country")
389 ("month" "Month of the publication as a string (remove braces)")
390 ("note" "Remarks to be put at the end of the \\bibitem"))))
393 (("author" "Author1 [and Author2 ...] [and others]")
394 ("title" "Title of the work (BibTeX converts it to lowercase)")
395 ("howpublished" "The way in which the work was published")
396 ("month" "Month of the publication as a string (remove braces)")
397 ("year" "Year of publication")
398 ("note" "Remarks to be put at the end of the \\bibitem"))))
400 ((("author" "Author1 [and Author2 ...] [and others]")
401 ("title" "Title of the PhD. thesis")
402 ("school" "School where the PhD. thesis was written")
403 ("year" "Year of publication"))
404 (("type" "Type of the PhD. thesis")
405 ("address" "Address of the school (if not part of field \"school\") or country")
406 ("month" "Month of the publication as a string (remove braces)")
407 ("note" "Remarks to be put at the end of the \\bibitem"))))
409 ((("title" "Title of the conference proceedings")
410 ("year" "Year of publication"))
411 (("booktitle" "Title of the proceedings for cross references")
412 ("editor" "Editor1 [and Editor2 ...] [and others]")
413 ("volume" "Volume of the conference proceedings in the series")
414 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
415 ("series" "Series in which the conference proceedings appeared")
416 ("address" "Location of the Proceedings")
417 ("month" "Month of the publication as a string (remove braces)")
418 ("organization" "Sponsoring organization of the conference")
419 ("publisher" "Publishing company, its location")
420 ("note" "Remarks to be put at the end of the \\bibitem"))))
422 ((("author" "Author1 [and Author2 ...] [and others]")
423 ("title" "Title of the technical report (BibTeX converts it to lowercase)")
424 ("institution" "Sponsoring institution of the report")
425 ("year" "Year of publication"))
426 (("type" "Type of the report (if other than \"technical report\")")
427 ("number" "Number of the technical report")
428 ("address" "Address of the institution (if not part of field \"institution\") 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"))))
432 ((("author" "Author1 [and Author2 ...] [and others]")
433 ("title" "Title of the unpublished work (BibTeX converts it to lowercase)")
434 ("note" "Remarks to be put at the end of the \\bibitem"))
435 (("month" "Month of the publication as a string (remove braces)")
436 ("year" "Year of publication")))))
438 "List of BibTeX entry types and their associated fields.
439 List elements are triples
440 \(ENTRY-NAME (REQUIRED OPTIONAL) (CROSSREF-REQUIRED CROSSREF-OPTIONAL)).
441 ENTRY-NAME is the name of a BibTeX entry. The remaining pairs contain
442 the required and optional fields of the BibTeX entry.
443 The second pair is used if a crossref field is present
444 and the first pair is used if a crossref field is absent.
445 If the second pair is nil, the first pair is always used.
446 REQUIRED, OPTIONAL, CROSSREF-REQUIRED and CROSSREF-OPTIONAL are lists.
447 Each element of these lists is a list of the form
448 \(FIELD-NAME COMMENT-STRING INIT ALTERNATIVE-FLAG).
449 COMMENT-STRING, INIT, and ALTERNATIVE-FLAG are optional.
450 FIELD-NAME is the name of the field, COMMENT-STRING is the comment that
451 appears in the echo area, INIT is either the initial content of the
452 field or a function, which is called to determine the initial content
453 of the field, and ALTERNATIVE-FLAG (either nil or t) marks if the
454 field is an alternative. ALTERNATIVE-FLAG may be t only in the
455 REQUIRED or CROSSREF-REQUIRED lists.")
456 (put 'bibtex-entry-field-alist 'risky-local-variable t)
458 (defcustom bibtex-comment-start "@Comment"
459 "String starting a BibTeX comment."
463 (defcustom bibtex-add-entry-hook nil
464 "List of functions to call when BibTeX entry has been inserted."
468 (defcustom bibtex-predefined-month-strings
469 '(("jan" . "January")
477 ("sep" . "September")
480 ("dec" . "December"))
481 "Alist of month string definitions used in the BibTeX style files.
482 Each element is a pair of strings (ABBREVIATION . EXPANSION)."
484 :type '(repeat (cons (string :tag "Month abbreviation")
485 (string :tag "Month expansion"))))
487 (defcustom bibtex-predefined-strings
489 bibtex-predefined-month-strings
490 '(("acmcs" . "ACM Computing Surveys")
491 ("acta" . "Acta Informatica")
492 ("cacm" . "Communications of the ACM")
493 ("ibmjrd" . "IBM Journal of Research and Development")
494 ("ibmsj" . "IBM Systems Journal")
495 ("ieeese" . "IEEE Transactions on Software Engineering")
496 ("ieeetc" . "IEEE Transactions on Computers")
497 ("ieeetcad" . "IEEE Transactions on Computer-Aided Design of Integrated Circuits")
498 ("ipl" . "Information Processing Letters")
499 ("jacm" . "Journal of the ACM")
500 ("jcss" . "Journal of Computer and System Sciences")
501 ("scp" . "Science of Computer Programming")
502 ("sicomp" . "SIAM Journal on Computing")
503 ("tcs" . "Theoretical Computer Science")
504 ("tocs" . "ACM Transactions on Computer Systems")
505 ("tods" . "ACM Transactions on Database Systems")
506 ("tog" . "ACM Transactions on Graphics")
507 ("toms" . "ACM Transactions on Mathematical Software")
508 ("toois" . "ACM Transactions on Office Information Systems")
509 ("toplas" . "ACM Transactions on Programming Languages and Systems")))
510 "Alist of string definitions used in the BibTeX style files.
511 Each element is a pair of strings (ABBREVIATION . EXPANSION)."
513 :type '(repeat (cons (string :tag "String")
514 (string :tag "String expansion"))))
516 (defcustom bibtex-string-files nil
517 "List of BibTeX files containing string definitions.
518 List elements can be absolute file names or file names relative
519 to the directories specified in `bibtex-string-file-path'."
521 :type '(repeat file))
523 (defvar bibtex-string-file-path (getenv "BIBINPUTS")
524 "*Colon separated list of paths to search for `bibtex-string-files'.")
526 (defcustom bibtex-files nil
527 "List of BibTeX files that are searched for entry keys.
528 List elements can be absolute file names or file names relative to the
529 directories specified in `bibtex-file-path'. If an element is a directory,
530 check all BibTeX files in this directory. If an element is the symbol
531 `bibtex-file-path', check all BibTeX files in `bibtex-file-path'."
533 :type '(repeat (choice (const :tag "bibtex-file-path" bibtex-file-path)
536 (defvar bibtex-file-path (getenv "BIBINPUTS")
537 "*Colon separated list of paths to search for `bibtex-files'.")
539 (defcustom bibtex-help-message t
540 "If non-nil print help messages in the echo area on entering a new field."
544 (defcustom bibtex-autokey-prefix-string ""
545 "String prefix for automatically generated reference keys.
546 See `bibtex-generate-autokey' for details."
547 :group 'bibtex-autokey
550 (defcustom bibtex-autokey-names 1
551 "Number of names to use for the automatically generated reference key.
552 Possibly more names are used according to `bibtex-autokey-names-stretch'.
553 If this variable is nil, all names are used.
554 See `bibtex-generate-autokey' for details."
555 :group 'bibtex-autokey
556 :type '(choice (const :tag "All" infty)
559 (defcustom bibtex-autokey-names-stretch 0
560 "Number of names that can additionally be used for reference keys.
561 These names are used only, if all names are used then.
562 See `bibtex-generate-autokey' for details."
563 :group 'bibtex-autokey
566 (defcustom bibtex-autokey-additional-names ""
567 "String to append to the generated key if not all names could be used.
568 See `bibtex-generate-autokey' for details."
569 :group 'bibtex-autokey
572 (defcustom bibtex-autokey-expand-strings nil
573 "If non-nil, expand strings when extracting the content of a BibTeX field.
574 See `bibtex-generate-autokey' for details."
575 :group 'bibtex-autokey
578 (defvar bibtex-autokey-transcriptions
579 '(;; language specific characters
580 ("\\\\aa" . "a") ; \aa -> a
581 ("\\\\AA" . "A") ; \AA -> A
582 ("\\\"a\\|\\\\\\\"a\\|\\\\ae" . "ae") ; "a,\"a,\ae -> ae
583 ("\\\"A\\|\\\\\\\"A\\|\\\\AE" . "Ae") ; "A,\"A,\AE -> Ae
584 ("\\\\i" . "i") ; \i -> i
585 ("\\\\j" . "j") ; \j -> j
586 ("\\\\l" . "l") ; \l -> l
587 ("\\\\L" . "L") ; \L -> L
588 ("\\\"o\\|\\\\\\\"o\\|\\\\o\\|\\\\oe" . "oe") ; "o,\"o,\o,\oe -> oe
589 ("\\\"O\\|\\\\\\\"O\\|\\\\O\\|\\\\OE" . "Oe") ; "O,\"O,\O,\OE -> Oe
590 ("\\\"s\\|\\\\\\\"s\\|\\\\3" . "ss") ; "s,\"s,\3 -> ss
591 ("\\\"u\\|\\\\\\\"u" . "ue") ; "u,\"u -> ue
592 ("\\\"U\\|\\\\\\\"U" . "Ue") ; "U,\"U -> Ue
594 ("\\\\`\\|\\\\'\\|\\\\\\^\\|\\\\~\\|\\\\=\\|\\\\\\.\\|\\\\u\\|\\\\v\\|\\\\H\\|\\\\t\\|\\\\c\\|\\\\d\\|\\\\b" . "")
595 ;; braces, quotes, concatenation.
598 ("\\\\?[ \t\n]+\\|~" . " "))
599 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
600 Used by the default values of `bibtex-autokey-name-change-strings' and
601 `bibtex-autokey-titleword-change-strings'. Defaults to translating some
602 language specific characters to their ASCII transcriptions, and
603 removing any character accents.")
605 (defcustom bibtex-autokey-name-change-strings
606 bibtex-autokey-transcriptions
607 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
608 Any part of a name matching OLD-REGEXP is replaced by NEW-STRING.
609 Case is significant in OLD-REGEXP. All regexps are tried in the
610 order in which they appear in the list.
611 See `bibtex-generate-autokey' for details."
612 :group 'bibtex-autokey
613 :type '(repeat (cons (regexp :tag "Old")
614 (string :tag "New"))))
616 (defcustom bibtex-autokey-name-case-convert-function 'downcase
617 "Function called for each name to perform case conversion.
618 See `bibtex-generate-autokey' for details."
619 :group 'bibtex-autokey
620 :type '(choice (const :tag "Preserve case" identity)
621 (const :tag "Downcase" downcase)
622 (const :tag "Capitalize" capitalize)
623 (const :tag "Upcase" upcase)
624 (function :tag "Conversion function")))
625 (put 'bibtex-autokey-name-case-convert-function 'safe-local-variable
626 (lambda (x) (memq x '(upcase downcase capitalize identity))))
627 (defvaralias 'bibtex-autokey-name-case-convert
628 'bibtex-autokey-name-case-convert-function)
630 (defcustom bibtex-autokey-name-length 'infty
631 "Number of characters from name to incorporate into key.
632 If this is set to anything but a number, all characters are used.
633 See `bibtex-generate-autokey' for details."
634 :group 'bibtex-autokey
635 :type '(choice (const :tag "All" infty)
638 (defcustom bibtex-autokey-name-separator ""
639 "String that comes between any two names in the key.
640 See `bibtex-generate-autokey' for details."
641 :group 'bibtex-autokey
644 (defcustom bibtex-autokey-year-length 2
645 "Number of rightmost digits from the year field to incorporate into key.
646 See `bibtex-generate-autokey' for details."
647 :group 'bibtex-autokey
650 (defcustom bibtex-autokey-use-crossref t
651 "If non-nil use fields from crossreferenced entry if necessary.
652 If this variable is non-nil and some field has no entry, but a
653 valid crossref entry, the field from the crossreferenced entry is used.
654 See `bibtex-generate-autokey' for details."
655 :group 'bibtex-autokey
658 (defcustom bibtex-autokey-titlewords 5
659 "Number of title words to use for the automatically generated reference key.
660 If this is set to anything but a number, all title words are used.
661 Possibly more words from the title are used according to
662 `bibtex-autokey-titlewords-stretch'.
663 See `bibtex-generate-autokey' for details."
664 :group 'bibtex-autokey
665 :type '(choice (const :tag "All" infty)
668 (defcustom bibtex-autokey-title-terminators "[.!?:;]\\|--"
669 "Regexp defining the termination of the main part of the title.
670 Case of the regexps is ignored. See `bibtex-generate-autokey' for details."
671 :group 'bibtex-autokey
674 (defcustom bibtex-autokey-titlewords-stretch 2
675 "Number of words that can additionally be used from the title.
676 These words are used only, if a sentence from the title can be ended then.
677 See `bibtex-generate-autokey' for details."
678 :group 'bibtex-autokey
681 (defcustom bibtex-autokey-titleword-ignore
682 '("A" "An" "On" "The" "Eine?" "Der" "Die" "Das"
683 "[^[:upper:]].*" ".*[^[:upper:]0-9].*")
684 "Determines words from the title that are not to be used in the key.
685 Each item of the list is a regexp. If a word of the title matches a
686 regexp from that list, it is not included in the title part of the key.
687 See `bibtex-generate-autokey' for details."
688 :group 'bibtex-autokey
689 :type '(repeat regexp))
691 (defcustom bibtex-autokey-titleword-case-convert-function 'downcase
692 "Function called for each titleword to perform case conversion.
693 See `bibtex-generate-autokey' for details."
694 :group 'bibtex-autokey
695 :type '(choice (const :tag "Preserve case" identity)
696 (const :tag "Downcase" downcase)
697 (const :tag "Capitalize" capitalize)
698 (const :tag "Upcase" upcase)
699 (function :tag "Conversion function")))
700 (defvaralias 'bibtex-autokey-titleword-case-convert
701 'bibtex-autokey-titleword-case-convert-function)
703 (defcustom bibtex-autokey-titleword-abbrevs nil
704 "Determines exceptions to the usual abbreviation mechanism.
705 An alist of (OLD-REGEXP . NEW-STRING) pairs. Case is ignored
706 in matching against OLD-REGEXP, and the first matching pair is used.
707 See `bibtex-generate-autokey' for details."
708 :group 'bibtex-autokey
709 :type '(repeat (cons (regexp :tag "Old")
710 (string :tag "New"))))
712 (defcustom bibtex-autokey-titleword-change-strings
713 bibtex-autokey-transcriptions
714 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
715 Any part of title word matching a OLD-REGEXP is replaced by NEW-STRING.
716 Case is significant in OLD-REGEXP. All regexps are tried in the
717 order in which they appear in the list.
718 See `bibtex-generate-autokey' for details."
719 :group 'bibtex-autokey
720 :type '(repeat (cons (regexp :tag "Old")
721 (string :tag "New"))))
723 (defcustom bibtex-autokey-titleword-length 5
724 "Number of characters from title words to incorporate into key.
725 If this is set to anything but a number, all characters are used.
726 See `bibtex-generate-autokey' for details."
727 :group 'bibtex-autokey
728 :type '(choice (const :tag "All" infty)
731 (defcustom bibtex-autokey-titleword-separator "_"
732 "String to be put between the title words.
733 See `bibtex-generate-autokey' for details."
734 :group 'bibtex-autokey
737 (defcustom bibtex-autokey-name-year-separator ""
738 "String to be put between name part and year part of key.
739 See `bibtex-generate-autokey' for details."
740 :group 'bibtex-autokey
743 (defcustom bibtex-autokey-year-title-separator ":_"
744 "String to be put between name part and year part of key.
745 See `bibtex-generate-autokey' for details."
746 :group 'bibtex-autokey
749 (defcustom bibtex-autokey-edit-before-use t
750 "If non-nil, user is allowed to edit the generated key before it is used."
751 :group 'bibtex-autokey
754 (defcustom bibtex-autokey-before-presentation-function nil
755 "If non-nil, function to call before generated key is presented.
756 The function must take one argument (the automatically generated key),
757 and must return a string (the key to use)."
758 :group 'bibtex-autokey
759 :type '(choice (const nil) function))
761 (defcustom bibtex-entry-offset 0
762 "Offset for BibTeX entries.
763 Added to the value of all other variables which determine columns."
767 (defcustom bibtex-field-indentation 2
768 "Starting column for the name part in BibTeX fields."
772 (defcustom bibtex-text-indentation
773 (+ bibtex-field-indentation
774 (length "organization = "))
775 "Starting column for the text part in BibTeX fields.
776 Should be equal to the space needed for the longest name part."
780 (defcustom bibtex-contline-indentation
781 (+ bibtex-text-indentation 1)
782 "Starting column for continuation lines of BibTeX fields."
786 (defcustom bibtex-align-at-equal-sign nil
787 "If non-nil, align fields at equal sign instead of field text.
788 If non-nil, the column for the equal sign is the value of
789 `bibtex-text-indentation', minus 2."
793 (defcustom bibtex-comma-after-last-field nil
794 "If non-nil, a comma is put at end of last field in the entry template."
798 (defcustom bibtex-autoadd-commas t
799 "If non-nil automatically add missing commas at end of BibTeX fields."
803 (defcustom bibtex-autofill-types '("Proceedings")
804 "Automatically fill fields if possible for those BibTeX entry types."
806 :type '(repeat string))
808 (defcustom bibtex-summary-function 'bibtex-summary
809 "Function to call for generating a summary of current BibTeX entry.
810 It takes no arguments. Point must be at beginning of entry.
811 Used by `bibtex-complete-crossref-cleanup' and `bibtex-copy-summary-as-kill'."
813 :type '(choice (const :tag "Default" bibtex-summary)
814 (function :tag "Personalized function")))
816 (defcustom bibtex-generate-url-list
817 '((("url" . ".*:.*")))
818 "List of schemes for generating the URL of a BibTeX entry.
819 These schemes are used by `bibtex-url'.
821 Each scheme should have one of these forms:
824 ((FIELD . REGEXP) STEP...)
825 ((FIELD . REGEXP) STRING STEP...)
827 FIELD is a field name as returned by `bibtex-parse-entry'.
828 REGEXP is matched against the text of FIELD. If the match succeeds,
829 then this scheme is used. If no STRING and STEPs are specified
830 the matched text is used as the URL, otherwise the URL is built
831 by evaluating STEPs. If no STRING is specified the STEPs must result
832 in strings which are concatenated. Otherwise the resulting objects
833 are passed through `format' using STRING as format control string.
835 A STEP is a list (FIELD REGEXP REPLACE). The text of FIELD
836 is matched against REGEXP, and is replaced with REPLACE.
837 REPLACE can be a string, or a number (which selects the corresponding
838 submatch), or a function called with the field's text as argument
839 and with the `match-data' properly set.
841 Case is always ignored. Always remove the field delimiters.
842 If `bibtex-expand-strings' is non-nil, BibTeX strings are expanded
843 for generating the URL.
845 The following is a complex example, see http://link.aps.org/linkfaq.html.
847 (((\"journal\" . \"\\\\=<\\(PR[ABCDEL]?\\|RMP\\)\\\\=>\")
848 \"http://link.aps.org/abstract/%s/v%s/p%s\"
849 (\"journal\" \".*\" downcase)
850 (\"volume\" \".*\" 0)
851 (\"pages\" \"\\`[A-Z]?[0-9]+\" 0)))"
855 (cons :tag "Matcher" :extra-offset 4
856 (string :tag "BibTeX field")
857 (regexp :tag "Regexp"))
859 (const :tag "Take match as is" nil)
860 (cons :tag "Formatted"
861 (string :tag "Format control string")
862 (repeat :tag "Steps to generate URL"
863 (list (string :tag "BibTeX field")
864 (regexp :tag "Regexp")
865 (choice (string :tag "Replacement")
866 (integer :tag "Sub-match")
867 (function :tag "Filter")))))
868 (repeat :tag "Concatenated"
869 (list (string :tag "BibTeX field")
870 (regexp :tag "Regexp")
871 (choice (string :tag "Replacement")
872 (integer :tag "Sub-match")
873 (function :tag "Filter"))))))))
874 (put 'bibtex-generate-url-list 'risky-local-variable t)
876 (defcustom bibtex-expand-strings nil
877 "If non-nil, expand strings when extracting the content of a BibTeX field."
881 ;; `bibtex-font-lock-keywords' is a user option, too. But since the
882 ;; patterns used to define this variable are defined in a later
883 ;; section of this file, it is defined later.
886 ;; Syntax Table and Keybindings
887 (defvar bibtex-mode-syntax-table
888 (let ((st (make-syntax-table)))
889 (modify-syntax-entry ?\" "\"" st)
890 (modify-syntax-entry ?$ "$$ " st)
891 (modify-syntax-entry ?% "< " st)
892 (modify-syntax-entry ?' "w " st)
893 (modify-syntax-entry ?@ "w " st)
894 (modify-syntax-entry ?\\ "\\" st)
895 (modify-syntax-entry ?\f "> " st)
896 (modify-syntax-entry ?\n "> " st)
897 ;; Keys cannot have = in them (wrong font-lock of @string{foo=bar}).
898 (modify-syntax-entry ?= "." st)
899 (modify-syntax-entry ?~ " " st)
901 "Syntax table used in BibTeX mode buffers.")
903 (defvar bibtex-mode-map
904 (let ((km (make-sparse-keymap)))
905 ;; The Key `C-c&' is reserved for reftex.el
906 (define-key km "\t" 'bibtex-find-text)
907 (define-key km "\n" 'bibtex-next-field)
908 (define-key km "\M-\t" 'bibtex-complete)
909 (define-key km "\C-c\"" 'bibtex-remove-delimiters)
910 (define-key km "\C-c{" 'bibtex-remove-delimiters)
911 (define-key km "\C-c}" 'bibtex-remove-delimiters)
912 (define-key km "\C-c\C-c" 'bibtex-clean-entry)
913 (define-key km "\C-c\C-q" 'bibtex-fill-entry)
914 (define-key km "\C-c\C-s" 'bibtex-find-entry)
915 (define-key km "\C-c\C-x" 'bibtex-find-crossref)
916 (define-key km "\C-c\C-t" 'bibtex-copy-summary-as-kill)
917 (define-key km "\C-c?" 'bibtex-print-help-message)
918 (define-key km "\C-c\C-p" 'bibtex-pop-previous)
919 (define-key km "\C-c\C-n" 'bibtex-pop-next)
920 (define-key km "\C-c\C-k" 'bibtex-kill-field)
921 (define-key km "\C-c\M-k" 'bibtex-copy-field-as-kill)
922 (define-key km "\C-c\C-w" 'bibtex-kill-entry)
923 (define-key km "\C-c\M-w" 'bibtex-copy-entry-as-kill)
924 (define-key km "\C-c\C-y" 'bibtex-yank)
925 (define-key km "\C-c\M-y" 'bibtex-yank-pop)
926 (define-key km "\C-c\C-d" 'bibtex-empty-field)
927 (define-key km "\C-c\C-f" 'bibtex-make-field)
928 (define-key km "\C-c\C-u" 'bibtex-entry-update)
929 (define-key km "\C-c$" 'bibtex-ispell-abstract)
930 (define-key km "\M-\C-a" 'bibtex-beginning-of-entry)
931 (define-key km "\M-\C-e" 'bibtex-end-of-entry)
932 (define-key km "\C-\M-l" 'bibtex-reposition-window)
933 (define-key km "\C-\M-h" 'bibtex-mark-entry)
934 (define-key km "\C-c\C-b" 'bibtex-entry)
935 (define-key km "\C-c\C-rn" 'bibtex-narrow-to-entry)
936 (define-key km "\C-c\C-rw" 'widen)
937 (define-key km "\C-c\C-l" 'bibtex-url)
938 (define-key km "\C-c\C-o" 'bibtex-remove-OPT-or-ALT)
939 (define-key km "\C-c\C-e\C-i" 'bibtex-InProceedings)
940 (define-key km "\C-c\C-ei" 'bibtex-InCollection)
941 (define-key km "\C-c\C-eI" 'bibtex-InBook)
942 (define-key km "\C-c\C-e\C-a" 'bibtex-Article)
943 (define-key km "\C-c\C-e\C-b" 'bibtex-InBook)
944 (define-key km "\C-c\C-eb" 'bibtex-Book)
945 (define-key km "\C-c\C-eB" 'bibtex-Booklet)
946 (define-key km "\C-c\C-e\C-c" 'bibtex-InCollection)
947 (define-key km "\C-c\C-e\C-m" 'bibtex-Manual)
948 (define-key km "\C-c\C-em" 'bibtex-MastersThesis)
949 (define-key km "\C-c\C-eM" 'bibtex-Misc)
950 (define-key km "\C-c\C-e\C-p" 'bibtex-InProceedings)
951 (define-key km "\C-c\C-ep" 'bibtex-Proceedings)
952 (define-key km "\C-c\C-eP" 'bibtex-PhdThesis)
953 (define-key km "\C-c\C-e\M-p" 'bibtex-Preamble)
954 (define-key km "\C-c\C-e\C-s" 'bibtex-String)
955 (define-key km "\C-c\C-e\C-t" 'bibtex-TechReport)
956 (define-key km "\C-c\C-e\C-u" 'bibtex-Unpublished)
958 "Keymap used in BibTeX mode.")
961 bibtex-edit-menu bibtex-mode-map "BibTeX-Edit Menu in BibTeX mode"
963 ("Moving inside an Entry"
964 ["End of Field" bibtex-find-text t]
965 ["Next Field" bibtex-next-field t]
966 ["Beginning of Entry" bibtex-beginning-of-entry t]
967 ["End of Entry" bibtex-end-of-entry t]
969 ["Make Entry Visible" bibtex-reposition-window t])
970 ("Moving in BibTeX Buffers"
971 ["Find Entry" bibtex-find-entry t]
972 ["Find Crossref Entry" bibtex-find-crossref t])
974 ("Operating on Current Field"
975 ["Fill Field" fill-paragraph t]
976 ["Remove Delimiters" bibtex-remove-delimiters t]
977 ["Remove OPT or ALT Prefix" bibtex-remove-OPT-or-ALT t]
978 ["Clear Field" bibtex-empty-field t]
980 ["Kill Field" bibtex-kill-field t]
981 ["Copy Field to Kill Ring" bibtex-copy-field-as-kill t]
982 ["Paste Most Recently Killed Field" bibtex-yank t]
983 ["Paste Previously Killed Field" bibtex-yank-pop t]
985 ["Make New Field" bibtex-make-field t]
987 ["Snatch from Similar Following Field" bibtex-pop-next t]
988 ["Snatch from Similar Preceding Field" bibtex-pop-previous t]
990 ["String or Key Complete" bibtex-complete t]
992 ["Help about Current Field" bibtex-print-help-message t])
993 ("Operating on Current Entry"
994 ["Fill Entry" bibtex-fill-entry t]
995 ["Clean Entry" bibtex-clean-entry t]
996 ["Update Entry" bibtex-entry-update t]
998 ["Kill Entry" bibtex-kill-entry t]
999 ["Copy Entry to Kill Ring" bibtex-copy-entry-as-kill t]
1000 ["Paste Most Recently Killed Entry" bibtex-yank t]
1001 ["Paste Previously Killed Entry" bibtex-yank-pop t]
1003 ["Copy Summary to Kill Ring" bibtex-copy-summary-as-kill t]
1004 ["Browse URL" bibtex-url t]
1006 ["Ispell Entry" bibtex-ispell-entry t]
1007 ["Ispell Entry Abstract" bibtex-ispell-abstract t]
1009 ["Narrow to Entry" bibtex-narrow-to-entry t]
1010 ["Mark Entry" bibtex-mark-entry t]
1012 ["View Cite Locations (RefTeX)" reftex-view-crossref-from-bibtex
1013 (fboundp 'reftex-view-crossref-from-bibtex)])
1014 ("Operating on Buffer or Region"
1015 ["Validate Entries" bibtex-validate t]
1016 ["Sort Entries" bibtex-sort-buffer t]
1017 ["Reformat Entries" bibtex-reformat t]
1018 ["Count Entries" bibtex-count-entries t]
1020 ["Convert Alien Buffer" bibtex-convert-alien t])
1021 ("Operating on Multiple Buffers"
1022 ["Validate Entries" bibtex-validate-globally t])))
1025 bibtex-entry-menu bibtex-mode-map "Entry-Types Menu in BibTeX mode"
1027 ["Article in Journal" bibtex-Article t]
1028 ["Article in Conference Proceedings" bibtex-InProceedings t]
1029 ["Article in a Collection" bibtex-InCollection t]
1030 ["Chapter or Pages in a Book" bibtex-InBook t]
1031 ["Conference Proceedings" bibtex-Proceedings t]
1032 ["Book" bibtex-Book t]
1033 ["Booklet (Bound, but no Publisher/Institution)" bibtex-Booklet t]
1034 ["PhD. Thesis" bibtex-PhdThesis t]
1035 ["Master's Thesis" bibtex-MastersThesis t]
1036 ["Technical Report" bibtex-TechReport t]
1037 ["Technical Manual" bibtex-Manual t]
1038 ["Unpublished" bibtex-Unpublished t]
1039 ["Miscellaneous" bibtex-Misc t]
1041 ["String" bibtex-String t]
1042 ["Preamble" bibtex-Preamble t]))
1045 ;; Internal Variables
1047 (defvar bibtex-pop-previous-search-point nil
1048 "Next point where `bibtex-pop-previous' starts looking for a similar entry.")
1050 (defvar bibtex-pop-next-search-point nil
1051 "Next point where `bibtex-pop-next' starts looking for a similar entry.")
1053 (defvar bibtex-field-kill-ring nil
1054 "Ring of least recently killed fields.
1055 At most `bibtex-field-kill-ring-max' items are kept here.")
1057 (defvar bibtex-field-kill-ring-yank-pointer nil
1058 "The tail of `bibtex-field-kill-ring' whose car is the last item yanked.")
1060 (defvar bibtex-entry-kill-ring nil
1061 "Ring of least recently killed entries.
1062 At most `bibtex-entry-kill-ring-max' items are kept here.")
1064 (defvar bibtex-entry-kill-ring-yank-pointer nil
1065 "The tail of `bibtex-entry-kill-ring' whose car is the last item yanked.")
1067 (defvar bibtex-last-kill-command nil
1068 "Type of the last kill command (either 'field or 'entry).")
1070 (defvar bibtex-strings
1071 (lazy-completion-table bibtex-strings
1073 (bibtex-parse-strings (bibtex-string-files-init))))
1074 "Completion table for BibTeX string keys.
1075 Initialized from `bibtex-predefined-strings' and `bibtex-string-files'.")
1076 (make-variable-buffer-local 'bibtex-strings)
1077 (put 'bibtex-strings 'risky-local-variable t)
1079 (defvar bibtex-reference-keys
1080 (lazy-completion-table bibtex-reference-keys
1081 (lambda () (bibtex-parse-keys nil t)))
1082 "Completion table for BibTeX reference keys.
1083 The CDRs of the elements are t for header keys and nil for crossref keys.")
1084 (make-variable-buffer-local 'bibtex-reference-keys)
1085 (put 'bibtex-reference-keys 'risky-local-variable t)
1087 (defvar bibtex-buffer-last-parsed-tick nil
1088 "Value of `buffer-modified-tick' last time buffer was parsed for keys.")
1090 (defvar bibtex-parse-idle-timer nil
1091 "Stores if timer is already installed.")
1093 (defvar bibtex-progress-lastperc nil
1094 "Last reported percentage for the progress message.")
1096 (defvar bibtex-progress-lastmes nil
1097 "Last reported progress message.")
1099 (defvar bibtex-progress-interval nil
1100 "Interval for progress messages.")
1102 (defvar bibtex-key-history nil
1103 "History list for reading keys.")
1105 (defvar bibtex-entry-type-history nil
1106 "History list for reading entry types.")
1108 (defvar bibtex-field-history nil
1109 "History list for reading field names.")
1111 (defvar bibtex-reformat-previous-options nil
1112 "Last reformat options given.")
1114 (defvar bibtex-reformat-previous-reference-keys nil
1115 "Last reformat reference keys option given.")
1117 (defconst bibtex-field-name "[^\"#%'(),={} \t\n0-9][^\"#%'(),={} \t\n]*"
1118 "Regexp matching the name of a BibTeX field.")
1120 (defconst bibtex-name-part
1121 (concat ",[ \t\n]*\\(" bibtex-field-name "\\)")
1122 "Regexp matching the name part of a BibTeX field.")
1124 (defconst bibtex-reference-key "[][[:alnum:].:;?!`'/*@+|()<>&_^$-]+"
1125 "Regexp matching the reference key part of a BibTeX entry.")
1127 (defconst bibtex-field-const "[][[:alnum:].:;?!`'/*@+=|<>&_^$-]+"
1128 "Regexp matching a BibTeX field constant.")
1130 (defvar bibtex-entry-type
1131 (concat "@[ \t]*\\(?:"
1132 (regexp-opt (mapcar 'car bibtex-entry-field-alist)) "\\)")
1133 "Regexp matching the name of a BibTeX entry.")
1135 (defvar bibtex-entry-head
1136 (concat "^[ \t]*\\("
1138 "\\)[ \t]*[({][ \t\n]*\\("
1139 bibtex-reference-key
1141 "Regexp matching the header line of a BibTeX entry (including key).")
1143 (defvar bibtex-entry-maybe-empty-head
1144 (concat bibtex-entry-head "?")
1145 "Regexp matching the header line of a BibTeX entry (possibly without key).")
1147 (defconst bibtex-any-entry-maybe-empty-head
1148 (concat "^[ \t]*\\(@[ \t]*" bibtex-field-name "\\)[ \t]*[({][ \t\n]*\\("
1149 bibtex-reference-key "\\)?")
1150 "Regexp matching the header line of any BibTeX entry (possibly without key).")
1152 (defvar bibtex-any-valid-entry-type
1153 (concat "^[ \t]*@[ \t]*\\(?:"
1154 (regexp-opt (append '("String" "Preamble")
1155 (mapcar 'car bibtex-entry-field-alist))) "\\)")
1156 "Regexp matching any valid BibTeX entry (including String and Preamble).")
1158 (defconst bibtex-type-in-head 1
1159 "Regexp subexpression number of the type part in `bibtex-entry-head'.")
1161 (defconst bibtex-key-in-head 2
1162 "Regexp subexpression number of the key part in `bibtex-entry-head'.")
1164 (defconst bibtex-string-type "^[ \t]*\\(@[ \t]*String\\)[ \t]*[({][ \t\n]*"
1165 "Regexp matching the name of a BibTeX String entry.")
1167 (defconst bibtex-string-maybe-empty-head
1168 (concat bibtex-string-type "\\(" bibtex-reference-key "\\)?")
1169 "Regexp matching the header line of a BibTeX String entry.")
1171 (defconst bibtex-preamble-prefix
1172 "[ \t]*\\(@[ \t]*Preamble\\)[ \t]*[({][ \t\n]*"
1173 "Regexp matching the prefix part of a BibTeX Preamble entry.")
1175 (defconst bibtex-font-lock-syntactic-keywords
1176 `((,(concat "^[ \t]*\\(" (substring bibtex-comment-start 0 1) "\\)"
1177 (substring bibtex-comment-start 1) "\\>")
1180 (defvar bibtex-font-lock-keywords
1181 ;; entry type and reference key
1182 `((,bibtex-any-entry-maybe-empty-head
1183 (,bibtex-type-in-head font-lock-function-name-face)
1184 (,bibtex-key-in-head font-lock-constant-face nil t))
1185 ;; optional field names (treated as comments)
1186 (,(concat "^[ \t]*\\(OPT" bibtex-field-name "\\)[ \t]*=")
1187 1 font-lock-comment-face)
1189 (,(concat "^[ \t]*\\(" bibtex-field-name "\\)[ \t]*=")
1190 1 font-lock-variable-name-face)
1192 (bibtex-font-lock-url) (bibtex-font-lock-crossref))
1193 "*Default expressions to highlight in BibTeX mode.")
1195 (defvar bibtex-font-lock-url-regexp
1196 ;; Assume that field names begin at the beginning of a line.
1198 (regexp-opt (delete-dups (mapcar 'caar bibtex-generate-url-list)) t)
1200 "Regexp for `bibtex-font-lock-url'.")
1202 (defvar bibtex-string-empty-key nil
1203 "If non-nil, `bibtex-parse-string' accepts empty key.")
1205 (defvar bibtex-sort-entry-class-alist nil
1206 "Alist mapping entry types to their sorting index.
1207 Auto-generated from `bibtex-sort-entry-class'.
1208 Used when `bibtex-maintain-sorted-entries' is `entry-class'.")
1211 ;; Support for hideshow minor mode
1212 (defun bibtex-hs-forward-sexp (arg)
1213 "Replacement for `forward-sexp' to be used by `hs-minor-mode'.
1215 (if (looking-at "@\\S(*\\s(")
1216 (goto-char (1- (match-end 0))))
1220 'hs-special-modes-alist
1221 '(bibtex-mode "@\\S(*\\s(" "\\s)" nil bibtex-hs-forward-sexp nil))
1224 (defun bibtex-parse-association (parse-lhs parse-rhs)
1225 "Parse a string of the format <left-hand-side = right-hand-side>.
1226 The functions PARSE-LHS and PARSE-RHS are used to parse the corresponding
1227 substrings. These functions are expected to return nil if parsing is not
1228 successful. If the returned values of both functions are non-nil,
1229 return a cons pair of these values. Do not move point."
1232 (let ((left (funcall parse-lhs))
1235 (looking-at "[ \t\n]*=[ \t\n]*")
1236 (goto-char (match-end 0))
1237 (setq right (funcall parse-rhs)))
1238 (cons left right))))))
1240 (defun bibtex-parse-field-name ()
1241 "Parse the name part of a BibTeX field.
1242 If the field name is found, return a triple consisting of the position of the
1243 very first character of the match, the actual starting position of the name
1244 part and end position of the match. Move point to end of field name.
1245 If `bibtex-autoadd-commas' is non-nil add missing comma at end of preceding
1246 BibTeX field as necessary."
1247 (cond ((looking-at bibtex-name-part)
1248 (goto-char (match-end 0))
1249 (list (match-beginning 0) (match-beginning 1) (match-end 0)))
1250 ;; Maybe add a missing comma.
1251 ((and bibtex-autoadd-commas
1252 (looking-at (concat "[ \t\n]*\\(?:" bibtex-field-name
1254 (skip-chars-backward " \t\n")
1255 ;; It can be confusing if non-editing commands try to
1256 ;; modify the buffer.
1257 (if buffer-read-only
1258 (error "Comma missing at buffer position %s" (point)))
1262 (bibtex-parse-field-name))))
1264 (defconst bibtex-braced-string-syntax-table
1265 (let ((st (make-syntax-table)))
1266 (modify-syntax-entry ?\{ "(}" st)
1267 (modify-syntax-entry ?\} "){" st)
1268 (modify-syntax-entry ?\[ "." st)
1269 (modify-syntax-entry ?\] "." st)
1270 (modify-syntax-entry ?\( "." st)
1271 (modify-syntax-entry ?\) "." st)
1272 (modify-syntax-entry ?\\ "." st)
1273 (modify-syntax-entry ?\" "." st)
1275 "Syntax-table to parse matched braces.")
1277 (defconst bibtex-quoted-string-syntax-table
1278 (let ((st (make-syntax-table)))
1279 (modify-syntax-entry ?\\ "\\" st)
1280 (modify-syntax-entry ?\" "\"" st)
1282 "Syntax-table to parse matched quotes.")
1284 (defun bibtex-parse-field-string ()
1285 "Parse a BibTeX field string enclosed by braces or quotes.
1286 If a syntactically correct string is found, a pair containing the start and
1287 end position of the field string is returned, nil otherwise.
1290 (or (and (eq (following-char) ?\")
1292 (with-syntax-table bibtex-quoted-string-syntax-table
1295 (and (eq (following-char) ?\{)
1297 (with-syntax-table bibtex-braced-string-syntax-table
1301 (cons (point) end-point))))
1303 (defun bibtex-parse-field-text ()
1304 "Parse the text part of a BibTeX field.
1305 The text part is either a string, or an empty string, or a constant followed
1306 by one or more <# (string|constant)> pairs. If a syntactically correct text
1307 is found, a pair containing the start and end position of the text is
1308 returned, nil otherwise. Move point to end of field text."
1309 (let ((starting-point (point))
1310 end-point failure boundaries)
1311 (while (not (or end-point failure))
1312 (cond ((looking-at bibtex-field-const)
1313 (goto-char (match-end 0)))
1314 ((setq boundaries (bibtex-parse-field-string))
1315 (goto-char (cdr boundaries)))
1317 (if (looking-at "[ \t\n]*#[ \t\n]*")
1318 (goto-char (match-end 0))
1319 (setq end-point (point))))
1320 (skip-chars-forward " \t\n")
1321 (if (and (not failure)
1323 (list starting-point end-point (point)))))
1325 (defun bibtex-parse-field ()
1326 "Parse the BibTeX field beginning at the position of point.
1327 If a syntactically correct field is found, return a cons pair containing
1328 the boundaries of the name and text parts of the field. Do not move point."
1329 (bibtex-parse-association 'bibtex-parse-field-name
1330 'bibtex-parse-field-text))
1332 (defsubst bibtex-start-of-field (bounds)
1333 (nth 0 (car bounds)))
1334 (defsubst bibtex-start-of-name-in-field (bounds)
1335 (nth 1 (car bounds)))
1336 (defsubst bibtex-end-of-name-in-field (bounds)
1337 (nth 2 (car bounds)))
1338 (defsubst bibtex-start-of-text-in-field (bounds)
1340 (defsubst bibtex-end-of-text-in-field (bounds)
1342 (defsubst bibtex-end-of-field (bounds)
1345 (defun bibtex-search-forward-field (name &optional bound)
1346 "Search forward to find a BibTeX field of name NAME.
1347 If a syntactically correct field is found, return a pair containing
1348 the boundaries of the name and text parts of the field. The search
1349 is limited by optional arg BOUND. If BOUND is t the search is limited
1350 by the end of the current entry. Do not move point."
1354 (let ((regexp (concat bibtex-name-part "[ \t\n]*=\\|"
1355 bibtex-any-entry-maybe-empty-head))
1356 (case-fold-search t) bounds)
1358 (if (looking-at "[ \t]*@") (goto-char (match-end 0)))
1359 (while (and (not bounds)
1360 (re-search-forward regexp nil t))
1361 (if (match-beginning 2)
1362 ;; We found a new entry
1365 (goto-char (match-beginning 0))
1366 (setq bounds (bibtex-parse-field))))
1367 ;; Step through all fields so that we cannot overshoot.
1369 (goto-char (bibtex-start-of-name-in-field bounds))
1370 (if (looking-at name) (throw 'done bounds))
1371 (goto-char (bibtex-end-of-field bounds))
1372 (setq bounds (bibtex-parse-field)))))
1373 ;; Bounded search or bound is nil (i.e. we cannot overshoot).
1374 ;; Indeed, the search is bounded when `bibtex-search-forward-field'
1375 ;; is called many times. So we optimize this part of this function.
1376 (let ((name-part (concat ",[ \t\n]*\\(" name "\\)[ \t\n]*=[ \t\n]*"))
1377 (case-fold-search t) left right)
1378 (while (and (not right)
1379 (re-search-forward name-part bound t))
1380 (setq left (list (match-beginning 0) (match-beginning 1)
1382 ;; Don't worry that the field text could be past bound.
1383 right (bibtex-parse-field-text)))
1384 (if right (cons left right)))))))
1386 (defun bibtex-search-backward-field (name &optional bound)
1387 "Search backward to find a BibTeX field of name NAME.
1388 If a syntactically correct field is found, return a pair containing
1389 the boundaries of the name and text parts of the field. The search
1390 is limited by the optional arg BOUND. If BOUND is t the search is
1391 limited by the beginning of the current entry. Do not move point."
1394 (setq bound (save-excursion (bibtex-beginning-of-entry))))
1395 (let ((name-part (concat ",[ \t\n]*\\(" name "\\)[ \t\n]*=[ \t\n]*"))
1396 (case-fold-search t) left right)
1398 ;; the parsing functions are not designed for parsing backwards :-(
1399 (when (search-backward "," bound t)
1401 (when (looking-at name-part)
1402 (setq left (list (match-beginning 0) (match-beginning 1)
1404 (goto-char (match-end 0))
1405 (setq right (bibtex-parse-field-text))))
1406 (while (and (not right)
1407 (re-search-backward name-part bound t))
1408 (setq left (list (match-beginning 0) (match-beginning 1)
1411 (goto-char (match-end 0))
1412 (setq right (bibtex-parse-field-text)))))
1413 (if right (cons left right)))))))
1415 (defun bibtex-name-in-field (bounds &optional remove-opt-alt)
1416 "Get content of name in BibTeX field defined via BOUNDS.
1417 If optional arg REMOVE-OPT-ALT is non-nil remove \"OPT\" and \"ALT\"."
1418 (let ((name (buffer-substring-no-properties
1419 (bibtex-start-of-name-in-field bounds)
1420 (bibtex-end-of-name-in-field bounds))))
1421 (if (and remove-opt-alt
1422 (string-match "\\`\\(OPT\\|ALT\\)" name))
1426 (defun bibtex-text-in-field-bounds (bounds &optional content)
1427 "Get text in BibTeX field defined via BOUNDS.
1428 If optional arg CONTENT is non-nil extract content of field
1429 by removing field delimiters and concatenating the resulting string.
1430 If `bibtex-expand-strings' is non-nil, also expand BibTeX strings."
1433 (goto-char (bibtex-start-of-text-in-field bounds))
1434 (let ((epoint (bibtex-end-of-text-in-field bounds))
1436 (while (< (setq opoint (point)) epoint)
1437 (if (looking-at bibtex-field-const)
1438 (let ((mtch (match-string-no-properties 0)))
1439 (push (or (if bibtex-expand-strings
1440 (cdr (assoc-string mtch (bibtex-strings) t)))
1442 (goto-char (match-end 0)))
1443 (let ((bounds (bibtex-parse-field-string)))
1444 (push (buffer-substring-no-properties
1445 (1+ (car bounds)) (1- (cdr bounds))) content)
1446 (goto-char (cdr bounds))))
1447 (re-search-forward "\\=[ \t\n]*#[ \t\n]*" nil t))
1448 (apply 'concat (nreverse content))))
1449 (buffer-substring-no-properties (bibtex-start-of-text-in-field bounds)
1450 (bibtex-end-of-text-in-field bounds))))
1452 (defun bibtex-text-in-field (field &optional follow-crossref)
1453 "Get content of field FIELD of current BibTeX entry.
1454 Return nil if not found.
1455 If optional arg FOLLOW-CROSSREF is non-nil, follow crossref."
1457 (let* ((end (if follow-crossref (bibtex-end-of-entry) t))
1458 (beg (bibtex-beginning-of-entry)) ; move point
1459 (bounds (bibtex-search-forward-field field end)))
1460 (cond (bounds (bibtex-text-in-field-bounds bounds t))
1461 ((and follow-crossref
1462 (progn (goto-char beg)
1463 (setq bounds (bibtex-search-forward-field
1464 "\\(OPT\\)?crossref" end))))
1465 (let ((crossref-field (bibtex-text-in-field-bounds bounds t)))
1466 (if (bibtex-find-crossref crossref-field)
1467 ;; Do not pass FOLLOW-CROSSREF because we want
1468 ;; to follow crossrefs only one level of recursion.
1469 (bibtex-text-in-field field))))))))
1471 (defun bibtex-parse-string-prefix ()
1472 "Parse the prefix part of a BibTeX string entry, including reference key.
1473 If the string prefix is found, return a triple consisting of the position of
1474 the very first character of the match, the actual starting position of the
1475 reference key and the end position of the match.
1476 If `bibtex-string-empty-key' is non-nil accept empty string key."
1477 (let ((case-fold-search t))
1478 (if (looking-at bibtex-string-type)
1479 (let ((start (point)))
1480 (goto-char (match-end 0))
1481 (cond ((looking-at bibtex-reference-key)
1482 (goto-char (match-end 0))
1486 ((and bibtex-string-empty-key
1488 (skip-chars-backward " \t\n")
1489 (list start (point) (point))))))))
1491 (defun bibtex-parse-string-postfix ()
1492 "Parse the postfix part of a BibTeX string entry, including the text.
1493 If the string postfix is found, return a triple consisting of the position of
1494 the actual starting and ending position of the text and the very last
1495 character of the string entry. Move point past BibTeX string entry."
1496 (let* ((case-fold-search t)
1497 (bounds (bibtex-parse-field-text)))
1499 (goto-char (nth 1 bounds))
1500 (when (looking-at "[ \t\n]*[})]")
1501 (goto-char (match-end 0))
1506 (defun bibtex-parse-string (&optional empty-key)
1507 "Parse a BibTeX string entry beginning at the position of point.
1508 If a syntactically correct entry is found, return a cons pair containing
1509 the boundaries of the reference key and text parts of the entry.
1510 If EMPTY-KEY is non-nil, key may be empty. Do not move point."
1511 (let ((bibtex-string-empty-key empty-key))
1512 (bibtex-parse-association 'bibtex-parse-string-prefix
1513 'bibtex-parse-string-postfix)))
1515 (defun bibtex-search-forward-string (&optional empty-key)
1516 "Search forward to find a BibTeX string entry.
1517 If a syntactically correct entry is found, a pair containing the boundaries of
1518 the reference key and text parts of the string is returned.
1519 If EMPTY-KEY is non-nil, key may be empty. Do not move point."
1522 (let ((case-fold-search t) bounds)
1523 (while (and (not bounds)
1524 (search-forward-regexp bibtex-string-type nil t))
1525 (save-excursion (goto-char (match-beginning 0))
1526 (setq bounds (bibtex-parse-string empty-key))))
1529 (defun bibtex-reference-key-in-string (bounds)
1530 "Return the key part of a BibTeX string defined via BOUNDS"
1531 (buffer-substring-no-properties (nth 1 (car bounds))
1532 (nth 2 (car bounds))))
1534 (defun bibtex-text-in-string (bounds &optional content)
1535 "Get text in BibTeX string field defined via BOUNDS.
1536 If optional arg CONTENT is non-nil extract content
1537 by removing field delimiters and concatenating the resulting string.
1538 If `bibtex-expand-strings' is non-nil, also expand BibTeX strings."
1539 (bibtex-text-in-field-bounds bounds content))
1541 (defsubst bibtex-start-of-text-in-string (bounds)
1542 (nth 0 (cdr bounds)))
1543 (defsubst bibtex-end-of-text-in-string (bounds)
1544 (nth 1 (cdr bounds)))
1545 (defsubst bibtex-end-of-string (bounds)
1546 (nth 2 (cdr bounds)))
1548 (defsubst bibtex-type-in-head ()
1549 "Extract BibTeX type in head."
1551 (buffer-substring-no-properties (1+ (match-beginning bibtex-type-in-head))
1552 (match-end bibtex-type-in-head)))
1554 (defsubst bibtex-key-in-head (&optional empty)
1555 "Extract BibTeX key in head. Return optional arg EMPTY if key is empty."
1556 (or (match-string-no-properties bibtex-key-in-head)
1559 (defun bibtex-parse-preamble ()
1560 "Parse BibTeX preamble.
1561 Point must be at beginning of preamble. Do not move point."
1562 (let ((case-fold-search t))
1563 (when (looking-at bibtex-preamble-prefix)
1564 (let ((start (match-beginning 0)) (pref-start (match-beginning 1))
1565 (bounds (save-excursion (goto-char (match-end 0))
1566 (bibtex-parse-string-postfix))))
1567 (if bounds (cons (list start pref-start) bounds))))))
1571 (defsubst bibtex-string= (str1 str2)
1572 "Return t if STR1 and STR2 are equal, ignoring case."
1573 (eq t (compare-strings str1 0 nil str2 0 nil t)))
1575 (defun bibtex-delete-whitespace ()
1576 "Delete all whitespace starting at point."
1577 (if (looking-at "[ \t\n]+")
1578 (delete-region (point) (match-end 0))))
1580 (defun bibtex-current-line ()
1581 "Compute line number of point regardless whether the buffer is narrowed."
1582 (+ (count-lines 1 (point))
1585 (defun bibtex-valid-entry (&optional empty-key)
1586 "Parse a valid BibTeX entry (maybe without key if EMPTY-KEY is t).
1587 A valid entry is a syntactical correct one with type contained in
1588 `bibtex-entry-field-alist'. Ignore @String and @Preamble entries.
1589 Return a cons pair with buffer positions of beginning and end of entry
1590 if a valid entry is found, nil otherwise. Do not move point.
1591 After a call to this function `match-data' corresponds to the header
1592 of the entry, see regexp `bibtex-entry-head'."
1593 (let ((case-fold-search t) end)
1594 (if (looking-at (if empty-key bibtex-entry-maybe-empty-head
1598 (goto-char (match-end 0))
1601 (goto-char (match-end bibtex-type-in-head))
1602 (looking-at "[ \t]*("))
1603 ",?[ \t\n]*)" ;; entry opened with `('
1604 ",?[ \t\n]*}")) ;; entry opened with `{'
1606 (skip-chars-forward " \t\n")
1607 ;; loop over all BibTeX fields
1608 (while (setq bounds (bibtex-parse-field))
1609 (goto-char (bibtex-end-of-field bounds)))
1610 ;; This matches the infix* part.
1611 (if (looking-at entry-closer) (setq end (match-end 0)))))
1612 (if end (cons (match-beginning 0) end))))))
1614 (defun bibtex-skip-to-valid-entry (&optional backward)
1615 "Move point to beginning of the next valid BibTeX entry.
1616 Do not move if we are already at beginning of a valid BibTeX entry.
1617 With optional argument BACKWARD non-nil, move backward to
1618 beginning of previous valid one. A valid entry is a syntactical correct one
1619 with type contained in `bibtex-entry-field-alist' or, if
1620 `bibtex-sort-ignore-string-entries' is nil, a syntactical correct string
1621 entry. Return buffer position of beginning and end of entry if a valid
1622 entry is found, nil otherwise."
1624 (let ((case-fold-search t)
1627 ;; Loop till we look at a valid entry.
1628 (while (not (or found (if backward (bobp) (eobp))))
1629 (cond ((setq found (or (bibtex-valid-entry)
1630 (and (not bibtex-sort-ignore-string-entries)
1631 (setq bounds (bibtex-parse-string))
1632 (cons (bibtex-start-of-field bounds)
1633 (bibtex-end-of-string bounds))))))
1634 (backward (re-search-backward "^[ \t]*@" nil 'move))
1635 (t (if (re-search-forward "\n\\([ \t]*@\\)" nil 'move)
1636 (goto-char (match-beginning 1))))))
1639 (defun bibtex-map-entries (fun)
1640 "Call FUN for each BibTeX entry in buffer (possibly narrowed).
1641 FUN is called with three arguments, the key of the entry and the buffer
1642 positions of beginning and end of entry. Also, point is at beginning of
1643 entry and `match-data' corresponds to the header of the entry,
1644 see regexp `bibtex-entry-head'. If `bibtex-sort-ignore-string-entries'
1645 is non-nil, FUN is not called for @String entries."
1646 (let ((case-fold-search t)
1649 (goto-char (point-min))
1650 (while (setq found (bibtex-skip-to-valid-entry))
1651 (looking-at bibtex-any-entry-maybe-empty-head)
1652 (funcall fun (bibtex-key-in-head "") (car found) (cdr found))
1653 (goto-char (cdr found))))))
1655 (defun bibtex-progress-message (&optional flag interval)
1656 "Echo a message about progress of current buffer.
1657 If FLAG is a string, the message is initialized (in this case a
1658 value for INTERVAL may be given as well (if not this is set to 5)).
1659 If FLAG is `done', the message is deinitialized.
1660 If FLAG is nil, a message is echoed if point was incremented at least
1661 `bibtex-progress-interval' percent since last message was echoed."
1662 (cond ((stringp flag)
1663 (setq bibtex-progress-lastmes flag
1664 bibtex-progress-interval (or interval 5)
1665 bibtex-progress-lastperc 0))
1667 (message "%s (done)" bibtex-progress-lastmes)
1668 (setq bibtex-progress-lastmes nil))
1670 (let* ((size (- (point-max) (point-min)))
1671 (perc (if (= size 0)
1673 (/ (* 100 (- (point) (point-min))) size))))
1674 (when (>= perc (+ bibtex-progress-lastperc
1675 bibtex-progress-interval))
1676 (setq bibtex-progress-lastperc perc)
1677 (message "%s (%d%%)" bibtex-progress-lastmes perc))))))
1679 (defun bibtex-field-left-delimiter ()
1680 "Return a string dependent on `bibtex-field-delimiters'."
1681 (if (eq bibtex-field-delimiters 'braces)
1685 (defun bibtex-field-right-delimiter ()
1686 "Return a string dependent on `bibtex-field-delimiters'."
1687 (if (eq bibtex-field-delimiters 'braces)
1691 (defun bibtex-entry-left-delimiter ()
1692 "Return a string dependent on `bibtex-entry-delimiters'."
1693 (if (eq bibtex-entry-delimiters 'braces)
1697 (defun bibtex-entry-right-delimiter ()
1698 "Return a string dependent on `bibtex-entry-delimiters'."
1699 (if (eq bibtex-entry-delimiters 'braces)
1703 (defun bibtex-flash-head (prompt)
1704 "Flash at BibTeX entry head before point, if exists."
1705 (let ((case-fold-search t)
1708 (bibtex-beginning-of-entry)
1709 (when (and (looking-at bibtex-any-entry-maybe-empty-head)
1711 (goto-char (match-beginning bibtex-type-in-head))
1712 (if (pos-visible-in-window-p (point))
1714 (message "%s%s" prompt (buffer-substring-no-properties
1715 (point) (match-end bibtex-key-in-head))))))))
1717 (defun bibtex-make-optional-field (field)
1718 "Make an optional field named FIELD in current BibTeX entry."
1720 (bibtex-make-field (cons (concat "OPT" (car field)) (cdr field)))
1721 (bibtex-make-field (concat "OPT" field))))
1723 (defun bibtex-move-outside-of-entry ()
1724 "Make sure point is outside of a BibTeX entry."
1725 (let ((orig-point (point)))
1726 (bibtex-end-of-entry)
1727 (when (< (point) orig-point)
1728 ;; We moved backward, so we weren't inside an entry to begin with.
1729 ;; Leave point at the beginning of a line, and preferably
1730 ;; at the beginning of a paragraph.
1731 (goto-char orig-point)
1732 (beginning-of-line 1)
1733 (unless (= ?\n (char-before (1- (point))))
1734 (re-search-forward "^[ \t]*[@\n]" nil 'move)
1736 (skip-chars-forward " \t\n")))
1738 (defun bibtex-beginning-of-first-entry ()
1739 "Go to beginning of line of first BibTeX entry in buffer.
1740 If `bibtex-sort-ignore-string-entries' is non-nil, @String entries
1741 are ignored. Return point"
1742 (goto-char (point-min))
1743 (bibtex-skip-to-valid-entry)
1746 (defun bibtex-enclosing-field (&optional comma noerr)
1747 "Search for BibTeX field enclosing point.
1748 For `bibtex-mode''s internal algorithms, a field begins at the comma
1749 following the preceding field. Usually, this is not what the user expects.
1750 Thus if COMMA is non-nil, the \"current field\" includes the terminating comma.
1751 Unless NOERR is non-nil, signal an error if no enclosing field is found.
1752 On success return bounds, nil otherwise. Do not move point."
1756 (skip-chars-backward " \t")
1757 (if (= (preceding-char) ?,) (forward-char -1)))
1759 (let ((bounds (bibtex-search-backward-field bibtex-field-name t)))
1761 (<= (bibtex-start-of-field bounds) (point))
1762 (>= (bibtex-end-of-field bounds) (point)))
1765 (error "Can't find enclosing BibTeX field"))))))
1767 (defun bibtex-beginning-first-field (&optional beg)
1768 "Move point to beginning of first field.
1769 Optional arg BEG is beginning of entry."
1770 (if beg (goto-char beg) (bibtex-beginning-of-entry))
1771 (looking-at bibtex-any-entry-maybe-empty-head)
1772 (goto-char (match-end 0)))
1774 (defun bibtex-insert-kill (n &optional comma)
1775 "Reinsert the Nth stretch of killed BibTeX text (field or entry).
1776 Optional arg COMMA is as in `bibtex-enclosing-field'."
1777 (unless bibtex-last-kill-command (error "BibTeX kill ring is empty"))
1778 (let ((fun (lambda (kryp kr) ;; adapted from `current-kill'
1779 (car (set kryp (nthcdr (mod (- n (length (eval kryp)))
1780 (length kr)) kr))))))
1781 (if (eq bibtex-last-kill-command 'field)
1783 ;; insert past the current field
1784 (goto-char (bibtex-end-of-field (bibtex-enclosing-field comma)))
1786 (message "Mark set")
1787 (bibtex-make-field (funcall fun 'bibtex-field-kill-ring-yank-pointer
1788 bibtex-field-kill-ring) t nil t))
1789 ;; insert past the current entry
1790 (bibtex-skip-to-valid-entry)
1792 (message "Mark set")
1793 (insert (funcall fun 'bibtex-entry-kill-ring-yank-pointer
1794 bibtex-entry-kill-ring)))))
1796 (defun bibtex-format-entry ()
1797 "Helper function for `bibtex-clean-entry'.
1798 Formats current entry according to variable `bibtex-entry-format'."
1801 (bibtex-narrow-to-entry)
1802 (let ((case-fold-search t)
1803 (format (if (eq bibtex-entry-format t)
1804 '(realign opts-or-alts required-fields
1806 last-comma page-dashes delimiters
1807 unify-case inherit-booktitle)
1808 bibtex-entry-format))
1809 crossref-key bounds alternatives-there non-empty-alternative
1810 entry-list req-field-list field-list)
1812 ;; identify entry type
1813 (goto-char (point-min))
1814 (or (re-search-forward bibtex-entry-type nil t)
1815 (error "Not inside a BibTeX entry"))
1816 (let ((beg-type (1+ (match-beginning 0)))
1817 (end-type (match-end 0)))
1818 (setq entry-list (assoc-string (buffer-substring-no-properties
1820 bibtex-entry-field-alist
1823 ;; unify case of entry name
1824 (when (memq 'unify-case format)
1825 (delete-region beg-type end-type)
1826 (insert (car entry-list)))
1828 ;; update left entry delimiter
1829 (when (memq 'delimiters format)
1830 (goto-char end-type)
1831 (skip-chars-forward " \t\n")
1833 (insert (bibtex-entry-left-delimiter))))
1835 ;; determine if entry has crossref field and if at least
1836 ;; one alternative is non-empty
1837 (goto-char (point-min))
1838 (let* ((fields-alist (bibtex-parse-entry t))
1839 (field (assoc-string "crossref" fields-alist t)))
1840 (setq crossref-key (and field
1841 (not (equal "" (cdr field)))
1843 req-field-list (if crossref-key
1844 (nth 0 (nth 2 entry-list)) ; crossref part
1845 (nth 0 (nth 1 entry-list)))) ; required part
1847 (dolist (rfield req-field-list)
1848 (when (nth 3 rfield) ; we should have an alternative
1849 (setq alternatives-there t
1850 field (assoc-string (car rfield) fields-alist t))
1852 (not (equal "" (cdr field))))
1853 (cond ((not non-empty-alternative)
1854 (setq non-empty-alternative t))
1855 ((memq 'required-fields format)
1856 (error "More than one non-empty alternative")))))))
1858 (if (and alternatives-there
1859 (not non-empty-alternative)
1860 (memq 'required-fields format))
1861 (error "All alternatives are empty"))
1863 ;; process all fields
1864 (bibtex-beginning-first-field (point-min))
1865 (while (setq bounds (bibtex-parse-field))
1866 (let* ((beg-field (copy-marker (bibtex-start-of-field bounds)))
1867 (end-field (copy-marker (bibtex-end-of-field bounds) t))
1868 (beg-name (copy-marker (bibtex-start-of-name-in-field bounds)))
1869 (end-name (copy-marker (bibtex-end-of-name-in-field bounds)))
1870 (beg-text (copy-marker (bibtex-start-of-text-in-field bounds)))
1871 (end-text (copy-marker (bibtex-end-of-text-in-field bounds) t))
1872 (opt-alt (string-match "OPT\\|ALT"
1873 (buffer-substring-no-properties
1874 beg-name (+ beg-name 3))))
1875 (field-name (buffer-substring-no-properties
1876 (if opt-alt (+ beg-name 3) beg-name) end-name))
1877 (empty-field (equal "" (bibtex-text-in-field-bounds bounds t)))
1880 ;; We have more elegant high-level functions for several
1881 ;; tasks done by bibtex-format-entry. However, they contain
1882 ;; quite some redundancy compared with what we need to do
1883 ;; anyway. So for speed-up we avoid using them.
1885 (if (memq 'opts-or-alts format)
1886 (cond ((and empty-field
1888 (let ((field (assoc-string
1889 field-name req-field-list t)))
1890 (or (not field) ; OPT field
1891 (nth 3 field))))) ; ALT field
1892 ;; Either it is an empty ALT field. Then we have checked
1893 ;; already that we have one non-empty alternative. Or it
1894 ;; is an empty OPT field that we do not miss anyway.
1895 ;; So we can safely delete this field.
1896 (delete-region beg-field end-field)
1898 ;; otherwise: not empty, delete "OPT" or "ALT"
1900 (goto-char beg-name)
1904 (push field-name field-list)
1906 ;; remove delimiters from purely numerical fields
1907 (when (and (memq 'numerical-fields format)
1908 (progn (goto-char beg-text)
1909 (looking-at "\\(\"[0-9]+\"\\)\\|\\({[0-9]+}\\)")))
1910 (goto-char end-text)
1912 (goto-char beg-text)
1915 ;; update delimiters
1916 (when (memq 'delimiters format)
1917 (goto-char beg-text)
1918 (when (looking-at "[{\"]")
1920 (insert (bibtex-field-left-delimiter)))
1921 (goto-char (1- (marker-position end-text)))
1922 (when (looking-at "[}\"]")
1924 (insert (bibtex-field-right-delimiter))))
1926 ;; update page dashes
1927 (if (and (memq 'page-dashes format)
1928 (bibtex-string= field-name "pages")
1929 (progn (goto-char beg-text)
1931 "\\([\"{][0-9]+\\)[ \t\n]*--?[ \t\n]*\\([0-9]+[\"}]\\)")))
1932 (replace-match "\\1-\\2"))
1934 ;; use book title of crossref'd entry
1935 (if (and (memq 'inherit-booktitle format)
1937 (bibtex-string= field-name "booktitle")
1939 (let ((title (save-excursion
1942 (if (bibtex-find-entry crossref-key t)
1943 (bibtex-text-in-field "title"))))))
1945 (setq empty-field nil)
1946 (goto-char (1+ beg-text))
1949 ;; Use booktitle to set a missing title.
1950 (if (and empty-field
1951 (bibtex-string= field-name "title"))
1952 (let ((booktitle (bibtex-text-in-field "booktitle")))
1954 (setq empty-field nil)
1955 (goto-char (1+ beg-text))
1956 (insert booktitle))))
1958 ;; if empty field, complain
1959 (if (and empty-field
1960 (memq 'required-fields format)
1961 (assoc-string field-name req-field-list t))
1962 (error "Mandatory field `%s' is empty" field-name))
1964 ;; unify case of field name
1965 (if (memq 'unify-case format)
1966 (let ((fname (car (assoc-string
1968 (append (nth 0 (nth 1 entry-list))
1969 (nth 1 (nth 1 entry-list))
1970 bibtex-user-optional-fields)
1974 (delete-region beg-name end-name)
1975 (goto-char beg-name)
1977 ;; there are no rules we could follow
1978 (downcase-region beg-name end-name))))
1981 (goto-char end-field))))
1983 ;; check whether all required fields are present
1984 (if (memq 'required-fields format)
1985 (let ((found 0) altlist)
1986 (dolist (fname req-field-list)
1988 (push (car fname) altlist))
1989 (unless (or (member (car fname) field-list)
1991 (error "Mandatory field `%s' is missing" (car fname))))
1993 (dolist (fname altlist)
1994 (if (member fname field-list)
1995 (setq found (1+ found))))
1997 (error "Alternative mandatory field `%s' is missing"
2000 (error "Alternative fields `%s' are defined %s times"
2003 ;; update comma after last field
2004 (if (memq 'last-comma format)
2005 (cond ((and bibtex-comma-after-last-field
2006 (not (looking-at ",")))
2008 ((and (not bibtex-comma-after-last-field)
2012 ;; update right entry delimiter
2013 (if (looking-at ",")
2015 (when (memq 'delimiters format)
2016 (skip-chars-forward " \t\n")
2018 (insert (bibtex-entry-right-delimiter)))
2021 (if (memq 'realign format)
2022 (bibtex-fill-entry))))))
2025 (defun bibtex-autokey-abbrev (string len)
2026 "Return an abbreviation of STRING with at least LEN characters.
2027 If LEN is positive the abbreviation is terminated only after a consonant
2028 or at the word end. If LEN is negative the abbreviation is strictly
2029 enforced using abs (LEN) characters. If LEN is not a number, STRING
2030 is returned unchanged."
2031 (cond ((or (not (numberp len))
2032 (<= (length string) (abs len)))
2037 (substring string 0 (abs len)))
2038 (t (let* ((case-fold-search t)
2039 (abort-char (string-match "[^aeiou]" string (1- len))))
2041 (substring string 0 (1+ abort-char))
2044 (defun bibtex-autokey-get-field (field &optional change-list)
2045 "Get content of BibTeX field FIELD. Return empty string if not found.
2046 Optional arg CHANGE-LIST is a list of substitution patterns that is
2047 applied to the content of FIELD. It is an alist with pairs
2048 \(OLD-REGEXP . NEW-STRING\)."
2049 (let* ((bibtex-expand-strings bibtex-autokey-expand-strings)
2050 (content (bibtex-text-in-field field bibtex-autokey-use-crossref))
2052 (unless content (setq content ""))
2053 (dolist (pattern change-list content)
2054 (setq content (replace-regexp-in-string (car pattern)
2058 (defun bibtex-autokey-get-names ()
2059 "Get contents of the name field of the current entry.
2060 Do some modifications based on `bibtex-autokey-name-change-strings'.
2061 Return the names as a concatenated string obeying `bibtex-autokey-names'
2062 and `bibtex-autokey-names-stretch'."
2063 (let ((names (bibtex-autokey-get-field "author\\|editor"
2064 bibtex-autokey-name-change-strings)))
2065 ;; Some entries do not have a name field.
2066 (if (string= "" names)
2068 (let* ((case-fold-search t)
2069 (name-list (mapcar 'bibtex-autokey-demangle-name
2070 (split-string names "[ \t\n]+and[ \t\n]+")))
2072 (unless (or (not (numberp bibtex-autokey-names))
2073 (<= (length name-list)
2074 (+ bibtex-autokey-names
2075 bibtex-autokey-names-stretch)))
2076 ;; Take bibtex-autokey-names elements from beginning of name-list
2077 (setq name-list (nreverse (nthcdr (- (length name-list)
2078 bibtex-autokey-names)
2079 (nreverse name-list)))
2080 additional-names bibtex-autokey-additional-names))
2081 (concat (mapconcat 'identity name-list
2082 bibtex-autokey-name-separator)
2083 additional-names)))))
2085 (defun bibtex-autokey-demangle-name (fullname)
2086 "Get the last part from a well-formed FULLNAME and perform abbreviations."
2087 (let* (case-fold-search
2088 (name (cond ((string-match "\\([[:upper:]][^, ]*\\)[^,]*," fullname)
2089 ;; Name is of the form "von Last, First" or
2090 ;; "von Last, Jr, First"
2091 ;; --> Take the first capital part before the comma
2092 (match-string 1 fullname))
2093 ((string-match "\\([^, ]*\\)," fullname)
2094 ;; Strange name: we have a comma, but nothing capital
2095 ;; So we accept even lowercase names
2096 (match-string 1 fullname))
2097 ((string-match "\\(\\<[[:lower:]][^ ]* +\\)+\\([[:upper:]][^ ]*\\)"
2099 ;; name is of the form "First von Last", "von Last",
2100 ;; "First von von Last", or "d'Last"
2101 ;; --> take the first capital part after the "von" parts
2102 (match-string 2 fullname))
2103 ((string-match "\\([^ ]+\\) *\\'" fullname)
2104 ;; name is of the form "First Middle Last" or "Last"
2105 ;; --> take the last token
2106 (match-string 1 fullname))
2107 (t (error "Name `%s' is incorrectly formed" fullname)))))
2108 (funcall bibtex-autokey-name-case-convert-function
2109 (bibtex-autokey-abbrev name bibtex-autokey-name-length))))
2111 (defun bibtex-autokey-get-year ()
2112 "Return year field contents as a string obeying `bibtex-autokey-year-length'."
2113 (let ((yearfield (bibtex-autokey-get-field "year")))
2114 (substring yearfield (max 0 (- (length yearfield)
2115 bibtex-autokey-year-length)))))
2117 (defun bibtex-autokey-get-title ()
2118 "Get title field contents up to a terminator.
2119 Return the result as a string"
2120 (let ((case-fold-search t)
2122 (bibtex-autokey-get-field "title"
2123 bibtex-autokey-titleword-change-strings)))
2124 ;; ignore everything past a terminator
2125 (if (string-match bibtex-autokey-title-terminators titlestring)
2126 (setq titlestring (substring titlestring 0 (match-beginning 0))))
2127 ;; gather words from titlestring into a list. Ignore
2128 ;; specific words and use only a specific amount of words.
2130 titlewords titlewords-extra word)
2131 (while (and (or (not (numberp bibtex-autokey-titlewords))
2132 (< counter (+ bibtex-autokey-titlewords
2133 bibtex-autokey-titlewords-stretch)))
2134 (string-match "\\b\\w+" titlestring))
2135 (setq word (match-string 0 titlestring)
2136 titlestring (substring titlestring (match-end 0)))
2137 ;; Ignore words matched by one of the elements of
2138 ;; bibtex-autokey-titleword-ignore
2139 (unless (let ((lst bibtex-autokey-titleword-ignore))
2141 (not (string-match (concat "\\`\\(?:" (car lst)
2143 (setq lst (cdr lst)))
2145 (setq counter (1+ counter))
2146 (if (or (not (numberp bibtex-autokey-titlewords))
2147 (<= counter bibtex-autokey-titlewords))
2148 (push word titlewords)
2149 (push word titlewords-extra))))
2150 ;; Obey bibtex-autokey-titlewords-stretch:
2151 ;; If by now we have processed all words in titlestring, we include
2152 ;; titlewords-extra in titlewords. Otherwise, we ignore titlewords-extra.
2153 (unless (string-match "\\b\\w+" titlestring)
2154 (setq titlewords (append titlewords-extra titlewords)))
2155 (mapconcat 'bibtex-autokey-demangle-title (nreverse titlewords)
2156 bibtex-autokey-titleword-separator))))
2158 (defun bibtex-autokey-demangle-title (titleword)
2159 "Do some abbreviations on TITLEWORD.
2160 The rules are defined in `bibtex-autokey-titleword-abbrevs'
2161 and `bibtex-autokey-titleword-length'."
2162 (let ((case-fold-search t)
2163 (alist bibtex-autokey-titleword-abbrevs))
2165 (not (string-match (concat "\\`\\(?:" (caar alist) "\\)\\'")
2167 (setq alist (cdr alist)))
2170 (funcall bibtex-autokey-titleword-case-convert-function
2171 (bibtex-autokey-abbrev titleword bibtex-autokey-titleword-length)))))
2173 (defun bibtex-generate-autokey ()
2174 "Generate automatically a key for a BibTeX entry.
2175 Use the author/editor, the year and the title field.
2176 The algorithm works as follows.
2179 1. Use the author or editor field to generate the name part of the key.
2180 Expand BibTeX strings if `bibtex-autokey-expand-strings' is non-nil.
2181 2. Change the content of the name field according to
2182 `bibtex-autokey-name-change-strings' (see there for further detail).
2183 3. Use the first `bibtex-autokey-names' names in the name field. If there
2184 are up to `bibtex-autokey-names' + `bibtex-autokey-names-stretch' names,
2186 4. Use only the last names to form the name part. From these last names,
2187 take at least `bibtex-autokey-name-length' characters (truncate only
2188 after a consonant or at a word end).
2189 5. Convert all last names using the function
2190 `bibtex-autokey-name-case-convert-function'.
2191 6. Build the name part of the key by concatenating all abbreviated last
2192 names with the string `bibtex-autokey-name-separator' between any two.
2193 If there are more names in the name field than names used in the name
2194 part, append the string `bibtex-autokey-additional-names'.
2197 1. Build the year part of the key by truncating the content of the year
2198 field to the rightmost `bibtex-autokey-year-length' digits (useful
2199 values are 2 and 4).
2200 2. If the year field (or any other field required to generate the key)
2201 is absent, but the entry has a valid crossref field and
2202 `bibtex-autokey-use-crossref' is non-nil, use the field of the
2203 crossreferenced entry instead.
2206 1. Change the content of the title field according to
2207 `bibtex-autokey-titleword-change-strings' (see there for further detail).
2208 2. Truncate the title before the first match of
2209 `bibtex-autokey-title-terminators' and delete those words which appear
2210 in `bibtex-autokey-titleword-ignore'. Build the title part using the
2211 first `bibtex-autokey-titlewords' words from this truncated title.
2212 If the truncated title ends after up to `bibtex-autokey-titlewords' +
2213 `bibtex-autokey-titlewords-stretch' words, use all words from the
2215 3. For every title word that appears in `bibtex-autokey-titleword-abbrevs'
2216 use the corresponding abbreviation (see documentation of this variable
2217 for further detail).
2218 4. From every title word not generated by an abbreviation, take at least
2219 `bibtex-autokey-titleword-length' characters (truncate only after
2220 a consonant or at a word end).
2221 5. Convert all title words using the function
2222 `bibtex-autokey-titleword-case-convert-function'.
2223 6. Build the title part by concatenating all abbreviated title words with
2224 the string `bibtex-autokey-titleword-separator' between any two.
2226 Concatenate the key:
2227 1. Concatenate `bibtex-autokey-prefix-string', the name part, the year
2228 part and the title part. If the name part and the year part are both
2229 non-empty insert `bibtex-autokey-name-year-separator' between the two.
2230 If the title part and the year (or name) part are non-empty, insert
2231 `bibtex-autokey-year-title-separator' between the two.
2232 2. If `bibtex-autokey-before-presentation-function' is non-nil, it must be
2233 a function taking one argument. Call this function with the generated
2234 key as the argument. Use the return value of this function (a string)
2236 3. If `bibtex-autokey-edit-before-use' is non-nil, present the key in the
2237 minibuffer to the user for editing. Insert the key given by the user."
2238 (let* ((names (bibtex-autokey-get-names))
2239 (year (bibtex-autokey-get-year))
2240 (title (bibtex-autokey-get-title))
2241 (autokey (concat bibtex-autokey-prefix-string
2243 (unless (or (equal names "")
2245 bibtex-autokey-name-year-separator)
2247 (unless (or (and (equal names "")
2250 bibtex-autokey-year-title-separator)
2252 (if bibtex-autokey-before-presentation-function
2253 (funcall bibtex-autokey-before-presentation-function autokey)
2257 (defun bibtex-global-key-alist ()
2258 "Return global key alist based on `bibtex-files'."
2261 (mapcar (lambda (buf)
2262 (with-current-buffer buf bibtex-reference-keys))
2263 (bibtex-files-expand t)))
2264 bibtex-reference-keys))
2266 (defun bibtex-read-key (prompt &optional key global)
2267 "Read BibTeX key from minibuffer using PROMPT and default KEY.
2268 If optional arg GLOBAL is non-nil, completion is based on the keys in
2269 `bibtex-reference-keys' of `bibtex-files',"
2270 (let (completion-ignore-case)
2271 (completing-read prompt (if global (bibtex-global-key-alist)
2272 bibtex-reference-keys)
2273 nil nil key 'bibtex-key-history)))
2275 (defun bibtex-read-string-key (&optional key)
2276 "Read BibTeX string key from minibuffer using default KEY."
2277 (let ((completion-ignore-case t))
2278 (completing-read "String key: " bibtex-strings
2279 nil nil key 'bibtex-key-history)))
2281 (defun bibtex-parse-keys (&optional abortable verbose)
2282 "Set `bibtex-reference-keys' to the keys used in the whole buffer.
2283 Find both entry keys and crossref entries. If ABORTABLE is non-nil abort
2284 on user input. If VERBOSE is non-nil give messages about progress.
2285 Return alist of keys if parsing was completed, `aborted' otherwise.
2286 If `bibtex-parse-keys-fast' is non-nil, use fast but simplified algorithm
2287 for parsing BibTeX keys. If parsing fails, try to set this variable to nil."
2288 (let (ref-keys crossref-keys)
2292 (bibtex-progress-message
2293 (concat (buffer-name) ": parsing reference keys")))
2295 (goto-char (point-min))
2296 (if bibtex-parse-keys-fast
2297 (let ((case-fold-search t)
2298 (re (concat bibtex-entry-head "\\|"
2299 ",[ \t\n]*crossref[ \t\n]*=[ \t\n]*"
2300 "\\(\"[^\"]*\"\\|{[^}]*}\\)[ \t\n]*[,})]")))
2301 (while (re-search-forward re nil t)
2302 (if (and abortable (input-pending-p))
2303 ;; user has aborted by typing a key --> return `aborted'
2304 (throw 'userkey 'aborted))
2305 (cond ((match-end 3)
2306 ;; This is a crossref.
2307 (let ((key (buffer-substring-no-properties
2308 (1+ (match-beginning 3)) (1- (match-end 3)))))
2309 (unless (assoc key crossref-keys)
2310 (push (list key) crossref-keys))))
2311 ;; only keys of known entries
2312 ((assoc-string (bibtex-type-in-head)
2313 bibtex-entry-field-alist t)
2314 ;; This is an entry.
2315 (let ((key (bibtex-key-in-head)))
2316 (unless (assoc key ref-keys)
2317 (push (cons key t) ref-keys)))))))
2319 (let (;; ignore @String entries because they are handled
2320 ;; separately by bibtex-parse-strings
2321 (bibtex-sort-ignore-string-entries t)
2324 (lambda (key beg end)
2327 ;; user has aborted by typing a key --> return `aborted'
2328 (throw 'userkey 'aborted))
2329 (if verbose (bibtex-progress-message))
2330 (unless (assoc key ref-keys)
2331 (push (cons key t) ref-keys))
2332 (if (and (setq bounds (bibtex-search-forward-field "crossref" end))
2333 (setq key (bibtex-text-in-field-bounds bounds t))
2334 (not (assoc key crossref-keys)))
2335 (push (list key) crossref-keys))))))
2337 (dolist (key crossref-keys)
2338 (unless (assoc (car key) ref-keys) (push key ref-keys)))
2340 (bibtex-progress-message 'done))
2341 ;; successful operation --> return `bibtex-reference-keys'
2342 (setq bibtex-reference-keys ref-keys))))))
2344 (defun bibtex-parse-strings (&optional add abortable)
2345 "Set `bibtex-strings' to the string definitions in the whole buffer.
2346 If ADD is non-nil add the new strings to `bibtex-strings' instead of
2347 simply resetting it. If ADD is an alist of strings, also add ADD to
2348 `bibtex-strings'. If ABORTABLE is non-nil abort on user input.
2349 Return alist of strings if parsing was completed, `aborted' otherwise."
2352 (goto-char (point-min))
2353 (let ((strings (if (and add
2354 (listp bibtex-strings))
2358 (dolist (string add)
2359 (unless (assoc-string (car string) strings t)
2360 (push string strings))))
2362 (while (setq bounds (bibtex-search-forward-string))
2365 ;; user has aborted by typing a key --> return `aborted'
2366 (throw 'userkey 'aborted))
2367 (setq key (bibtex-reference-key-in-string bounds))
2368 (unless (assoc-string key strings t)
2369 (push (cons key (bibtex-text-in-string bounds t))
2371 (goto-char (bibtex-end-of-text-in-string bounds)))
2372 ;; successful operation --> return `bibtex-strings'
2373 (setq bibtex-strings strings))))))
2375 (defun bibtex-strings ()
2376 "Return `bibtex-strings'. Initialize this variable if necessary."
2377 (if (listp bibtex-strings) bibtex-strings
2378 (bibtex-parse-strings (bibtex-string-files-init))))
2380 (defun bibtex-string-files-init ()
2381 "Return initialization for `bibtex-strings'.
2382 Use `bibtex-predefined-strings' and BibTeX files `bibtex-string-files'."
2384 (let ((dirlist (split-string (or bibtex-string-file-path default-directory)
2387 string-files fullfilename compl bounds found)
2388 ;; collect absolute file names of valid string files
2389 (dolist (filename bibtex-string-files)
2390 (unless (string-match "\\.bib\\'" filename)
2391 (setq filename (concat filename ".bib")))
2393 (if (file-name-absolute-p filename)
2394 (if (file-readable-p filename)
2395 (push filename string-files)
2396 (error "BibTeX strings file %s not found" filename))
2397 (dolist (dir dirlist)
2398 (when (file-readable-p
2399 (setq fullfilename (expand-file-name filename dir)))
2400 (push fullfilename string-files)
2403 (error "File %s not in paths defined via bibtex-string-file-path"
2405 ;; parse string files
2406 (dolist (filename string-files)
2408 (insert-file-contents filename)
2409 (goto-char (point-min))
2410 (while (setq bounds (bibtex-search-forward-string))
2411 (push (cons (bibtex-reference-key-in-string bounds)
2412 (bibtex-text-in-string bounds t))
2414 (goto-char (bibtex-end-of-string bounds)))))
2415 (append bibtex-predefined-strings (nreverse compl)))))
2417 (defun bibtex-parse-buffers-stealthily ()
2418 "Parse buffer in the background during idle time.
2419 Called by `run-with-idle-timer'. Whenever Emacs has been idle
2420 for `bibtex-parse-keys-timeout' seconds, parse all BibTeX buffers
2421 which have been modified after last parsing.
2422 Parsing initializes `bibtex-reference-keys' and `bibtex-strings'."
2424 (let ((buffers (buffer-list))
2425 (strings-init (bibtex-string-files-init)))
2426 (while (and buffers (not (input-pending-p)))
2427 (set-buffer (car buffers))
2428 (if (and (eq major-mode 'bibtex-mode)
2429 (not (eq (buffer-modified-tick)
2430 bibtex-buffer-last-parsed-tick)))
2433 ;; Output no progress messages in bibtex-parse-keys
2434 ;; because when in y-or-n-p that can hide the question.
2435 (if (and (listp (bibtex-parse-keys t))
2436 ;; update bibtex-strings
2437 (listp (bibtex-parse-strings strings-init t)))
2439 ;; remember that parsing was successful
2440 (setq bibtex-buffer-last-parsed-tick (buffer-modified-tick)))))
2441 (setq buffers (cdr buffers))))))
2443 (defun bibtex-files-expand (&optional current force)
2444 "Return an expanded list of BibTeX buffers based on `bibtex-files'.
2445 Initialize in these buffers `bibtex-reference-keys' if not yet set.
2446 List of BibTeX buffers includes current buffer if CURRENT is non-nil.
2447 If FORCE is non-nil, (re)initialize `bibtex-reference-keys' even if
2449 (let ((file-path (split-string (or bibtex-file-path default-directory) ":+"))
2450 file-list dir-list buffer-list)
2451 (dolist (file bibtex-files)
2452 (cond ((eq file 'bibtex-file-path)
2453 (setq dir-list (append dir-list file-path)))
2454 ((file-accessible-directory-p file)
2455 (push file dir-list))
2456 ((progn (unless (string-match "\\.bib\\'" file)
2457 (setq file (concat file ".bib")))
2458 (file-name-absolute-p file))
2459 (push file file-list))
2461 (let (fullfilename found)
2462 (dolist (dir file-path)
2463 (when (file-readable-p
2464 (setq fullfilename (expand-file-name file dir)))
2465 (push fullfilename file-list)
2468 (error "File %s not in paths defined via bibtex-file-path"
2470 (dolist (file file-list)
2471 (unless (file-readable-p file)
2472 (error "BibTeX file %s not found" file)))
2474 (dolist (dir dir-list)
2476 (append file-list (directory-files dir t "\\.bib\\'" t))))
2477 (delete-dups file-list)
2478 (dolist (file file-list)
2479 (when (file-readable-p file)
2480 (push (find-file-noselect file) buffer-list)
2481 (with-current-buffer (car buffer-list)
2482 (if (or force (not (listp bibtex-reference-keys)))
2483 (bibtex-parse-keys)))))
2484 (cond ((and current (not (memq (current-buffer) buffer-list)))
2485 (push (current-buffer) buffer-list)
2486 (if force (bibtex-parse-keys)))
2487 ((and (not current) (memq (current-buffer) buffer-list))
2488 (setq buffer-list (delq (current-buffer) buffer-list))))
2491 (defun bibtex-complete-internal (completions)
2492 "Complete word fragment before point to longest prefix of COMPLETIONS.
2493 COMPLETIONS is an alist of strings. If point is not after the part
2494 of a word, all strings are listed. Return completion."
2495 ;; Return value is used by cleanup functions.
2496 (let* ((case-fold-search t)
2497 (beg (save-excursion
2498 (re-search-backward "[ \t{\"]")
2502 (part-of-word (buffer-substring-no-properties beg end))
2503 (completion (try-completion part-of-word completions)))
2504 (cond ((not completion)
2505 (error "Can't find completion for `%s'" part-of-word))
2508 ((not (string= part-of-word completion))
2509 (delete-region beg end)
2513 (message "Making completion list...")
2514 (with-output-to-temp-buffer "*Completions*"
2515 (display-completion-list (all-completions part-of-word completions)
2517 (message "Making completion list...done")
2520 (defun bibtex-complete-string-cleanup (str compl)
2521 "Cleanup after inserting string STR.
2522 Remove enclosing field delimiters for STR. Display message with
2523 expansion of STR using expansion list COMPL."
2524 ;; point is at position inside field where completion was requested
2526 (let ((abbr (cdr (if (stringp str)
2527 (assoc-string str compl t)))))
2528 (if abbr (message "Abbreviation for `%s'" abbr))
2529 (bibtex-remove-delimiters))))
2531 (defun bibtex-complete-crossref-cleanup (key)
2532 "Display summary message on entry KEY after completion of a crossref key.
2533 Use `bibtex-summary-function' to generate summary."
2535 (if (and (stringp key)
2536 (bibtex-find-entry key t))
2537 (message "Ref: %s" (funcall bibtex-summary-function)))))
2539 (defun bibtex-copy-summary-as-kill ()
2540 "Push summery of current BibTeX entry to kill ring.
2541 Use `bibtex-summary-function' to generate summary."
2544 (bibtex-beginning-of-entry)
2545 (if (looking-at bibtex-entry-maybe-empty-head)
2546 (kill-new (message "%s" (funcall bibtex-summary-function)))
2547 (error "No entry found"))))
2549 (defun bibtex-summary ()
2550 "Return summary of current BibTeX entry.
2551 Used as default value of `bibtex-summary-function'."
2552 ;; It would be neat to customize this function. How?
2553 (if (looking-at bibtex-entry-maybe-empty-head)
2554 (let* ((bibtex-autokey-name-case-convert-function 'identity)
2555 (bibtex-autokey-name-length 'infty)
2556 (bibtex-autokey-names 1)
2557 (bibtex-autokey-names-stretch 0)
2558 (bibtex-autokey-name-separator " ")
2559 (bibtex-autokey-additional-names " etal")
2560 (names (bibtex-autokey-get-names))
2561 (bibtex-autokey-year-length 4)
2562 (year (bibtex-autokey-get-year))
2563 (bibtex-autokey-titlewords 5)
2564 (bibtex-autokey-titlewords-stretch 2)
2565 (bibtex-autokey-titleword-case-convert-function 'identity)
2566 (bibtex-autokey-titleword-length 5)
2567 (bibtex-autokey-titleword-separator " ")
2568 (title (bibtex-autokey-get-title))
2569 (journal (bibtex-autokey-get-field
2570 "journal" bibtex-autokey-transcriptions))
2571 (volume (bibtex-autokey-get-field "volume"))
2572 (pages (bibtex-autokey-get-field "pages" '(("-.*\\'" . "")))))
2573 (mapconcat (lambda (arg)
2574 (if (not (string= "" (cdr arg)))
2575 (concat (car arg) (cdr arg))))
2576 `((" " . ,names) (" " . ,year) (": " . ,title)
2577 (", " . ,journal) (" " . ,volume) (":" . ,pages))
2579 (error "Entry not found")))
2581 (defun bibtex-pop (arg direction)
2582 "Fill current field from the ARGth same field's text in DIRECTION.
2583 Generic function used by `bibtex-pop-previous' and `bibtex-pop-next'."
2584 ;; parse current field
2585 (let* ((bounds (bibtex-enclosing-field t))
2586 (start-old-field (bibtex-start-of-field bounds))
2587 (start-old-text (bibtex-start-of-text-in-field bounds))
2588 (end-old-text (bibtex-end-of-text-in-field bounds))
2589 (field-name (bibtex-name-in-field bounds t))
2592 ;; if executed several times in a row, start each search where
2593 ;; the last one was finished
2594 (cond ((eq last-command 'bibtex-pop)
2595 (goto-char (if (eq direction 'previous)
2596 bibtex-pop-previous-search-point
2597 bibtex-pop-next-search-point)))
2598 ((eq direction 'previous)
2599 (bibtex-beginning-of-entry))
2600 (t (bibtex-end-of-entry)))
2601 ;; Search for arg'th previous/next similar field
2602 (while (and (not failure)
2603 (>= (setq arg (1- arg)) 0))
2604 ;; The search of BibTeX fields is not bounded by entry boundaries
2605 (if (eq direction 'previous)
2606 (if (setq bounds (bibtex-search-backward-field field-name))
2607 (goto-char (bibtex-start-of-field bounds))
2609 (if (setq bounds (bibtex-search-forward-field field-name))
2610 (goto-char (bibtex-end-of-field bounds))
2613 (error "No %s matching BibTeX field"
2614 (if (eq direction 'previous) "previous" "next"))
2615 ;; Found a matching field. Remember boundaries.
2616 (let ((new-text (bibtex-text-in-field-bounds bounds))
2617 (nbeg (copy-marker (bibtex-start-of-field bounds)))
2618 (nend (copy-marker (bibtex-end-of-field bounds))))
2619 (bibtex-flash-head "From: ")
2620 ;; Go back to where we started, delete old text, and pop new.
2621 (goto-char end-old-text)
2622 (delete-region start-old-text end-old-text)
2623 (if (= nbeg start-old-field)
2624 (insert (bibtex-field-left-delimiter)
2625 (bibtex-field-right-delimiter))
2627 (setq bibtex-pop-previous-search-point (marker-position nbeg)
2628 bibtex-pop-next-search-point (marker-position nend))))))
2629 (bibtex-find-text nil nil nil t)
2630 (setq this-command 'bibtex-pop))
2632 (defun bibtex-beginning-of-field ()
2633 "Move point backward to beginning of field.
2634 This function uses a simple, fast algorithm assuming that the field
2635 begins at the beginning of a line. We use this function for font-locking."
2636 (let ((field-reg (concat "^[ \t]*" bibtex-field-name "[ \t]*=")))
2638 (unless (looking-at field-reg)
2639 (re-search-backward field-reg nil t))))
2641 (defun bibtex-font-lock-url (bound)
2642 "Font-lock for URLs. BOUND limits the search."
2643 (let ((case-fold-search t)
2645 field bounds start end found)
2646 (bibtex-beginning-of-field)
2647 (while (and (not found)
2649 (prog1 (re-search-forward bibtex-font-lock-url-regexp bound t)
2650 (setq field (match-string-no-properties 1)))
2651 (setq bounds (bibtex-parse-field-text))
2653 (setq start (car bounds) end (nth 1 bounds))
2654 ;; Always ignore field delimiters
2655 (if (memq (char-before end) '(?\} ?\"))
2656 (setq end (1- end)))
2657 (if (memq (char-after start) '(?\{ ?\"))
2658 (setq start (1+ start)))
2660 (let ((lst bibtex-generate-url-list) url)
2662 (while (and (not found)
2663 (setq url (car (pop lst))))
2664 (setq found (and (bibtex-string= field (car url))
2665 (re-search-forward (cdr url) end t)
2666 (>= (match-beginning 0) pnt)))))
2668 (if found (bibtex-button (match-beginning 0) (match-end 0)
2669 'bibtex-url (match-beginning 0)))
2672 (defun bibtex-font-lock-crossref (bound)
2673 "Font-lock for crossref fields. BOUND limits the search."
2674 (let ((case-fold-search t)
2676 (crossref-reg (concat "^[ \t]*crossref[ \t]*=[ \t\n]*"
2677 "\\(\"[^\"]*\"\\|{[^}]*}\\)[ \t\n]*[,})]"))
2679 (bibtex-beginning-of-field)
2680 (while (and (not found)
2681 (re-search-forward crossref-reg bound t))
2682 (setq start (1+ (match-beginning 1))
2683 end (1- (match-end 1))
2684 found (>= start pnt)))
2685 (if found (bibtex-button start end 'bibtex-find-crossref
2686 (buffer-substring-no-properties start end)
2690 (defun bibtex-button-action (button)
2691 "Call BUTTON's BibTeX function."
2692 (apply (button-get button 'bibtex-function)
2693 (button-get button 'bibtex-args)))
2695 (define-button-type 'bibtex-url
2696 'action 'bibtex-button-action
2697 'bibtex-function 'bibtex-url
2698 'help-echo (purecopy "mouse-2, RET: follow URL"))
2700 (define-button-type 'bibtex-find-crossref
2701 'action 'bibtex-button-action
2702 'bibtex-function 'bibtex-find-crossref
2703 'help-echo (purecopy "mouse-2, RET: follow crossref"))
2705 (defun bibtex-button (beg end type &rest args)
2706 "Make a BibTeX button from BEG to END of type TYPE in the current buffer."
2707 (make-text-button beg end 'type type 'bibtex-args args))
2710 ;; Interactive Functions:
2713 (defun bibtex-mode ()
2714 "Major mode for editing BibTeX files.
2716 General information on working with BibTeX mode:
2718 Use commands such as \\[bibtex-Book] to get a template for a specific entry.
2719 Then fill in all desired fields using \\[bibtex-next-field] to jump from field
2720 to field. After having filled in all desired fields in the entry, clean the
2721 new entry with the command \\[bibtex-clean-entry].
2723 Some features of BibTeX mode are available only by setting the variable
2724 `bibtex-maintain-sorted-entries' to non-nil. However, then BibTeX mode
2725 works only with buffers containing valid (syntactical correct) and sorted
2726 entries. This is usually the case, if you have created a buffer completely
2727 with BibTeX mode and finished every new entry with \\[bibtex-clean-entry].
2729 For third party BibTeX files, call the command \\[bibtex-convert-alien]
2730 to fully take advantage of all features of BibTeX mode.
2733 Special information:
2735 A command such as \\[bibtex-Book] outlines the fields for a BibTeX book entry.
2737 The names of optional fields start with the string OPT, and are thus ignored
2738 by BibTeX. The names of alternative fields from which only one is required
2739 start with the string ALT. The OPT or ALT string may be removed from
2740 the name of a field with \\[bibtex-remove-OPT-or-ALT].
2741 \\[bibtex-make-field] inserts a new field after the current one.
2742 \\[bibtex-kill-field] kills the current field entirely.
2743 \\[bibtex-yank] yanks the last recently killed field after the current field.
2744 \\[bibtex-remove-delimiters] removes the double-quotes or braces around the text of the current field.
2745 \\[bibtex-empty-field] replaces the text of the current field with the default \"\" or {}.
2746 \\[bibtex-find-text] moves point to the end of the current field.
2747 \\[bibtex-complete] completes word fragment before point according to context.
2749 The command \\[bibtex-clean-entry] cleans the current entry, i.e. it removes OPT/ALT
2750 from the names of all non-empty optional or alternative fields, checks that
2751 no required fields are empty, and does some formatting dependent on the value
2752 of `bibtex-entry-format'. Furthermore, it can automatically generate a key
2753 for the BibTeX entry, see `bibtex-generate-autokey'.
2754 Note: some functions in BibTeX mode depend on entries being in a special
2755 format (all fields beginning on separate lines), so it is usually a bad
2756 idea to remove `realign' from `bibtex-entry-format'.
2758 BibTeX mode supports Imenu and hideshow minor mode (`hs-minor-mode').
2760 ----------------------------------------------------------
2761 Entry to BibTeX mode calls the value of `bibtex-mode-hook'
2762 if that value is non-nil.
2764 \\{bibtex-mode-map}"
2766 (kill-all-local-variables)
2767 (use-local-map bibtex-mode-map)
2768 (setq major-mode 'bibtex-mode)
2769 (setq mode-name "BibTeX")
2770 (set-syntax-table bibtex-mode-syntax-table)
2771 (make-local-variable 'bibtex-buffer-last-parsed-tick)
2772 ;; Install stealthy parse function if not already installed
2773 (unless bibtex-parse-idle-timer
2774 (setq bibtex-parse-idle-timer (run-with-idle-timer
2775 bibtex-parse-keys-timeout t
2776 'bibtex-parse-buffers-stealthily)))
2777 (set (make-local-variable 'paragraph-start) "[ \f\n\t]*$")
2778 (set (make-local-variable 'comment-start) bibtex-comment-start)
2779 (set (make-local-variable 'comment-start-skip)
2780 (concat (regexp-quote bibtex-comment-start) "\\>[ \t]*"))
2781 (set (make-local-variable 'comment-column) 0)
2782 (set (make-local-variable 'defun-prompt-regexp) "^[ \t]*@[[:alnum:]]+[ \t]*")
2783 (set (make-local-variable 'outline-regexp) "[ \t]*@")
2784 (set (make-local-variable 'fill-paragraph-function) 'bibtex-fill-field)
2785 (set (make-local-variable 'fill-prefix) (make-string (+ bibtex-entry-offset
2786 bibtex-contline-indentation)
2788 (set (make-local-variable 'font-lock-defaults)
2789 '(bibtex-font-lock-keywords
2791 ;; Mathematical expressions should be fontified as strings
2793 ;; Quotes are field delimiters and quote-delimited
2794 ;; entries should be fontified in the same way as
2795 ;; brace-delimited ones
2798 (font-lock-syntactic-keywords . bibtex-font-lock-syntactic-keywords)
2799 (font-lock-extra-managed-props . (category))
2800 (font-lock-mark-block-function
2802 (set-mark (bibtex-end-of-entry))
2803 (bibtex-beginning-of-entry)))))
2804 (setq imenu-generic-expression
2805 (list (list nil bibtex-entry-head bibtex-key-in-head))
2806 imenu-case-fold-search t)
2807 (make-local-variable 'choose-completion-string-functions)
2808 ;; XEmacs needs easy-menu-add, Emacs does not care
2809 (easy-menu-add bibtex-edit-menu)
2810 (easy-menu-add bibtex-entry-menu)
2811 (run-mode-hooks 'bibtex-mode-hook))
2813 (defun bibtex-field-list (entry-type)
2814 "Return list of allowed fields for entry ENTRY-TYPE.
2815 More specifically, the return value is a cons pair (REQUIRED . OPTIONAL),
2816 where REQUIRED and OPTIONAL are lists of the required and optional field
2817 names for ENTRY-TYPE according to `bibtex-entry-field-alist',
2818 `bibtex-include-OPTkey', `bibtex-include-OPTcrossref',
2819 and `bibtex-user-optional-fields'."
2820 (let ((e (assoc-string entry-type bibtex-entry-field-alist t))
2823 (error "Fields for BibTeX entry type %s not defined" entry-type))
2824 (if (and (member-ignore-case entry-type bibtex-include-OPTcrossref)
2826 (setq required (nth 0 (nth 2 e))
2827 optional (nth 1 (nth 2 e)))
2828 (setq required (nth 0 (nth 1 e))
2829 optional (nth 1 (nth 1 e))))
2830 (if bibtex-include-OPTkey
2832 "Used for reference key creation if author and editor fields are missing"
2833 (if (or (stringp bibtex-include-OPTkey)
2834 (functionp bibtex-include-OPTkey))
2835 bibtex-include-OPTkey))
2837 (if (member-ignore-case entry-type bibtex-include-OPTcrossref)
2838 (push '("crossref" "Reference key of the cross-referenced entry")
2840 (setq optional (append optional bibtex-user-optional-fields))
2841 (cons required optional)))
2843 (defun bibtex-entry (entry-type)
2844 "Insert a new BibTeX entry of type ENTRY-TYPE.
2845 After insertion call the value of `bibtex-add-entry-hook' if that value
2848 (let ((completion-ignore-case t))
2849 (list (completing-read "Entry Type: " bibtex-entry-field-alist
2850 nil t nil 'bibtex-entry-type-history))))
2851 (let ((key (if bibtex-maintain-sorted-entries
2852 (bibtex-read-key (format "%s key: " entry-type))))
2853 (field-list (bibtex-field-list entry-type)))
2854 (unless (bibtex-prepare-new-entry (list key nil entry-type))
2855 (error "Entry with key `%s' already exists" key))
2856 (indent-to-column bibtex-entry-offset)
2857 (insert "@" entry-type (bibtex-entry-left-delimiter))
2858 (if key (insert key))
2860 (mapc 'bibtex-make-field (car field-list))
2861 (mapc 'bibtex-make-optional-field (cdr field-list))
2862 (if bibtex-comma-after-last-field
2865 (indent-to-column bibtex-entry-offset)
2866 (insert (bibtex-entry-right-delimiter) "\n\n"))
2867 (bibtex-next-field t)
2868 (if (member-ignore-case entry-type bibtex-autofill-types)
2869 (bibtex-autofill-entry))
2870 (run-hooks 'bibtex-add-entry-hook)))
2872 (defun bibtex-entry-update (&optional entry-type)
2873 "Update an existing BibTeX entry.
2874 In the BibTeX entry at point, make new fields for those items that may occur
2875 according to `bibtex-field-list', but are not yet present.
2876 Also, add field delimiters to numerical fields if they are not present.
2877 If ENTRY-TYPE is non-nil, change first the entry type to ENTRY-TYPE.
2878 When called interactively with a prefix arg, query for a value of ENTRY-TYPE."
2880 (list (if current-prefix-arg
2881 (let ((completion-ignore-case t))
2882 (completing-read "New entry type: " bibtex-entry-field-alist
2883 nil t nil 'bibtex-entry-type-history)))))
2885 (bibtex-beginning-of-entry)
2886 (when (looking-at bibtex-entry-maybe-empty-head)
2887 (goto-char (match-end 0))
2890 (replace-match (concat "@" entry-type) nil nil nil 1))
2891 (setq entry-type (bibtex-type-in-head)))
2892 (let* ((field-list (bibtex-field-list entry-type))
2893 (required (copy-tree (car field-list)))
2894 (optional (copy-tree (cdr field-list)))
2896 (while (setq bounds (bibtex-parse-field))
2897 (let ((fname (bibtex-name-in-field bounds t))
2898 (end (copy-marker (bibtex-end-of-field bounds) t)))
2899 (setq required (delete (assoc-string fname required t) required)
2900 optional (delete (assoc-string fname optional t) optional))
2901 (when (string-match "\\`[0-9]+\\'"
2902 (bibtex-text-in-field-bounds bounds))
2903 (goto-char (bibtex-end-of-text-in-field bounds))
2904 (insert (bibtex-field-right-delimiter))
2905 (goto-char (bibtex-start-of-text-in-field bounds))
2906 (insert (bibtex-field-left-delimiter)))
2908 (skip-chars-backward " \t\n")
2909 (dolist (field required) (bibtex-make-field field))
2910 (dolist (field optional) (bibtex-make-optional-field field))))))
2912 (defun bibtex-parse-entry (&optional content)
2913 "Parse entry at point, return an alist.
2914 The alist elements have the form (FIELD . TEXT), where FIELD can also be
2915 the special strings \"=type=\" and \"=key=\". For the FIELD \"=key=\"
2916 TEXT may be nil. Remove \"OPT\" and \"ALT\" from FIELD.
2917 Move point to the end of the last field.
2918 If optional arg CONTENT is non-nil extract content of text fields."
2920 (when (looking-at bibtex-entry-maybe-empty-head)
2921 (push (cons "=type=" (bibtex-type-in-head)) alist)
2922 (push (cons "=key=" (bibtex-key-in-head)) alist)
2923 (goto-char (match-end 0))
2924 (while (setq bounds (bibtex-parse-field))
2925 (push (cons (bibtex-name-in-field bounds t)
2926 (bibtex-text-in-field-bounds bounds content))
2928 (goto-char (bibtex-end-of-field bounds))))
2931 (defun bibtex-autofill-entry ()
2932 "Try to fill fields of current BibTeX entry based on neighboring entries.
2933 The current entry must have a key. Determine the neighboring entry
2934 \(previouse or next\) whose key is more similar to the key of the current
2935 entry. For all empty fields of the current entry insert the corresponding
2936 field contents of the neighboring entry. Finally try to update the text
2937 based on the difference between the keys of the neighboring and the current
2938 entry (for example, the year parts of the keys)."
2940 (undo-boundary) ;So you can easily undo it, if it didn't work right.
2941 (bibtex-beginning-of-entry)
2942 (when (looking-at bibtex-entry-head)
2943 (let ((type (bibtex-type-in-head))
2944 (key (bibtex-key-in-head))
2945 (key-end (match-end bibtex-key-in-head))
2946 (case-fold-search t)
2947 (bibtex-sort-ignore-string-entries t)
2948 tmp other-key other bounds)
2949 ;; The fields we want to change start right after the key.
2951 ;; First see whether to use the previous or the next entry
2952 ;; for "inspiration".
2954 (goto-char (1- (match-beginning 0)))
2955 (bibtex-beginning-of-entry)
2956 (if (and (looking-at bibtex-entry-head)
2957 (bibtex-string= type (bibtex-type-in-head))
2958 ;; In case we found ourselves :-(
2959 (not (equal key (setq tmp (bibtex-key-in-head)))))
2963 (bibtex-end-of-entry)
2964 (bibtex-skip-to-valid-entry)
2965 (if (and (looking-at bibtex-entry-head)
2966 (bibtex-string= type (bibtex-type-in-head))
2967 ;; In case we found ourselves :-(
2968 (not (equal key (setq tmp (bibtex-key-in-head))))
2970 ;; Check which is the best match.
2971 (< (length (try-completion "" (list key other-key)))
2972 (length (try-completion "" (list key tmp))))))
2975 ;; Then fill the new entry's fields with the chosen other entry.
2977 (setq other (save-excursion (goto-char other) (bibtex-parse-entry)))
2978 (setq key-end (point)) ;In case parse-entry changed the buffer.
2979 (while (setq bounds (bibtex-parse-field))
2980 (let ((text (assoc-string (bibtex-name-in-field bounds t)
2983 (equal "" (bibtex-text-in-field-bounds bounds t))))
2984 (goto-char (bibtex-end-of-field bounds))
2985 (goto-char (bibtex-start-of-text-in-field bounds))
2986 (delete-region (point) (bibtex-end-of-text-in-field bounds))
2987 (insert (cdr text)))))
2988 ;; Finally try to update the text based on the difference between
2990 (let* ((prefix (try-completion "" (list key other-key)))
2991 ;; If the keys are foo91 and foo92, don't replace 1 for 2
2992 ;; but 91 for 92 instead.
2993 (_ (if (string-match "[0-9]+\\'" prefix)
2994 (setq prefix (substring prefix 0 (match-beginning 0)))))
2995 (suffix (substring key (length prefix)))
2996 (other-suffix (substring other-key (length prefix))))
2997 (while (re-search-backward (regexp-quote other-suffix) key-end 'move)
2998 (replace-match suffix)))))))
3000 (defun bibtex-print-help-message (&optional field comma)
3001 "Print helpful information about current FIELD in current BibTeX entry.
3002 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3004 (interactive (list nil t))
3005 (unless field (setq field (car (bibtex-find-text-internal nil nil comma))))
3006 (if (string-match "@" field)
3007 (cond ((bibtex-string= field "@string")
3008 (message "String definition"))
3009 ((bibtex-string= field "@preamble")
3010 (message "Preamble definition"))
3011 (t (message "Entry key")))
3012 (let* ((case-fold-search t)
3013 (type (save-excursion
3014 (bibtex-beginning-of-entry)
3015 (looking-at bibtex-entry-maybe-empty-head)
3016 (bibtex-type-in-head)))
3017 (field-list (bibtex-field-list type))
3018 (comment (assoc-string field (append (car field-list)
3019 (cdr field-list)) t)))
3020 (if comment (message "%s" (nth 1 comment))
3021 (message "No comment available")))))
3023 (defun bibtex-make-field (field &optional move interactive nodelim)
3024 "Make a field named FIELD in current BibTeX entry.
3025 FIELD is either a string or a list of the form
3026 \(FIELD-NAME COMMENT-STRING INIT ALTERNATIVE-FLAG) as in
3027 `bibtex-entry-field-alist'.
3028 If MOVE is non-nil, move point past the present field before making
3029 the new field. If INTERACTIVE is non-nil, move point to the end of
3030 the new field. Otherwise move point past the new field.
3031 MOVE and INTERACTIVE are t when called interactively.
3032 INIT is surrounded by field delimiters, unless NODELIM is non-nil."
3034 (list (let ((completion-ignore-case t)
3035 (field-list (bibtex-field-list
3037 (bibtex-beginning-of-entry)
3038 (looking-at bibtex-any-entry-maybe-empty-head)
3039 (bibtex-type-in-head)))))
3040 (completing-read "BibTeX field name: "
3041 (append (car field-list) (cdr field-list))
3042 nil nil nil bibtex-field-history))
3044 (unless (consp field)
3045 (setq field (list field)))
3048 (if (looking-at "[}\"]")
3051 (indent-to-column (+ bibtex-entry-offset bibtex-field-indentation))
3052 (if (nth 3 field) (insert "ALT"))
3053 (insert (car field) " ")
3054 (if bibtex-align-at-equal-sign
3055 (indent-to-column (+ bibtex-entry-offset
3056 (- bibtex-text-indentation 2))))
3058 (unless bibtex-align-at-equal-sign
3059 (indent-to-column (+ bibtex-entry-offset
3060 bibtex-text-indentation)))
3061 (let ((init (nth 2 field)))
3062 (if (not init) (setq init "")
3063 (if (functionp init) (setq init (funcall init)))
3064 (unless (stringp init) (error "`%s' is not a string" init)))
3065 ;; NODELIM is required by `bibtex-insert-kill'
3066 (if nodelim (insert init)
3067 (insert (bibtex-field-left-delimiter) init
3068 (bibtex-field-right-delimiter))))
3070 ;; (bibtex-find-text nil nil bibtex-help-message)
3071 (if (memq (preceding-char) '(?} ?\")) (forward-char -1))
3072 (if bibtex-help-message (bibtex-print-help-message (car field)))))
3074 (defun bibtex-beginning-of-entry ()
3075 "Move to beginning of BibTeX entry (beginning of line).
3076 If inside an entry, move to the beginning of it, otherwise move to the
3077 beginning of the previous entry. If point is ahead of all BibTeX entries
3078 move point to the beginning of buffer. Return the new location of point."
3080 (skip-chars-forward " \t")
3081 (if (looking-at "@")
3083 (re-search-backward "^[ \t]*@" nil 'move)
3086 (defun bibtex-end-of-entry ()
3087 "Move to end of BibTeX entry (past the closing brace).
3088 If inside an entry, move to the end of it, otherwise move to the end
3089 of the previous entry. Do not move if ahead of first entry.
3090 Return the new location of point."
3092 (let ((case-fold-search t)
3094 (_ (bibtex-beginning-of-entry))
3095 (bounds (bibtex-valid-entry t)))
3096 (cond (bounds (goto-char (cdr bounds))) ; regular entry
3097 ;; @String or @Preamble
3098 ((setq bounds (or (bibtex-parse-string t) (bibtex-parse-preamble)))
3099 (goto-char (bibtex-end-of-string bounds)))
3100 ((looking-at bibtex-any-valid-entry-type)
3101 ;; Parsing of entry failed
3102 (error "Syntactically incorrect BibTeX entry starts here."))
3103 (t (if (interactive-p) (message "Not on a known BibTeX entry."))
3107 (defun bibtex-goto-line (arg)
3108 "Goto line ARG, counting from beginning of (narrowed) buffer."
3109 ;; code adapted from `goto-line'
3110 (goto-char (point-min))
3111 (if (eq selective-display t)
3112 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
3113 (forward-line (1- arg))))
3115 (defun bibtex-reposition-window ()
3116 "Make the current BibTeX entry visible.
3117 If entry is smaller than `window-body-height', entry is centered in window.
3118 Otherwise display the beginning of entry."
3121 (beg (line-number-at-pos (bibtex-beginning-of-entry)))
3122 (end (line-number-at-pos (bibtex-end-of-entry))))
3123 (if (> (window-body-height) (- end beg))
3124 ;; entry fits in current window
3126 (bibtex-goto-line (/ (+ 1 beg end) 2))
3129 ;; entry too large for current window
3130 (bibtex-goto-line beg)
3132 (if (> (1+ (- (line-number-at-pos pnt) beg))
3133 (window-body-height))
3134 (bibtex-goto-line beg)
3137 (defun bibtex-mark-entry ()
3138 "Put mark at beginning, point at end of current BibTeX entry."
3140 (set-mark (bibtex-beginning-of-entry))
3141 (bibtex-end-of-entry))
3143 (defun bibtex-count-entries (&optional count-string-entries)
3144 "Count number of entries in current buffer or region.
3145 With prefix argument COUNT-STRING-ENTRIES count all entries,
3146 otherwise count all entries except @String entries.
3147 If mark is active count entries in region, if not in whole buffer."
3150 (bibtex-sort-ignore-string-entries (not count-string-entries)))
3152 (if mark-active (narrow-to-region (region-beginning) (region-end)))
3153 (bibtex-map-entries (lambda (key beg end) (setq number (1+ number)))))
3154 (message "%s contains %d entries."
3155 (if mark-active "Region" "Buffer")
3158 (defun bibtex-ispell-entry ()
3159 "Check BibTeX entry for spelling errors."
3161 (ispell-region (save-excursion (bibtex-beginning-of-entry))
3162 (save-excursion (bibtex-end-of-entry))))
3164 (defun bibtex-ispell-abstract ()
3165 "Check abstract of BibTeX entry for spelling errors."
3167 (let ((bounds (save-excursion
3168 (bibtex-beginning-of-entry)
3169 (bibtex-search-forward-field "abstract" t))))
3171 (ispell-region (bibtex-start-of-text-in-field bounds)
3172 (bibtex-end-of-text-in-field bounds))
3173 (error "No abstract in entry"))))
3175 (defun bibtex-narrow-to-entry ()
3176 "Narrow buffer to current BibTeX entry."
3180 (narrow-to-region (bibtex-beginning-of-entry)
3181 (bibtex-end-of-entry))))
3183 (defun bibtex-entry-index ()
3184 "Return index of BibTeX entry head at or past position of point.
3185 The index is a list (KEY CROSSREF-KEY ENTRY-NAME) that is used for sorting
3186 the entries of the BibTeX buffer. CROSSREF-KEY is nil unless the value
3187 of `bibtex-maintain-sorted-entries' is `crossref'. Move point to the end
3188 of the head of the entry found. Return nil if no entry found."
3189 (let ((case-fold-search t))
3190 (if (re-search-forward bibtex-entry-maybe-empty-head nil t)
3191 (let ((key (bibtex-key-in-head))
3192 ;; all entry names should be downcase (for ease of comparison)
3193 (entry-name (downcase (bibtex-type-in-head))))
3194 ;; Don't search CROSSREF-KEY if we don't need it.
3195 (if (eq bibtex-maintain-sorted-entries 'crossref)
3196 (let ((bounds (bibtex-search-forward-field
3197 "\\(OPT\\)?crossref" t)))
3199 (if bounds (bibtex-text-in-field-bounds bounds t))
3201 (list key nil entry-name))))))
3203 (defun bibtex-init-sort-entry-class-alist ()
3204 (unless (local-variable-p 'bibtex-sort-entry-class-alist)
3205 (set (make-local-variable 'bibtex-sort-entry-class-alist)
3207 (dolist (class bibtex-sort-entry-class alist)
3209 (dolist (entry class)
3210 ;; All entry names should be downcase (for ease of comparison).
3211 (push (cons (if (stringp entry) (downcase entry) entry) i)
3214 (defun bibtex-lessp (index1 index2)
3215 "Predicate for sorting BibTeX entries with indices INDEX1 and INDEX2.
3216 Each index is a list (KEY CROSSREF-KEY ENTRY-NAME).
3217 The predicate depends on the variable `bibtex-maintain-sorted-entries'.
3218 If its value is nil use plain sorting."
3219 (cond ((not index1) (not index2)) ; indices can be nil
3221 ((eq bibtex-maintain-sorted-entries 'crossref)
3224 (or (string-lessp (nth 1 index1) (nth 1 index2))
3225 (and (string-equal (nth 1 index1) (nth 1 index2))
3226 (string-lessp (nth 0 index1) (nth 0 index2))))
3227 (not (string-lessp (nth 0 index2) (nth 1 index1))))
3229 (string-lessp (nth 0 index1) (nth 1 index2))
3230 (string-lessp (nth 0 index1) (nth 0 index2)))))
3231 ((eq bibtex-maintain-sorted-entries 'entry-class)
3232 (let ((n1 (cdr (or (assoc (nth 2 index1) bibtex-sort-entry-class-alist)
3233 (assoc 'catch-all bibtex-sort-entry-class-alist)
3234 '(nil . 1000)))) ; if there is nothing else
3235 (n2 (cdr (or (assoc (nth 2 index2) bibtex-sort-entry-class-alist)
3236 (assoc 'catch-all bibtex-sort-entry-class-alist)
3237 '(nil . 1000))))) ; if there is nothing else
3240 (string-lessp (car index1) (car index2))))))
3241 (t ; (eq bibtex-maintain-sorted-entries 'plain)
3242 (string-lessp (car index1) (car index2)))))
3244 (defun bibtex-sort-buffer ()
3245 "Sort BibTeX buffer alphabetically by key.
3246 The predicate for sorting is defined via `bibtex-maintain-sorted-entries'.
3247 If its value is nil use plain sorting. Text outside of BibTeX entries is not
3248 affected. If `bibtex-sort-ignore-string-entries' is non-nil, @String entries
3251 (bibtex-beginning-of-first-entry) ; Needed by `sort-subr'
3252 (bibtex-init-sort-entry-class-alist) ; Needed by `bibtex-lessp'.
3254 'bibtex-skip-to-valid-entry ; NEXTREC function
3255 'bibtex-end-of-entry ; ENDREC function
3256 'bibtex-entry-index ; STARTKEY function
3257 nil ; ENDKEY function
3258 'bibtex-lessp)) ; PREDICATE
3260 (defun bibtex-find-crossref (crossref-key &optional pnt split)
3261 "Move point to the beginning of BibTeX entry CROSSREF-KEY.
3262 If `bibtex-files' is non-nil, search all these files.
3263 Otherwise the search is limited to the current buffer.
3264 Return position of entry if CROSSREF-KEY is found or nil otherwise.
3265 If CROSSREF-KEY is in the same buffer like current entry but before it
3266 an error is signaled. Optional arg PNT is the position of the referencing
3267 entry. It defaults to position of point. If optional arg SPLIT is non-nil,
3268 split window so that both the referencing and the crossrefed entry are
3270 If called interactively, CROSSREF-KEY defaults to crossref key of current
3271 entry and SPLIT is t."
3275 (bibtex-beginning-of-entry)
3276 (let ((bounds (bibtex-search-forward-field "crossref" t)))
3278 (bibtex-text-in-field-bounds bounds t))))))
3279 (list (bibtex-read-key "Find crossref key: " crossref-key t)
3281 (let (buffer pos eqb)
3283 (setq pos (bibtex-find-entry crossref-key t)
3284 buffer (current-buffer)))
3285 (setq eqb (eq buffer (current-buffer)))
3287 (if split (message "Crossref key `%s' not found" crossref-key)))
3288 (split ; called (quasi) interactively
3289 (unless pnt (setq pnt (point)))
3291 (if eqb (select-window (split-window))
3292 (pop-to-buffer buffer))
3294 (bibtex-reposition-window)
3296 (if (and eqb (> pnt pos))
3297 (error "The referencing entry must precede the crossrefed entry!")))
3298 ;; `bibtex-find-crossref' is called noninteractively during
3299 ;; clean-up of an entry. Then it is not possible to check
3300 ;; whether the current entry and the crossrefed entry have
3301 ;; the correct sorting order.
3302 (eqb (goto-char pos))
3303 (t (set-buffer buffer) (goto-char pos)))
3306 (defun bibtex-find-entry (key &optional global start display)
3307 "Move point to the beginning of BibTeX entry named KEY.
3308 Return position of entry if KEY is found or nil if not found.
3309 With prefix arg GLOBAL non-nil, search KEY in `bibtex-files'.
3310 Otherwise the search is limited to the current buffer.
3311 Optional arg START is buffer position where the search starts.
3312 If it is nil, start search at beginning of buffer.
3313 If DISPLAY is non-nil, display the buffer containing KEY.
3314 Otherwise, use `set-buffer'. DISPLAY is t when called interactively."
3315 (interactive (list (bibtex-read-key "Find key: " nil current-prefix-arg)
3316 current-prefix-arg nil t))
3317 (if (and global bibtex-files)
3318 (let ((buffer-list (bibtex-files-expand t))
3320 (while (and (not found)
3321 (setq buffer (pop buffer-list)))
3322 (with-current-buffer buffer
3323 (if (cdr (assoc-string key bibtex-reference-keys))
3324 ;; `bibtex-find-entry' moves point if key found
3325 (setq found (bibtex-find-entry key)))))
3326 (cond ((and found display)
3327 (let ((same-window-buffer-names
3328 (cons (buffer-name buffer) same-window-buffer-names)))
3329 (pop-to-buffer buffer)
3330 (bibtex-reposition-window)))
3331 (found (set-buffer buffer))
3332 (display (message "Key `%s' not found" key)))
3335 (let* ((case-fold-search t)
3336 (pnt (save-excursion
3337 (goto-char (or start (point-min)))
3338 (if (re-search-forward (concat "^[ \t]*\\("
3340 "\\)[ \t]*[({][ \t\n]*\\("
3344 (match-beginning 0)))))
3347 (if display (bibtex-reposition-window)))
3348 (display (message "Key `%s' not found" key)))
3351 (defun bibtex-prepare-new-entry (index)
3352 "Prepare a new BibTeX entry with index INDEX.
3353 INDEX is a list (KEY CROSSREF-KEY ENTRY-NAME).
3354 Move point where the entry KEY should be placed.
3355 If `bibtex-maintain-sorted-entries' is non-nil, perform a binary
3356 search to look for place for KEY. This requires that buffer is sorted,
3357 see `bibtex-validate'.
3358 Return t if preparation was successful or nil if entry KEY already exists."
3359 (bibtex-init-sort-entry-class-alist) ; Needed by `bibtex-lessp'.
3360 (let ((key (nth 0 index))
3362 (cond ((or (null key)
3364 (string-equal key ""))
3365 (and (not (setq key-exist (bibtex-find-entry key)))
3366 (not bibtex-maintain-sorted-entries)))
3367 (bibtex-move-outside-of-entry))
3368 ;; if key-exist is non-nil due to the previous cond clause
3369 ;; then point will be at beginning of entry named key.
3371 (t ; bibtex-maintain-sorted-entries is non-nil
3372 (let* ((case-fold-search t)
3373 (left (save-excursion (bibtex-beginning-of-first-entry)))
3374 (bounds (save-excursion (goto-char (point-max))
3375 (bibtex-skip-to-valid-entry t)))
3376 (right (if bounds (cdr bounds) (point-min)))
3377 (found (if (>= left right) left))
3382 (goto-char (/ (+ left right) 2))
3383 (bibtex-skip-to-valid-entry t)
3384 (setq actual-index (bibtex-entry-index))
3385 (cond ((bibtex-lessp index actual-index)
3386 (setq new (bibtex-beginning-of-entry))
3387 (if (equal right new)
3391 (bibtex-end-of-entry)
3392 (bibtex-skip-to-valid-entry)
3394 (if (equal left new)
3396 (setq left new))))))
3398 (bibtex-beginning-of-entry)
3399 (setq actual-index (save-excursion (bibtex-entry-index)))
3400 (when (or (not actual-index)
3401 (bibtex-lessp actual-index index))
3402 ;; buffer contains no valid entries or
3403 ;; greater than last entry --> append
3404 (bibtex-end-of-entry)
3405 (unless (bobp) (newline (forward-line 2)))
3406 (beginning-of-line)))))
3407 (unless key-exist t)))
3409 (defun bibtex-validate (&optional test-thoroughly)
3410 "Validate if buffer or region is syntactically correct.
3411 Check also for duplicate keys and correct sort order provided
3412 `bibtex-maintain-sorted-entries' is non-nil.
3413 With optional argument TEST-THOROUGHLY non-nil check also for
3414 the absence of required fields and for questionable month fields.
3415 If mark is active, validate current region, if not the whole buffer.
3416 Only check known entry types, so you can put comments outside of entries.
3417 Return t if test was successful, nil otherwise."
3419 (let* ((case-fold-search t)
3420 error-list syntax-error)
3423 (if mark-active (narrow-to-region (region-beginning) (region-end)))
3425 ;; Check syntactical structure of entries
3426 (goto-char (point-min))
3427 (bibtex-progress-message "Checking syntactical structure")
3429 (while (setq end (re-search-forward "^[ \t]*@" nil t))
3430 (bibtex-progress-message)
3431 (goto-char (match-beginning 0))
3432 (cond ((setq bounds (bibtex-valid-entry))
3433 (goto-char (cdr bounds)))
3434 ((setq bounds (or (bibtex-parse-string)
3435 (bibtex-parse-preamble)))
3436 (goto-char (bibtex-end-of-string bounds)))
3437 ((looking-at bibtex-any-valid-entry-type)
3438 (push (cons (bibtex-current-line)
3439 "Syntax error (check esp. commas, braces, and quotes)")
3441 (goto-char (match-end 0)))
3442 (t (goto-char end)))))
3443 (bibtex-progress-message 'done)
3446 ;; Continue only if there were no syntax errors.
3447 (setq syntax-error t)
3449 ;; Check for duplicate keys and correct sort order
3450 (let (previous current key-list)
3451 (bibtex-progress-message "Checking for duplicate keys")
3453 (lambda (key beg end)
3454 (bibtex-progress-message)
3455 (setq current (bibtex-entry-index))
3456 (cond ((not previous))
3457 ((member key key-list)
3458 (push (cons (bibtex-current-line)
3459 (format "Duplicate key `%s'" key))
3461 ((and bibtex-maintain-sorted-entries
3462 (not (bibtex-lessp previous current)))
3463 (push (cons (bibtex-current-line)
3464 "Entries out of order")
3467 (setq previous current)))
3468 (bibtex-progress-message 'done))
3470 ;; Check for duplicate keys in `bibtex-files'.
3472 ;; We don't want to be fooled by outdated `bibtex-reference-keys'.
3473 (dolist (buffer (bibtex-files-expand nil t))
3474 (dolist (key (with-current-buffer buffer bibtex-reference-keys))
3475 (when (and (cdr key)
3476 (cdr (assoc-string (car key) bibtex-reference-keys)))
3477 (bibtex-find-entry (car key))
3478 (push (cons (bibtex-current-line)
3479 (format "Duplicate key `%s' in %s" (car key)
3480 (abbreviate-file-name (buffer-file-name buffer))))
3483 (when test-thoroughly
3484 (bibtex-progress-message
3485 "Checking required fields and month fields")
3486 (let ((bibtex-sort-ignore-string-entries t))
3488 (lambda (key beg end)
3489 (bibtex-progress-message)
3490 (let* ((entry-list (assoc-string (bibtex-type-in-head)
3491 bibtex-entry-field-alist t))
3492 (req (copy-sequence (elt (elt entry-list 1) 0)))
3493 (creq (copy-sequence (elt (elt entry-list 2) 0)))
3494 crossref-there bounds alt-there field)
3495 (bibtex-beginning-first-field beg)
3496 (while (setq bounds (bibtex-parse-field))
3497 (let ((field-name (bibtex-name-in-field bounds)))
3498 (if (and (bibtex-string= field-name "month")
3499 ;; Check only abbreviated month fields.
3500 (let ((month (bibtex-text-in-field-bounds bounds)))
3501 (not (or (string-match "\\`[\"{].+[\"}]\\'" month)
3504 bibtex-predefined-month-strings t)))))
3505 (push (cons (bibtex-current-line)
3506 "Questionable month field")
3508 (setq field (assoc-string field-name req t)
3509 req (delete field req)
3510 creq (delete (assoc-string field-name creq t) creq))
3513 (push (cons (bibtex-current-line)
3514 "More than one non-empty alternative")
3516 (setq alt-there t)))
3517 (if (bibtex-string= field-name "crossref")
3518 (setq crossref-there t)))
3519 (goto-char (bibtex-end-of-field bounds)))
3520 (if crossref-there (setq req creq))
3524 (push (car field) alt)
3525 (push (cons (save-excursion (goto-char beg)
3526 (bibtex-current-line))
3527 (format "Required field `%s' missing"
3530 ;; The following fails if there are more than two
3531 ;; alternatives in a BibTeX entry, which isn't
3532 ;; the case momentarily.
3534 (push (cons (save-excursion (goto-char beg)
3535 (bibtex-current-line))
3536 (format "Alternative fields `%s'/`%s' missing"
3537 (car alt) (cadr alt)))
3539 (bibtex-progress-message 'done)))))
3542 (let ((file (file-name-nondirectory (buffer-file-name)))
3543 (dir default-directory)
3544 (err-buf "*BibTeX validation errors*"))
3545 (setq error-list (sort error-list 'car-less-than-car))
3546 (with-current-buffer (get-buffer-create err-buf)
3547 (setq default-directory dir)
3548 (unless (eq major-mode 'compilation-mode) (compilation-mode))
3549 (toggle-read-only -1)
3550 (delete-region (point-min) (point-max))
3551 (insert "BibTeX mode command `bibtex-validate'\n"
3553 "Maybe undetected errors due to syntax errors. Correct and validate again.\n"
3555 (dolist (err error-list)
3556 (insert (format "%s:%d: %s\n" file (car err) (cdr err))))
3557 (set-buffer-modified-p nil)
3558 (toggle-read-only 1)
3559 (goto-line 3)) ; first error message
3560 (display-buffer err-buf)
3561 nil) ; return `nil' (i.e., buffer is invalid)
3562 (message "%s is syntactically correct"
3563 (if mark-active "Region" "Buffer"))
3564 t))) ; return `t' (i.e., buffer is valid)
3566 (defun bibtex-validate-globally (&optional strings)
3567 "Check for duplicate keys in `bibtex-files'.
3568 With optional prefix arg STRINGS, check for duplicate strings, too.
3569 Return t if test was successful, nil otherwise."
3571 (let ((buffer-list (bibtex-files-expand t))
3572 buffer-key-list current-buf current-keys error-list)
3573 ;; Check for duplicate keys within BibTeX buffer
3574 (dolist (buffer buffer-list)
3577 (let (entry-type key key-list)
3578 (goto-char (point-min))
3579 (while (re-search-forward bibtex-entry-head nil t)
3580 (setq entry-type (bibtex-type-in-head)
3581 key (bibtex-key-in-head))
3582 (if (or (and strings (bibtex-string= entry-type "string"))
3583 (assoc-string entry-type bibtex-entry-field-alist t))
3584 (if (member key key-list)
3585 (push (format "%s:%d: Duplicate key `%s'\n"
3587 (bibtex-current-line) key)
3589 (push key key-list))))
3590 (push (cons buffer key-list) buffer-key-list))))
3592 ;; Check for duplicate keys among BibTeX buffers
3593 (while (setq current-buf (pop buffer-list))
3594 (setq current-keys (cdr (assq current-buf buffer-key-list)))
3595 (with-current-buffer current-buf
3596 (dolist (buffer buffer-list)
3597 (dolist (key (cdr (assq buffer buffer-key-list)))
3598 (when (assoc-string key current-keys)
3599 (bibtex-find-entry key)
3600 (push (format "%s:%d: Duplicate key `%s' in %s\n"
3601 (buffer-file-name) (bibtex-current-line) key
3602 (abbreviate-file-name (buffer-file-name buffer)))
3605 ;; Process error list
3607 (let ((err-buf "*BibTeX validation errors*"))
3608 (with-current-buffer (get-buffer-create err-buf)
3609 (unless (eq major-mode 'compilation-mode) (compilation-mode))
3610 (toggle-read-only -1)
3611 (delete-region (point-min) (point-max))
3612 (insert "BibTeX mode command `bibtex-validate-globally'\n\n")
3613 (dolist (err (sort error-list 'string-lessp)) (insert err))
3614 (set-buffer-modified-p nil)
3615 (toggle-read-only 1)
3616 (goto-line 3)) ; first error message
3617 (display-buffer err-buf)
3618 nil) ; return `nil' (i.e., buffer is invalid)
3619 (message "No duplicate keys.")
3620 t))) ; return `t' (i.e., buffer is valid)
3622 (defun bibtex-next-field (begin &optional comma)
3623 "Move point to end of text of next BibTeX field or entry head.
3624 With prefix BEGIN non-nil, move point to its beginning. Optional arg COMMA
3625 is as in `bibtex-enclosing-field'. It is t for interactive calls."
3626 (interactive (list current-prefix-arg t))
3627 (let ((bounds (bibtex-find-text-internal t nil comma))
3630 (setq end-of-entry t)
3631 (goto-char (nth 3 bounds))
3632 (if (assoc-string (car bounds) '("@String" "@Preamble") t)
3633 (setq end-of-entry t)
3634 ;; BibTeX key or field
3635 (if (looking-at ",[ \t\n]*") (goto-char (match-end 0)))
3637 (if (looking-at "[)}][ \t\n]*") (setq end-of-entry t))))
3638 (if (and end-of-entry
3639 (re-search-forward bibtex-any-entry-maybe-empty-head nil t))
3640 (goto-char (match-beginning 0)))
3641 (bibtex-find-text begin nil bibtex-help-message)))
3643 (defun bibtex-find-text (&optional begin noerror help comma)
3644 "Move point to end of text of current BibTeX field or entry head.
3645 With optional prefix BEGIN non-nil, move point to its beginning.
3646 Unless NOERROR is non-nil, an error is signaled if point is not
3647 on a BibTeX field. If optional arg HELP is non-nil print help message.
3648 When called interactively, the value of HELP is `bibtex-help-message'.
3649 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3651 (interactive (list current-prefix-arg nil bibtex-help-message t))
3652 (let ((bounds (bibtex-find-text-internal t nil comma)))
3655 (progn (goto-char (nth 1 bounds))
3656 (if (looking-at "[{\"]")
3658 (goto-char (nth 2 bounds))
3659 (if (memq (preceding-char) '(?} ?\"))
3661 (if help (bibtex-print-help-message (car bounds))))
3662 ((not noerror) (error "Not on BibTeX field")))))
3664 (defun bibtex-find-text-internal (&optional noerror subfield comma)
3665 "Find text part of current BibTeX field or entry head.
3666 Return list (NAME START-TEXT END-TEXT END STRING-CONST) with field
3667 or entry name, start and end of text, and end of field or entry head.
3668 STRING-CONST is a flag which is non-nil if current subfield delimited by #
3669 is a BibTeX string constant. Return value is nil if field or entry head
3671 If optional arg NOERROR is non-nil, an error message is suppressed
3672 if text is not found. If optional arg SUBFIELD is non-nil START-TEXT
3673 and END-TEXT correspond to the current subfield delimited by #.
3674 Optional arg COMMA is as in `bibtex-enclosing-field'."
3677 (bounds (bibtex-enclosing-field comma t))
3678 (case-fold-search t)
3679 name start-text end-text end failure done no-sub string-const)
3680 (bibtex-beginning-of-entry)
3682 (setq name (bibtex-name-in-field bounds t)
3683 start-text (bibtex-start-of-text-in-field bounds)
3684 end-text (bibtex-end-of-text-in-field bounds)
3685 end (bibtex-end-of-field bounds)))
3687 ((setq bounds (bibtex-parse-string t))
3688 (if (<= pnt (bibtex-end-of-string bounds))
3689 (setq name "@String" ;; not a field name!
3690 start-text (bibtex-start-of-text-in-string bounds)
3691 end-text (bibtex-end-of-text-in-string bounds)
3692 end (bibtex-end-of-string bounds))
3695 ((setq bounds (bibtex-parse-preamble))
3696 (if (<= pnt (bibtex-end-of-string bounds))
3697 (setq name "@Preamble" ;; not a field name!
3698 start-text (bibtex-start-of-text-in-string bounds)
3699 end-text (bibtex-end-of-text-in-string bounds)
3700 end (bibtex-end-of-string bounds))
3703 ((looking-at bibtex-entry-maybe-empty-head)
3704 (goto-char (match-end 0))
3705 (if comma (save-match-data
3706 (re-search-forward "\\=[ \t\n]*," nil t)))
3707 (if (<= pnt (point))
3708 (setq name (match-string-no-properties bibtex-type-in-head)
3709 start-text (or (match-beginning bibtex-key-in-head)
3711 end-text (or (match-end bibtex-key-in-head)
3714 no-sub t) ;; subfields do not make sense
3716 (t (setq failure t)))
3717 (when (and subfield (not failure))
3718 (setq failure no-sub)
3720 (goto-char start-text)
3722 (if (or (prog1 (looking-at bibtex-field-const)
3723 (setq end-text (match-end 0)
3725 (prog1 (setq bounds (bibtex-parse-field-string))
3726 (setq end-text (cdr bounds)
3729 (if (and (<= start-text pnt) (<= pnt end-text))
3731 (goto-char end-text))
3732 (if (looking-at "[ \t\n]*#[ \t\n]*")
3733 (setq start-text (goto-char (match-end 0)))))
3734 (setq done t failure t)))))
3735 (cond ((not failure)
3736 (list name start-text end-text end string-const))
3737 ((and no-sub (not noerror))
3738 (error "Not on text part of BibTeX field"))
3739 ((not noerror) (error "Not on BibTeX field"))))))
3741 (defun bibtex-remove-OPT-or-ALT (&optional comma)
3742 "Remove the string starting optional/alternative fields.
3743 Align text and go thereafter to end of text. Optional arg COMMA
3744 is as in `bibtex-enclosing-field'. It is t for interactive calls."
3745 (interactive (list t))
3746 (let ((case-fold-search t)
3747 (bounds (bibtex-enclosing-field comma)))
3749 (goto-char (bibtex-start-of-name-in-field bounds))
3750 (when (looking-at "OPT\\|ALT")
3751 (delete-region (match-beginning 0) (match-end 0))
3752 ;; make field non-OPT
3753 (search-forward "=")
3755 (delete-horizontal-space)
3756 (if bibtex-align-at-equal-sign
3757 (indent-to-column (- bibtex-text-indentation 2))
3759 (search-forward "=")
3760 (delete-horizontal-space)
3761 (if bibtex-align-at-equal-sign
3763 (indent-to-column bibtex-text-indentation))))))
3765 (defun bibtex-remove-delimiters (&optional comma)
3766 "Remove \"\" or {} around current BibTeX field text.
3767 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3769 (interactive (list t))
3770 (let ((bounds (bibtex-find-text-internal nil t comma)))
3771 (unless (nth 4 bounds)
3772 (delete-region (1- (nth 2 bounds)) (nth 2 bounds))
3773 (delete-region (nth 1 bounds) (1+ (nth 1 bounds))))))
3775 (defun bibtex-kill-field (&optional copy-only comma)
3776 "Kill the entire enclosing BibTeX field.
3777 With prefix arg COPY-ONLY, copy the current field to `bibtex-field-kill-ring',
3778 but do not actually kill it. Optional arg COMMA is as in
3779 `bibtex-enclosing-field'. It is t for interactive calls."
3780 (interactive (list current-prefix-arg t))
3782 (let* ((case-fold-search t)
3783 (bounds (bibtex-enclosing-field comma))
3784 (end (bibtex-end-of-field bounds))
3785 (beg (bibtex-start-of-field bounds)))
3787 (skip-chars-forward ",")
3788 (push (list (bibtex-name-in-field bounds) nil
3789 (bibtex-text-in-field-bounds bounds))
3790 bibtex-field-kill-ring)
3791 (if (> (length bibtex-field-kill-ring) bibtex-field-kill-ring-max)
3792 (setcdr (nthcdr (1- bibtex-field-kill-ring-max)
3793 bibtex-field-kill-ring)
3795 (setq bibtex-field-kill-ring-yank-pointer bibtex-field-kill-ring)
3797 (delete-region beg end))))
3798 (setq bibtex-last-kill-command 'field))
3800 (defun bibtex-copy-field-as-kill (&optional comma)
3801 "Copy the BibTeX field at point to the kill ring.
3802 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3804 (interactive (list t))
3805 (bibtex-kill-field t comma))
3807 (defun bibtex-kill-entry (&optional copy-only)
3808 "Kill the entire enclosing BibTeX entry.
3809 With prefix arg COPY-ONLY, copy the current entry to `bibtex-entry-kill-ring',
3810 but do not actually kill it."
3813 (let* ((case-fold-search t)
3814 (beg (bibtex-beginning-of-entry))
3815 (end (progn (bibtex-end-of-entry)
3816 (if (re-search-forward
3817 bibtex-any-entry-maybe-empty-head nil 'move)
3818 (goto-char (match-beginning 0)))
3820 (push (buffer-substring-no-properties beg end)
3821 bibtex-entry-kill-ring)
3822 (if (> (length bibtex-entry-kill-ring) bibtex-entry-kill-ring-max)
3823 (setcdr (nthcdr (1- bibtex-entry-kill-ring-max)
3824 bibtex-entry-kill-ring)
3826 (setq bibtex-entry-kill-ring-yank-pointer bibtex-entry-kill-ring)
3828 (delete-region beg end))))
3829 (setq bibtex-last-kill-command 'entry))
3831 (defun bibtex-copy-entry-as-kill ()
3832 "Copy the entire enclosing BibTeX entry to `bibtex-entry-kill-ring'."
3834 (bibtex-kill-entry t))
3836 (defun bibtex-yank (&optional n)
3837 "Reinsert the last BibTeX item.
3838 More precisely, reinsert the field or entry killed or yanked most recently.
3839 With argument N, reinsert the Nth most recently killed BibTeX item.
3840 See also the command \\[bibtex-yank-pop]."
3842 (bibtex-insert-kill (1- n) t)
3843 (setq this-command 'bibtex-yank))
3845 (defun bibtex-yank-pop (n)
3846 "Replace just-yanked killed BibTeX item with a different item.
3847 This command is allowed only immediately after a `bibtex-yank' or a
3848 `bibtex-yank-pop'. In this case, the region contains a reinserted
3849 previously killed BibTeX item. `bibtex-yank-pop' deletes that item
3850 and inserts in its place a different killed BibTeX item.
3852 With no argument, the previous kill is inserted.
3853 With argument N, insert the Nth previous kill.
3854 If N is negative, this is a more recent kill.
3856 The sequence of kills wraps around, so that after the oldest one
3857 comes the newest one."
3859 (unless (eq last-command 'bibtex-yank)
3860 (error "Previous command was not a BibTeX yank"))
3861 (setq this-command 'bibtex-yank)
3862 (let ((inhibit-read-only t))
3863 (delete-region (point) (mark t))
3864 (bibtex-insert-kill n t)))
3866 (defun bibtex-empty-field (&optional comma)
3867 "Delete the text part of the current field, replace with empty text.
3868 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3870 (interactive (list t))
3871 (let ((bounds (bibtex-enclosing-field comma)))
3872 (goto-char (bibtex-start-of-text-in-field bounds))
3873 (delete-region (point) (bibtex-end-of-text-in-field bounds))
3874 (insert (bibtex-field-left-delimiter)
3875 (bibtex-field-right-delimiter))
3876 (bibtex-find-text t nil bibtex-help-message)))
3878 (defun bibtex-pop-previous (arg)
3879 "Replace text of current field with the similar field in previous entry.
3880 With arg, goes up ARG entries. Repeated, goes up so many times. May be
3881 intermixed with \\[bibtex-pop-next] (bibtex-pop-next)."
3883 (bibtex-pop arg 'previous))
3885 (defun bibtex-pop-next (arg)
3886 "Replace text of current field with the text of similar field in next entry.
3887 With arg, goes down ARG entries. Repeated, goes down so many times. May be
3888 intermixed with \\[bibtex-pop-previous] (bibtex-pop-previous)."
3890 (bibtex-pop arg 'next))
3892 (defun bibtex-clean-entry (&optional new-key called-by-reformat)
3893 "Finish editing the current BibTeX entry and clean it up.
3894 Check that no required fields are empty and formats entry dependent
3895 on the value of `bibtex-entry-format'.
3896 If the reference key of the entry is empty or a prefix argument is given,
3897 calculate a new reference key. (Note: this works only if fields in entry
3898 begin on separate lines prior to calling `bibtex-clean-entry' or if
3899 'realign is contained in `bibtex-entry-format'.)
3900 Don't call `bibtex-clean-entry' on @Preamble entries.
3901 At end of the cleaning process, the functions in
3902 `bibtex-clean-entry-hook' are called with region narrowed to entry."
3903 ;; Opt. arg called-by-reformat is t if bibtex-clean-entry
3904 ;; is called by bibtex-reformat
3906 (let ((case-fold-search t)
3907 (start (bibtex-beginning-of-entry))
3908 (_ (or (looking-at bibtex-any-entry-maybe-empty-head)
3909 (error "Not inside a BibTeX entry")))
3910 (entry-type (bibtex-type-in-head))
3911 (key (bibtex-key-in-head)))
3913 (cond ((bibtex-string= entry-type "preamble")
3914 ;; (bibtex-format-preamble)
3915 (error "No clean up of @Preamble entries"))
3916 ((bibtex-string= entry-type "string")
3917 (setq entry-type 'string))
3918 ;; (bibtex-format-string)
3919 (t (bibtex-format-entry)))
3921 (when (or new-key (not key))
3922 (setq key (bibtex-generate-autokey))
3923 ;; Sometimes bibtex-generate-autokey returns an empty string
3924 (if (or bibtex-autokey-edit-before-use (string= "" key))
3925 (setq key (if (eq entry-type 'string)
3926 (bibtex-read-string-key key)
3927 (bibtex-read-key "Key to use: " key))))
3929 (re-search-forward (if (eq entry-type 'string)
3930 bibtex-string-maybe-empty-head
3931 bibtex-entry-maybe-empty-head))
3932 (if (match-beginning bibtex-key-in-head)
3933 (delete-region (match-beginning bibtex-key-in-head)
3934 (match-end bibtex-key-in-head)))
3937 (unless called-by-reformat
3938 (let* ((end (save-excursion
3939 (bibtex-end-of-entry)
3940 (if (re-search-forward
3941 bibtex-entry-maybe-empty-head nil 'move)
3942 (goto-char (match-beginning 0)))
3944 (entry (buffer-substring start end))
3945 ;; include the crossref key in index
3946 (index (let ((bibtex-maintain-sorted-entries 'crossref))
3947 (bibtex-entry-index))) ; moves point to end of head
3950 (if (and bibtex-maintain-sorted-entries
3951 (not (and bibtex-sort-ignore-string-entries
3952 (eq entry-type 'string))))
3954 (delete-region start end)
3955 (setq error (not (bibtex-prepare-new-entry index))
3956 start (point)) ; update start
3957 (save-excursion (insert entry)))
3958 (bibtex-find-entry key)
3959 (setq error (or (/= (point) start)
3960 (bibtex-find-entry key nil end))))
3962 (error "New inserted entry yields duplicate key"))
3963 (dolist (buffer (bibtex-files-expand))
3964 (with-current-buffer buffer
3965 (if (cdr (assoc-string key bibtex-reference-keys))
3966 (error "Duplicate key in %s" (buffer-file-name)))))
3968 ;; Only update the list of keys if it has been built already.
3969 (cond ((eq entry-type 'string)
3970 (if (and (listp bibtex-strings)
3971 (not (assoc key bibtex-strings)))
3972 (push (cons key (bibtex-text-in-string
3973 (bibtex-parse-string) t))
3975 ;; We have a normal entry.
3976 ((listp bibtex-reference-keys)
3977 (cond ((not (assoc key bibtex-reference-keys))
3978 (push (cons key t) bibtex-reference-keys))
3979 ((not (cdr (assoc key bibtex-reference-keys)))
3980 ;; Turn a crossref key into a header key
3981 (setq bibtex-reference-keys
3983 (delete (list key) bibtex-reference-keys)))))
3984 ;; Handle crossref key.
3985 (if (and (nth 1 index)
3986 (not (assoc (nth 1 index) bibtex-reference-keys)))
3987 (push (list (nth 1 index)) bibtex-reference-keys)))))
3990 (if bibtex-clean-entry-hook
3993 (bibtex-narrow-to-entry)
3994 (run-hooks 'bibtex-clean-entry-hook)))))))
3996 (defun bibtex-fill-field-bounds (bounds justify &optional move)
3997 "Fill BibTeX field delimited by BOUNDS.
3998 If JUSTIFY is non-nil justify as well.
3999 If optional arg MOVE is non-nil move point to end of field."
4000 (let ((end-field (copy-marker (bibtex-end-of-field bounds))))
4002 (goto-char (bibtex-start-of-text-in-field bounds))
4003 (goto-char (bibtex-start-of-field bounds))
4004 (forward-char) ;; leading comma
4005 (bibtex-delete-whitespace)
4008 (indent-to-column (+ bibtex-entry-offset
4009 bibtex-field-indentation))
4010 (re-search-forward "[ \t\n]*=" end-field)
4013 (if bibtex-align-at-equal-sign
4015 (+ bibtex-entry-offset (- bibtex-text-indentation 2)))
4018 (bibtex-delete-whitespace)
4019 (if bibtex-align-at-equal-sign
4021 (indent-to-column bibtex-text-indentation)))
4022 ;; Paragraphs within fields are not preserved. Bother?
4023 (fill-region-as-paragraph (line-beginning-position) end-field
4024 default-justification nil (point))
4025 (if move (goto-char end-field))))
4027 (defun bibtex-fill-field (&optional justify)
4028 "Like \\[fill-paragraph], but fill current BibTeX field.
4029 If optional prefix JUSTIFY is non-nil justify as well.
4030 In BibTeX mode this function is bound to `fill-paragraph-function'."
4032 (let ((pnt (copy-marker (point)))
4033 (bounds (bibtex-enclosing-field t)))
4034 (bibtex-fill-field-bounds bounds justify)
4037 (defun bibtex-fill-entry ()
4038 "Fill current BibTeX entry.
4039 Realign entry, so that every field starts on a separate line. Field
4040 names appear in column `bibtex-field-indentation', field text starts in
4041 column `bibtex-text-indentation' and continuation lines start here, too.
4042 If `bibtex-align-at-equal-sign' is non-nil, align equal signs, too."
4044 (let ((pnt (copy-marker (point)))
4045 (end (copy-marker (bibtex-end-of-entry)))
4046 (beg (bibtex-beginning-of-entry)) ; move point
4048 (bibtex-delete-whitespace)
4049 (indent-to-column bibtex-entry-offset)
4050 (bibtex-beginning-first-field beg)
4051 (while (setq bounds (bibtex-parse-field))
4052 (bibtex-fill-field-bounds bounds t t))
4053 (if (looking-at ",")
4055 (skip-chars-backward " \t\n")
4056 (bibtex-delete-whitespace)
4059 (indent-to-column bibtex-entry-offset)
4062 (defun bibtex-realign ()
4063 "Realign BibTeX entries such that they are separated by one blank line."
4064 (goto-char (point-min))
4065 (let ((case-fold-search t)
4066 (entry-type (concat "[ \t\n]*\\(" bibtex-entry-type "\\)")))
4067 ;; No blank lines prior to the first entry if there no
4068 ;; non-white characters in front of it.
4069 (when (looking-at entry-type)
4070 (replace-match "\\1"))
4071 ;; Entries are separated by one blank line.
4072 (while (re-search-forward entry-type nil t)
4073 (replace-match "\n\n\\1"))
4074 ;; One blank line past the last entry if it is followed by
4075 ;; non-white characters, no blank line otherwise.
4077 (when (re-search-forward bibtex-entry-type nil t)
4078 (bibtex-end-of-entry)
4079 (bibtex-delete-whitespace)
4080 (open-line (if (eobp) 1 2)))))
4082 (defun bibtex-reformat (&optional read-options)
4083 "Reformat all BibTeX entries in buffer or region.
4084 Without prefix argument, reformatting is based on `bibtex-entry-format'.
4085 With prefix argument, read options for reformatting from minibuffer.
4086 With \\[universal-argument] \\[universal-argument] prefix argument, reuse previous answers (if any) again.
4087 If mark is active reformat entries in region, if not in whole buffer."
4089 (let* ((pnt (point))
4090 (use-previous-options
4091 (and (equal (prefix-numeric-value read-options) 16)
4092 (or bibtex-reformat-previous-options
4093 bibtex-reformat-previous-reference-keys)))
4094 (bibtex-entry-format
4096 (if use-previous-options
4097 bibtex-reformat-previous-options
4098 (setq bibtex-reformat-previous-options
4099 (mapcar (lambda (option)
4100 (if (y-or-n-p (car option)) (cdr option)))
4101 `(("Realign entries (recommended)? " . 'realign)
4102 ("Remove empty optional and alternative fields? " . 'opts-or-alts)
4103 ("Remove delimiters around pure numerical fields? " . 'numerical-fields)
4104 (,(concat (if bibtex-comma-after-last-field "Insert" "Remove")
4105 " comma at end of entry? ") . 'last-comma)
4106 ("Replace double page dashes by single ones? " . 'page-dashes)
4107 ("Inherit booktitle? " . 'inherit-booktitle)
4108 ("Force delimiters? " . 'delimiters)
4109 ("Unify case of entry types and field names? " . 'unify-case))))))
4110 ;; Do not include required-fields because `bibtex-reformat'
4111 ;; cannot handle the error messages of `bibtex-format-entry'.
4112 ;; Use `bibtex-validate' to check for required fields.
4113 ((eq t bibtex-entry-format)
4114 '(realign opts-or-alts numerical-fields delimiters
4115 last-comma page-dashes unify-case inherit-booktitle))
4117 (remove 'required-fields (push 'realign bibtex-entry-format)))))
4118 (reformat-reference-keys
4120 (if use-previous-options
4121 bibtex-reformat-previous-reference-keys
4122 (setq bibtex-reformat-previous-reference-keys
4123 (y-or-n-p "Generate new reference keys automatically? ")))))
4124 (bibtex-sort-ignore-string-entries t)
4125 bibtex-autokey-edit-before-use)
4128 (if mark-active (narrow-to-region (region-beginning) (region-end)))
4129 (if (memq 'realign bibtex-entry-format)
4131 (bibtex-progress-message "Formatting" 1)
4132 (bibtex-map-entries (lambda (key beg end)
4133 (bibtex-progress-message)
4134 (bibtex-clean-entry reformat-reference-keys t)))
4135 (bibtex-progress-message 'done))
4136 (when reformat-reference-keys
4137 (kill-local-variable 'bibtex-reference-keys)
4138 (when bibtex-maintain-sorted-entries
4139 (bibtex-progress-message "Sorting" 1)
4140 (bibtex-sort-buffer)
4141 (bibtex-progress-message 'done)))
4144 (defun bibtex-convert-alien (&optional read-options)
4145 "Make an alien BibTeX buffer fully usable by BibTeX mode.
4146 If a file does not conform with all standards used by BibTeX mode,
4147 some of the high-level features of BibTeX mode are not available.
4148 This function tries to convert current buffer to conform with these standards.
4149 With prefix argument READ-OPTIONS non-nil, read options for reformatting
4150 entries from minibuffer."
4152 (message "Starting to validate buffer...")
4155 (deactivate-mark) ; So bibtex-validate works on the whole buffer.
4156 (if (not (let (bibtex-maintain-sorted-entries)
4158 (message "Correct errors and call `bibtex-convert-alien' again")
4159 (message "Starting to reformat entries...")
4161 (bibtex-reformat read-options)
4162 (goto-char (point-max))
4163 (message "Buffer is now parsable. Please save it.")))
4165 (defun bibtex-complete ()
4166 "Complete word fragment before point according to context.
4167 If point is inside key or crossref field perform key completion based on
4168 `bibtex-reference-keys'. Inside a month field perform key completion
4169 based on `bibtex-predefined-month-strings'. Inside any other field
4170 \(including a String or Preamble definition) perform string completion
4171 based on `bibtex-strings'.
4172 An error is signaled if point is outside key or BibTeX field."
4175 (case-fold-search t)
4178 (if (and (setq bounds (bibtex-enclosing-field nil t))
4179 (>= pnt (bibtex-start-of-text-in-field bounds))
4180 (<= pnt (bibtex-end-of-text-in-field bounds)))
4181 (setq name (bibtex-name-in-field bounds t)
4182 compl (cond ((bibtex-string= name "crossref")
4183 ;; point is in crossref field
4185 ((bibtex-string= name "month")
4186 ;; point is in month field
4187 bibtex-predefined-month-strings)
4188 ;; point is in other field
4189 (t (bibtex-strings))))
4190 (bibtex-beginning-of-entry)
4191 (cond ((setq bounds (bibtex-parse-string t))
4192 ;; point is inside a @String key
4193 (cond ((and (>= pnt (nth 1 (car bounds)))
4194 (<= pnt (nth 2 (car bounds))))
4195 (setq compl 'string))
4196 ;; point is inside a @String field
4197 ((and (>= pnt (bibtex-start-of-text-in-string bounds))
4198 (<= pnt (bibtex-end-of-text-in-string bounds)))
4199 (setq compl (bibtex-strings)))))
4200 ;; point is inside a @Preamble field
4201 ((setq bounds (bibtex-parse-preamble))
4202 (if (and (>= pnt (bibtex-start-of-text-in-string bounds))
4203 (<= pnt (bibtex-end-of-text-in-string bounds)))
4204 (setq compl (bibtex-strings))))
4205 ((and (looking-at bibtex-entry-maybe-empty-head)
4206 ;; point is inside a key
4207 (or (and (match-beginning bibtex-key-in-head)
4208 (>= pnt (match-beginning bibtex-key-in-head))
4209 (<= pnt (match-end bibtex-key-in-head)))
4210 ;; or point is on empty key
4211 (and (not (match-beginning bibtex-key-in-head))
4212 (= pnt (match-end 0)))))
4213 (setq compl 'key)))))
4215 (cond ((eq compl 'key)
4216 ;; key completion: no cleanup needed
4217 (setq choose-completion-string-functions nil)
4218 (let (completion-ignore-case)
4219 (bibtex-complete-internal (bibtex-global-key-alist))))
4221 ((eq compl 'crossref-key)
4222 ;; crossref key completion
4224 ;; If we quit the *Completions* buffer without requesting
4225 ;; a completion, `choose-completion-string-functions' is still
4226 ;; non-nil. Therefore, `choose-completion-string-functions' is
4227 ;; always set (either to non-nil or nil) when a new completion
4229 (let (completion-ignore-case)
4230 (setq choose-completion-string-functions
4231 (lambda (choice buffer mini-p base-size)
4232 (setq choose-completion-string-functions nil)
4233 (choose-completion-string choice buffer base-size)
4234 (bibtex-complete-crossref-cleanup choice)
4235 t)) ; needed by choose-completion-string-functions
4236 (bibtex-complete-crossref-cleanup
4237 (bibtex-complete-internal (bibtex-global-key-alist)))))
4240 ;; string key completion: no cleanup needed
4241 (setq choose-completion-string-functions nil)
4242 (let ((completion-ignore-case t))
4243 (bibtex-complete-internal bibtex-strings)))
4246 ;; string completion
4247 (let ((completion-ignore-case t))
4248 (setq choose-completion-string-functions
4249 `(lambda (choice buffer mini-p base-size)
4250 (setq choose-completion-string-functions nil)
4251 (choose-completion-string choice buffer base-size)
4252 (bibtex-complete-string-cleanup choice ',compl)
4253 t)) ; needed by choose-completion-string-functions
4254 (bibtex-complete-string-cleanup (bibtex-complete-internal compl)
4257 (t (setq choose-completion-string-functions nil)
4258 (error "Point outside key or BibTeX field")))))
4260 (defun bibtex-Article ()
4261 "Insert a new BibTeX @Article entry; see also `bibtex-entry'."
4263 (bibtex-entry "Article"))
4265 (defun bibtex-Book ()
4266 "Insert a new BibTeX @Book entry; see also `bibtex-entry'."
4268 (bibtex-entry "Book"))
4270 (defun bibtex-Booklet ()
4271 "Insert a new BibTeX @Booklet entry; see also `bibtex-entry'."
4273 (bibtex-entry "Booklet"))
4275 (defun bibtex-InBook ()
4276 "Insert a new BibTeX @InBook entry; see also `bibtex-entry'."
4278 (bibtex-entry "InBook"))
4280 (defun bibtex-InCollection ()
4281 "Insert a new BibTeX @InCollection entry; see also `bibtex-entry'."
4283 (bibtex-entry "InCollection"))
4285 (defun bibtex-InProceedings ()
4286 "Insert a new BibTeX @InProceedings entry; see also `bibtex-entry'."
4288 (bibtex-entry "InProceedings"))
4290 (defun bibtex-Manual ()
4291 "Insert a new BibTeX @Manual entry; see also `bibtex-entry'."
4293 (bibtex-entry "Manual"))
4295 (defun bibtex-MastersThesis ()
4296 "Insert a new BibTeX @MastersThesis entry; see also `bibtex-entry'."
4298 (bibtex-entry "MastersThesis"))
4300 (defun bibtex-Misc ()
4301 "Insert a new BibTeX @Misc entry; see also `bibtex-entry'."
4303 (bibtex-entry "Misc"))
4305 (defun bibtex-PhdThesis ()
4306 "Insert a new BibTeX @PhdThesis entry; see also `bibtex-entry'."
4308 (bibtex-entry "PhdThesis"))
4310 (defun bibtex-Proceedings ()
4311 "Insert a new BibTeX @Proceedings entry; see also `bibtex-entry'."
4313 (bibtex-entry "Proceedings"))
4315 (defun bibtex-TechReport ()
4316 "Insert a new BibTeX @TechReport entry; see also `bibtex-entry'."
4318 (bibtex-entry "TechReport"))
4320 (defun bibtex-Unpublished ()
4321 "Insert a new BibTeX @Unpublished entry; see also `bibtex-entry'."
4323 (bibtex-entry "Unpublished"))
4325 (defun bibtex-String (&optional key)
4326 "Insert a new BibTeX @String entry with key KEY."
4327 (interactive (list (bibtex-read-string-key)))
4328 (let ((bibtex-maintain-sorted-entries
4329 (unless bibtex-sort-ignore-string-entries
4330 bibtex-maintain-sorted-entries))
4332 (unless (bibtex-prepare-new-entry (list key nil "String"))
4333 (error "Entry with key `%s' already exists" key))
4334 (if (zerop (length key)) (setq key nil))
4335 (indent-to-column bibtex-entry-offset)
4337 (bibtex-entry-left-delimiter))
4340 (setq endpos (point)))
4342 (bibtex-field-left-delimiter))
4344 (setq endpos (point)))
4345 (insert (bibtex-field-right-delimiter)
4346 (bibtex-entry-right-delimiter)
4348 (goto-char endpos)))
4350 (defun bibtex-Preamble ()
4351 "Insert a new BibTeX @Preamble entry."
4353 (bibtex-move-outside-of-entry)
4354 (indent-to-column bibtex-entry-offset)
4356 (bibtex-entry-left-delimiter)
4357 (bibtex-field-left-delimiter))
4358 (let ((endpos (point)))
4359 (insert (bibtex-field-right-delimiter)
4360 (bibtex-entry-right-delimiter)
4362 (goto-char endpos)))
4364 (defun bibtex-url (&optional pos no-browse)
4365 "Browse a URL for the BibTeX entry at point.
4366 Optional POS is the location of the BibTeX entry.
4367 The URL is generated using the schemes defined in `bibtex-generate-url-list'
4368 \(see there\). Then the URL is passed to `browse-url' unless NO-BROWSE is nil.
4369 Return the URL or nil if none can be generated."
4372 (if pos (goto-char pos))
4373 (bibtex-beginning-of-entry)
4374 ;; Always remove field delimiters
4375 (let ((fields-alist (bibtex-parse-entry t))
4376 ;; Always ignore case,
4377 (case-fold-search t)
4378 (lst bibtex-generate-url-list)
4379 field url scheme obj fmt)
4380 (while (setq scheme (pop lst))
4381 (when (and (setq field (cdr (assoc-string (caar scheme)
4383 (string-match (cdar scheme) field))
4386 url (if (null scheme) (match-string 0 field)
4387 (if (stringp (car scheme))
4388 (setq fmt (pop scheme)))
4389 (dolist (step scheme)
4390 (setq field (cdr (assoc-string (car step) fields-alist t)))
4391 (if (string-match (nth 1 step) field)
4392 (push (cond ((functionp (nth 2 step))
4393 (funcall (nth 2 step) field))
4394 ((numberp (nth 2 step))
4395 (match-string (nth 2 step) field))
4397 (replace-match (nth 2 step) t nil field)))
4399 ;; If the scheme is set up correctly,
4400 ;; we should never reach this point
4401 (error "Match failed: %s" field)))
4402 (if fmt (apply 'format fmt (nreverse obj))
4403 (apply 'concat (nreverse obj)))))
4404 (if (interactive-p) (message "%s" url))
4405 (unless no-browse (browse-url url))))
4406 (if (and (not url) (interactive-p)) (message "No URL known."))
4410 ;; Make BibTeX a Feature
4414 ;; arch-tag: ee2be3af-caad-427f-b42a-d20fad630d04
4415 ;;; bibtex.el ends here