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