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