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