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