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