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