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