Switch to recommended form of GPLv3 permissions notice.
[emacs.git] / lisp / textmodes / bibtex.el
blob362aea1e4e4e59e018f03daea70df9c9922b4acd
1 ;;; bibtex.el --- BibTeX mode for GNU Emacs
3 ;; Copyright (C) 1992, 1994, 1995, 1996, 1997, 1998, 1999, 2001, 2002,
4 ;; 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, 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 <roland.winkler@physik.uni-erlangen.de>
13 ;; Keywords: BibTeX, LaTeX, TeX
15 ;; This file is part of GNU Emacs.
17 ;; GNU Emacs is free software: you can redistribute it and/or modify
18 ;; it under the terms of the GNU General Public License as published by
19 ;; the Free Software Foundation, either version 3 of the License, or
20 ;; (at your option) any later version.
22 ;; GNU Emacs is distributed in the hope that it will be useful,
23 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 ;; GNU General Public License for more details.
27 ;; You should have received a copy of the GNU General Public License
28 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
30 ;;; Commentary:
32 ;; Major mode for editing and validating BibTeX files.
34 ;; Usage:
35 ;; See documentation for `bibtex-mode' or type "M-x describe-mode"
36 ;; when you are in BibTeX mode.
38 ;; Todo:
39 ;; Distribute texinfo file.
41 ;;; Code:
43 (require 'button)
46 ;; User Options:
48 (defgroup bibtex nil
49 "BibTeX mode."
50 :group 'tex
51 :prefix "bibtex-")
53 (defgroup bibtex-autokey nil
54 "Generate automatically a key from the author/editor and the title field."
55 :group 'bibtex
56 :prefix "bibtex-autokey-")
58 (defcustom bibtex-mode-hook nil
59 "List of functions to call on entry to BibTeX mode."
60 :group 'bibtex
61 :type 'hook)
63 (defcustom bibtex-field-delimiters 'braces
64 "Type of field delimiters. Allowed values are `braces' or `double-quotes'."
65 :group 'bibtex
66 :type '(choice (const braces)
67 (const double-quotes)))
69 (defcustom bibtex-entry-delimiters 'braces
70 "Type of entry delimiters. Allowed values are `braces' or `parentheses'."
71 :group 'bibtex
72 :type '(choice (const braces)
73 (const parentheses)))
75 (defcustom bibtex-include-OPTcrossref '("InProceedings" "InCollection")
76 "List of BibTeX entries that get an OPTcrossref field."
77 :group 'bibtex
78 :type '(repeat string))
80 (defcustom bibtex-include-OPTkey t
81 "If non-nil, all newly created entries get an OPTkey field.
82 If this is a string, use it as the initial field text.
83 If this is a function, call it to generate the initial field text."
84 :group 'bibtex
85 :type '(choice (const :tag "None" nil)
86 (string :tag "Initial text")
87 (function :tag "Initialize Function")
88 (const :tag "Default" t)))
89 (put 'bibtex-include-OPTkey 'risky-local-variable t)
91 (defcustom bibtex-user-optional-fields
92 '(("annote" "Personal annotation (ignored)"))
93 "List of optional fields the user wants to have always present.
94 Entries should be of the same form as the OPTIONAL and
95 CROSSREF-OPTIONAL lists in `bibtex-entry-field-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'.
131 The value t means do all of the above formatting actions.
132 The value nil means do no formatting at all."
133 :group 'bibtex
134 :type '(choice (const :tag "None" nil)
135 (const :tag "All" t)
136 (set :menu-tag "Some"
137 (const opts-or-alts)
138 (const required-fields)
139 (const numerical-fields)
140 (const page-dashes)
141 (const whitespace)
142 (const inherit-booktitle)
143 (const realign)
144 (const last-comma)
145 (const delimiters)
146 (const unify-case)
147 (const braces)
148 (const strings))))
150 (defcustom bibtex-field-braces-alist nil
151 "Alist of field regexps that \\[bibtex-clean-entry] encloses by braces.
152 Each element has the form (FIELDS REGEXP), where FIELDS is a list
153 of BibTeX field names and REGEXP is a regexp.
154 Whitespace in REGEXP will be replaced by \"[ \\t\\n]+\"."
155 :group 'bibtex
156 :type '(repeat (list (repeat (string :tag "field name"))
157 (choice (regexp :tag "regexp")
158 (sexp :tag "sexp")))))
160 (defcustom bibtex-field-strings-alist nil
161 "Alist of regexps that \\[bibtex-clean-entry] replaces by string constants.
162 Each element has the form (FIELDS REGEXP TO-STR), where FIELDS is a list
163 of BibTeX field names. In FIELDS search for REGEXP, which are replaced
164 by the BibTeX string constant TO-STR.
165 Whitespace in REGEXP will be replaced by \"[ \\t\\n]+\"."
166 :group 'bibtex
167 :type '(repeat (list (repeat (string :tag "field name"))
168 (regexp :tag "From regexp")
169 (regexp :tag "To string constant"))))
171 (defcustom bibtex-clean-entry-hook nil
172 "List of functions to call when entry has been cleaned.
173 Functions are called with point inside the cleaned entry, and the buffer
174 narrowed to just the entry."
175 :group 'bibtex
176 :type 'hook)
178 (defcustom bibtex-maintain-sorted-entries nil
179 "If non-nil, BibTeX mode maintains all entries in sorted order.
180 Allowed non-nil values are:
181 plain or t All entries are sorted alphabetically.
182 crossref All entries are sorted alphabetically unless an entry has a
183 crossref field. These crossrefed entries are placed in
184 alphabetical order immediately preceding the main entry.
185 entry-class The entries are divided into classes according to their
186 entry type, see `bibtex-sort-entry-class'. Within each class
187 the entries are sorted alphabetically.
188 See also `bibtex-sort-ignore-string-entries'."
189 :group 'bibtex
190 :type '(choice (const nil)
191 (const plain)
192 (const crossref)
193 (const entry-class)
194 (const t)))
195 (put 'bibtex-maintain-sorted-entries 'safe-local-variable
196 '(lambda (a) (memq a '(nil t plain crossref entry-class))))
198 (defcustom bibtex-sort-entry-class
199 '(("String")
200 (catch-all)
201 ("Book" "Proceedings"))
202 "List of classes of BibTeX entry types, used for sorting entries.
203 If value of `bibtex-maintain-sorted-entries' is `entry-class'
204 entries are ordered according to the classes they belong to. Each
205 class contains a list of entry types. An entry `catch-all' applies
206 to all entries not explicitly mentioned."
207 :group 'BibTeX
208 :type '(repeat (choice :tag "Class"
209 (const :tag "catch-all" (catch-all))
210 (repeat :tag "Entry type" string))))
211 (put 'bibtex-sort-entry-class 'safe-local-variable
212 (lambda (x) (let ((OK t))
213 (while (consp x)
214 (let ((y (pop x)))
215 (while (consp y)
216 (let ((z (pop y)))
217 (unless (or (stringp z) (eq z 'catch-all))
218 (setq OK nil))))
219 (unless (null y) (setq OK nil))))
220 (unless (null x) (setq OK nil))
221 OK)))
223 (defcustom bibtex-sort-ignore-string-entries t
224 "If non-nil, BibTeX @String entries are not sort-significant.
225 That means they are ignored when determining ordering of the buffer
226 \(e.g., sorting, locating alphabetical position for new entries, etc.)."
227 :group 'bibtex
228 :type 'boolean)
230 (defcustom bibtex-field-kill-ring-max 20
231 "Max length of `bibtex-field-kill-ring' before discarding oldest elements."
232 :group 'bibtex
233 :type 'integer)
235 (defcustom bibtex-entry-kill-ring-max 20
236 "Max length of `bibtex-entry-kill-ring' before discarding oldest elements."
237 :group 'bibtex
238 :type 'integer)
240 (defcustom bibtex-parse-keys-timeout 60
241 "Time interval in seconds for parsing BibTeX buffers during idle time.
242 Parsing initializes `bibtex-reference-keys' and `bibtex-strings'."
243 :group 'bibtex
244 :type 'integer)
246 (defcustom bibtex-parse-keys-fast t
247 "If non-nil, use fast but simplified algorithm for parsing BibTeX keys.
248 If parsing fails, try to set this variable to nil."
249 :group 'bibtex
250 :type 'boolean)
252 (defcustom bibtex-entry-field-alist
253 '(("Article"
254 ((("author" "Author1 [and Author2 ...] [and others]")
255 ("title" "Title of the article (BibTeX converts it to lowercase)")
256 ("journal" "Name of the journal (use string, remove braces)")
257 ("year" "Year of publication"))
258 (("volume" "Volume of the journal")
259 ("number" "Number of the journal (only allowed if entry contains volume)")
260 ("pages" "Pages in the journal")
261 ("month" "Month of the publication as a string (remove braces)")
262 ("note" "Remarks to be put at the end of the \\bibitem")))
263 ((("author" "Author1 [and Author2 ...] [and others]")
264 ("title" "Title of the article (BibTeX converts it to lowercase)"))
265 (("pages" "Pages in the journal")
266 ("journal" "Name of the journal (use string, remove braces)")
267 ("year" "Year of publication")
268 ("volume" "Volume of the journal")
269 ("number" "Number of the journal")
270 ("month" "Month of the publication as a string (remove braces)")
271 ("note" "Remarks to be put at the end of the \\bibitem"))))
272 ("Book"
273 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
274 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
275 ("title" "Title of the book")
276 ("publisher" "Publishing company")
277 ("year" "Year of publication"))
278 (("volume" "Volume of the book in the series")
279 ("number" "Number of the book in a small series (overwritten by volume)")
280 ("series" "Series in which the book appeared")
281 ("address" "Address of the publisher")
282 ("edition" "Edition of the book as a capitalized English word")
283 ("month" "Month of the publication as a string (remove braces)")
284 ("note" "Remarks to be put at the end of the \\bibitem")))
285 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
286 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
287 ("title" "Title of the book"))
288 (("publisher" "Publishing company")
289 ("year" "Year of publication")
290 ("volume" "Volume of the book in the series")
291 ("number" "Number of the book in a small series (overwritten by volume)")
292 ("series" "Series in which the book appeared")
293 ("address" "Address of the publisher")
294 ("edition" "Edition of the book as a capitalized English word")
295 ("month" "Month of the publication as a string (remove braces)")
296 ("note" "Remarks to be put at the end of the \\bibitem"))))
297 ("Booklet"
298 ((("title" "Title of the booklet (BibTeX converts it to lowercase)"))
299 (("author" "Author1 [and Author2 ...] [and others]")
300 ("howpublished" "The way in which the booklet was published")
301 ("address" "Address of the publisher")
302 ("month" "Month of the publication as a string (remove braces)")
303 ("year" "Year of publication")
304 ("note" "Remarks to be put at the end of the \\bibitem"))))
305 ("InBook"
306 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
307 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
308 ("title" "Title of the book")
309 ("chapter" "Chapter in the book")
310 ("publisher" "Publishing company")
311 ("year" "Year of publication"))
312 (("volume" "Volume of the book in the series")
313 ("number" "Number of the book in a small series (overwritten by volume)")
314 ("series" "Series in which the book appeared")
315 ("type" "Word to use instead of \"chapter\"")
316 ("address" "Address of the publisher")
317 ("edition" "Edition of the book as a capitalized English word")
318 ("month" "Month of the publication as a string (remove braces)")
319 ("pages" "Pages in the book")
320 ("note" "Remarks to be put at the end of the \\bibitem")))
321 ((("author" "Author1 [and Author2 ...] [and others]" nil t)
322 ("editor" "Editor1 [and Editor2 ...] [and others]" nil t)
323 ("title" "Title of the book")
324 ("chapter" "Chapter in the book"))
325 (("pages" "Pages in the book")
326 ("publisher" "Publishing company")
327 ("year" "Year of publication")
328 ("volume" "Volume of the book in the series")
329 ("number" "Number of the book in a small series (overwritten by volume)")
330 ("series" "Series in which the book appeared")
331 ("type" "Word to use instead of \"chapter\"")
332 ("address" "Address of the publisher")
333 ("edition" "Edition of the book as a capitalized English word")
334 ("month" "Month of the publication as a string (remove braces)")
335 ("note" "Remarks to be put at the end of the \\bibitem"))))
336 ("InCollection"
337 ((("author" "Author1 [and Author2 ...] [and others]")
338 ("title" "Title of the article in book (BibTeX converts it to lowercase)")
339 ("booktitle" "Name of the book")
340 ("publisher" "Publishing company")
341 ("year" "Year of publication"))
342 (("editor" "Editor1 [and Editor2 ...] [and others]")
343 ("volume" "Volume of the book in the series")
344 ("number" "Number of the book in a small series (overwritten by volume)")
345 ("series" "Series in which the book appeared")
346 ("type" "Word to use instead of \"chapter\"")
347 ("chapter" "Chapter in the book")
348 ("pages" "Pages in the book")
349 ("address" "Address of the publisher")
350 ("edition" "Edition of the book as a capitalized English word")
351 ("month" "Month of the publication as a string (remove braces)")
352 ("note" "Remarks to be put at the end of the \\bibitem")))
353 ((("author" "Author1 [and Author2 ...] [and others]")
354 ("title" "Title of the article in book (BibTeX converts it to lowercase)")
355 ("booktitle" "Name of the book"))
356 (("pages" "Pages in the book")
357 ("publisher" "Publishing company")
358 ("year" "Year of publication")
359 ("editor" "Editor1 [and Editor2 ...] [and others]")
360 ("volume" "Volume of the book in the series")
361 ("number" "Number of the book in a small series (overwritten by volume)")
362 ("series" "Series in which the book appeared")
363 ("type" "Word to use instead of \"chapter\"")
364 ("chapter" "Chapter in the book")
365 ("address" "Address of the publisher")
366 ("edition" "Edition of the book as a capitalized English word")
367 ("month" "Month of the publication as a string (remove braces)")
368 ("note" "Remarks to be put at the end of the \\bibitem"))))
369 ("InProceedings"
370 ((("author" "Author1 [and Author2 ...] [and others]")
371 ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)")
372 ("booktitle" "Name of the conference proceedings")
373 ("year" "Year of publication"))
374 (("editor" "Editor1 [and Editor2 ...] [and others]")
375 ("volume" "Volume of the conference proceedings in the series")
376 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
377 ("series" "Series in which the conference proceedings appeared")
378 ("pages" "Pages in the conference proceedings")
379 ("address" "Location of the Proceedings")
380 ("month" "Month of the publication as a string (remove braces)")
381 ("organization" "Sponsoring organization of the conference")
382 ("publisher" "Publishing company, its location")
383 ("note" "Remarks to be put at the end of the \\bibitem")))
384 ((("author" "Author1 [and Author2 ...] [and others]")
385 ("title" "Title of the article in proceedings (BibTeX converts it to lowercase)"))
386 (("booktitle" "Name of the conference proceedings")
387 ("pages" "Pages in the conference proceedings")
388 ("year" "Year of publication")
389 ("editor" "Editor1 [and Editor2 ...] [and others]")
390 ("volume" "Volume of the conference proceedings in the series")
391 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
392 ("series" "Series in which the conference proceedings appeared")
393 ("address" "Location of the Proceedings")
394 ("month" "Month of the publication as a string (remove braces)")
395 ("organization" "Sponsoring organization of the conference")
396 ("publisher" "Publishing company, its location")
397 ("note" "Remarks to be put at the end of the \\bibitem"))))
398 ("Manual"
399 ((("title" "Title of the manual"))
400 (("author" "Author1 [and Author2 ...] [and others]")
401 ("organization" "Publishing organization of the manual")
402 ("address" "Address of the organization")
403 ("edition" "Edition of the manual as a capitalized English word")
404 ("month" "Month of the publication as a string (remove braces)")
405 ("year" "Year of publication")
406 ("note" "Remarks to be put at the end of the \\bibitem"))))
407 ("MastersThesis"
408 ((("author" "Author1 [and Author2 ...] [and others]")
409 ("title" "Title of the master\'s thesis (BibTeX converts it to lowercase)")
410 ("school" "School where the master\'s thesis was written")
411 ("year" "Year of publication"))
412 (("type" "Type of the master\'s thesis (if other than \"Master\'s thesis\")")
413 ("address" "Address of the school (if not part of field \"school\") or country")
414 ("month" "Month of the publication as a string (remove braces)")
415 ("note" "Remarks to be put at the end of the \\bibitem"))))
416 ("Misc"
418 (("author" "Author1 [and Author2 ...] [and others]")
419 ("title" "Title of the work (BibTeX converts it to lowercase)")
420 ("howpublished" "The way in which the work was published")
421 ("month" "Month of the publication as a string (remove braces)")
422 ("year" "Year of publication")
423 ("note" "Remarks to be put at the end of the \\bibitem"))))
424 ("PhdThesis"
425 ((("author" "Author1 [and Author2 ...] [and others]")
426 ("title" "Title of the PhD. thesis")
427 ("school" "School where the PhD. thesis was written")
428 ("year" "Year of publication"))
429 (("type" "Type of the PhD. thesis")
430 ("address" "Address of the school (if not part of field \"school\") or country")
431 ("month" "Month of the publication as a string (remove braces)")
432 ("note" "Remarks to be put at the end of the \\bibitem"))))
433 ("Proceedings"
434 ((("title" "Title of the conference proceedings")
435 ("year" "Year of publication"))
436 (("booktitle" "Title of the proceedings for cross references")
437 ("editor" "Editor1 [and Editor2 ...] [and others]")
438 ("volume" "Volume of the conference proceedings in the series")
439 ("number" "Number of the conference proceedings in a small series (overwritten by volume)")
440 ("series" "Series in which the conference proceedings appeared")
441 ("address" "Location of the Proceedings")
442 ("month" "Month of the publication as a string (remove braces)")
443 ("organization" "Sponsoring organization of the conference")
444 ("publisher" "Publishing company, its location")
445 ("note" "Remarks to be put at the end of the \\bibitem"))))
446 ("TechReport"
447 ((("author" "Author1 [and Author2 ...] [and others]")
448 ("title" "Title of the technical report (BibTeX converts it to lowercase)")
449 ("institution" "Sponsoring institution of the report")
450 ("year" "Year of publication"))
451 (("type" "Type of the report (if other than \"technical report\")")
452 ("number" "Number of the technical report")
453 ("address" "Address of the institution (if not part of field \"institution\") or country")
454 ("month" "Month of the publication as a string (remove braces)")
455 ("note" "Remarks to be put at the end of the \\bibitem"))))
456 ("Unpublished"
457 ((("author" "Author1 [and Author2 ...] [and others]")
458 ("title" "Title of the unpublished work (BibTeX converts it to lowercase)")
459 ("note" "Remarks to be put at the end of the \\bibitem"))
460 (("month" "Month of the publication as a string (remove braces)")
461 ("year" "Year of publication")))))
463 "List of BibTeX entry types and their associated fields.
464 List elements are triples
465 \(ENTRY-TYPE (REQUIRED OPTIONAL) (CROSSREF-REQUIRED CROSSREF-OPTIONAL)).
466 ENTRY-TYPE is the type of a BibTeX entry. The remaining pairs contain
467 the required and optional fields of the BibTeX entry.
468 The second pair is used if a crossref field is present
469 and the first pair is used if a crossref field is absent.
470 If the second pair is nil, the first pair is always used.
471 REQUIRED, OPTIONAL, CROSSREF-REQUIRED and CROSSREF-OPTIONAL are lists.
472 Each element of these lists is a list of the form
473 \(FIELD-NAME COMMENT-STRING INIT ALTERNATIVE-FLAG).
474 COMMENT-STRING, INIT, and ALTERNATIVE-FLAG are optional.
475 FIELD-NAME is the name of the field, COMMENT-STRING is the comment that
476 appears in the echo area, INIT is either the initial content of the
477 field or a function, which is called to determine the initial content
478 of the field, and ALTERNATIVE-FLAG (either nil or t) marks if the
479 field is an alternative. ALTERNATIVE-FLAG may be t only in the
480 REQUIRED or CROSSREF-REQUIRED lists."
481 :group 'bibtex
482 :type '(repeat (group (string :tag "Entry type")
483 (group (repeat :tag "Required fields"
484 (group (string :tag "Field")
485 (string :tag "Comment")
486 (option (choice :tag "Init" :value nil
487 (const nil) string function))
488 (option (choice :tag "Alternative"
489 (const :tag "No" nil)
490 (const :tag "Yes" t)))))
491 (repeat :tag "Optional fields"
492 (group (string :tag "Field")
493 (string :tag "Comment")
494 (option (choice :tag "Init" :value nil
495 (const nil) string function)))))
496 (option :extra-offset -4
497 (group (repeat :tag "Crossref: required fields"
498 (group (string :tag "Field")
499 (string :tag "Comment")
500 (option (choice :tag "Init" :value nil
501 (const nil) string function))
502 (option (choice :tag "Alternative"
503 (const :tag "No" nil)
504 (const :tag "Yes" t)))))
505 (repeat :tag "Crossref: optional fields"
506 (group (string :tag "Field")
507 (string :tag "Comment")
508 (option (choice :tag "Init" :value nil
509 (const nil) string function)))))))))
510 (put 'bibtex-entry-field-alist 'risky-local-variable t)
512 (defcustom bibtex-comment-start "@Comment"
513 "String starting a BibTeX comment."
514 :group 'bibtex
515 :type 'string)
517 (defcustom bibtex-add-entry-hook nil
518 "List of functions to call when BibTeX entry has been inserted."
519 :group 'bibtex
520 :type 'hook)
522 (defcustom bibtex-predefined-month-strings
523 '(("jan" . "January")
524 ("feb" . "February")
525 ("mar" . "March")
526 ("apr" . "April")
527 ("may" . "May")
528 ("jun" . "June")
529 ("jul" . "July")
530 ("aug" . "August")
531 ("sep" . "September")
532 ("oct" . "October")
533 ("nov" . "November")
534 ("dec" . "December"))
535 "Alist of month string definitions used in the BibTeX style files.
536 Each element is a pair of strings (ABBREVIATION . EXPANSION)."
537 :group 'bibtex
538 :type '(repeat (cons (string :tag "Month abbreviation")
539 (string :tag "Month expansion"))))
541 (defcustom bibtex-predefined-strings
542 (append
543 bibtex-predefined-month-strings
544 '(("acmcs" . "ACM Computing Surveys")
545 ("acta" . "Acta Informatica")
546 ("cacm" . "Communications of the ACM")
547 ("ibmjrd" . "IBM Journal of Research and Development")
548 ("ibmsj" . "IBM Systems Journal")
549 ("ieeese" . "IEEE Transactions on Software Engineering")
550 ("ieeetc" . "IEEE Transactions on Computers")
551 ("ieeetcad" . "IEEE Transactions on Computer-Aided Design of Integrated Circuits")
552 ("ipl" . "Information Processing Letters")
553 ("jacm" . "Journal of the ACM")
554 ("jcss" . "Journal of Computer and System Sciences")
555 ("scp" . "Science of Computer Programming")
556 ("sicomp" . "SIAM Journal on Computing")
557 ("tcs" . "Theoretical Computer Science")
558 ("tocs" . "ACM Transactions on Computer Systems")
559 ("tods" . "ACM Transactions on Database Systems")
560 ("tog" . "ACM Transactions on Graphics")
561 ("toms" . "ACM Transactions on Mathematical Software")
562 ("toois" . "ACM Transactions on Office Information Systems")
563 ("toplas" . "ACM Transactions on Programming Languages and Systems")))
564 "Alist of string definitions used in the BibTeX style files.
565 Each element is a pair of strings (ABBREVIATION . EXPANSION)."
566 :group 'bibtex
567 :type '(repeat (cons (string :tag "String")
568 (string :tag "String expansion"))))
570 (defcustom bibtex-string-files nil
571 "List of BibTeX files containing string definitions.
572 List elements can be absolute file names or file names relative
573 to the directories specified in `bibtex-string-file-path'."
574 :group 'bibtex
575 :type '(repeat file))
577 (defvar bibtex-string-file-path (getenv "BIBINPUTS")
578 "*Colon separated list of paths to search for `bibtex-string-files'.")
580 (defcustom bibtex-files nil
581 "List of BibTeX files that are searched for entry keys.
582 List elements can be absolute file names or file names relative to the
583 directories specified in `bibtex-file-path'. If an element is a directory,
584 check all BibTeX files in this directory. If an element is the symbol
585 `bibtex-file-path', check all BibTeX files in `bibtex-file-path'."
586 :group 'bibtex
587 :type '(repeat (choice (const :tag "bibtex-file-path" bibtex-file-path)
588 directory file)))
590 (defvar bibtex-file-path (getenv "BIBINPUTS")
591 "*Colon separated list of paths to search for `bibtex-files'.")
593 (defcustom bibtex-help-message t
594 "If non-nil print help messages in the echo area on entering a new field."
595 :group 'bibtex
596 :type 'boolean)
598 (defcustom bibtex-autokey-prefix-string ""
599 "String prefix for automatically generated reference keys.
600 See `bibtex-generate-autokey' for details."
601 :group 'bibtex-autokey
602 :type 'string)
604 (defcustom bibtex-autokey-names 1
605 "Number of names to use for the automatically generated reference key.
606 Possibly more names are used according to `bibtex-autokey-names-stretch'.
607 If this variable is nil, all names are used.
608 See `bibtex-generate-autokey' for details."
609 :group 'bibtex-autokey
610 :type '(choice (const :tag "All" infty)
611 integer))
613 (defcustom bibtex-autokey-names-stretch 0
614 "Number of names that can additionally be used for reference keys.
615 These names are used only, if all names are used then.
616 See `bibtex-generate-autokey' for details."
617 :group 'bibtex-autokey
618 :type 'integer)
620 (defcustom bibtex-autokey-additional-names ""
621 "String to append to the generated key if not all names could be used.
622 See `bibtex-generate-autokey' for details."
623 :group 'bibtex-autokey
624 :type 'string)
626 (defcustom bibtex-autokey-expand-strings nil
627 "If non-nil, expand strings when extracting the content of a BibTeX field.
628 See `bibtex-generate-autokey' for details."
629 :group 'bibtex-autokey
630 :type 'boolean)
632 (defvar bibtex-autokey-transcriptions
633 '(;; language specific characters
634 ("\\\\aa" . "a") ; \aa -> a
635 ("\\\\AA" . "A") ; \AA -> A
636 ("\\\"a\\|\\\\\\\"a\\|\\\\ae" . "ae") ; "a,\"a,\ae -> ae
637 ("\\\"A\\|\\\\\\\"A\\|\\\\AE" . "Ae") ; "A,\"A,\AE -> Ae
638 ("\\\\i" . "i") ; \i -> i
639 ("\\\\j" . "j") ; \j -> j
640 ("\\\\l" . "l") ; \l -> l
641 ("\\\\L" . "L") ; \L -> L
642 ("\\\"o\\|\\\\\\\"o\\|\\\\o\\|\\\\oe" . "oe") ; "o,\"o,\o,\oe -> oe
643 ("\\\"O\\|\\\\\\\"O\\|\\\\O\\|\\\\OE" . "Oe") ; "O,\"O,\O,\OE -> Oe
644 ("\\\"s\\|\\\\\\\"s\\|\\\\3" . "ss") ; "s,\"s,\3 -> ss
645 ("\\\"u\\|\\\\\\\"u" . "ue") ; "u,\"u -> ue
646 ("\\\"U\\|\\\\\\\"U" . "Ue") ; "U,\"U -> Ue
647 ;; accents
648 ("\\\\`\\|\\\\'\\|\\\\\\^\\|\\\\~\\|\\\\=\\|\\\\\\.\\|\\\\u\\|\\\\v\\|\\\\H\\|\\\\t\\|\\\\c\\|\\\\d\\|\\\\b" . "")
649 ;; braces, quotes, concatenation.
650 ("[`'\"{}#]" . "")
651 ;; spaces
652 ("\\\\?[ \t\n]+\\|~" . " "))
653 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
654 Used by the default values of `bibtex-autokey-name-change-strings' and
655 `bibtex-autokey-titleword-change-strings'. Defaults to translating some
656 language specific characters to their ASCII transcriptions, and
657 removing any character accents.")
659 (defcustom bibtex-autokey-name-change-strings
660 bibtex-autokey-transcriptions
661 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
662 Any part of a name matching OLD-REGEXP is replaced by NEW-STRING.
663 Case is significant in OLD-REGEXP. All regexps are tried in the
664 order in which they appear in the list.
665 See `bibtex-generate-autokey' for details."
666 :group 'bibtex-autokey
667 :type '(repeat (cons (regexp :tag "Old")
668 (string :tag "New"))))
670 (defcustom bibtex-autokey-name-case-convert-function 'downcase
671 "Function called for each name to perform case conversion.
672 See `bibtex-generate-autokey' for details."
673 :group 'bibtex-autokey
674 :type '(choice (const :tag "Preserve case" identity)
675 (const :tag "Downcase" downcase)
676 (const :tag "Capitalize" capitalize)
677 (const :tag "Upcase" upcase)
678 (function :tag "Conversion function")))
679 (put 'bibtex-autokey-name-case-convert-function 'safe-local-variable
680 (lambda (x) (memq x '(upcase downcase capitalize identity))))
681 (defvaralias 'bibtex-autokey-name-case-convert
682 'bibtex-autokey-name-case-convert-function)
684 (defcustom bibtex-autokey-name-length 'infty
685 "Number of characters from name to incorporate into key.
686 If this is set to anything but a number, all characters are used.
687 See `bibtex-generate-autokey' for details."
688 :group 'bibtex-autokey
689 :type '(choice (const :tag "All" infty)
690 integer))
692 (defcustom bibtex-autokey-name-separator ""
693 "String that comes between any two names in the key.
694 See `bibtex-generate-autokey' for details."
695 :group 'bibtex-autokey
696 :type 'string)
698 (defcustom bibtex-autokey-year-length 2
699 "Number of rightmost digits from the year field to incorporate into key.
700 See `bibtex-generate-autokey' for details."
701 :group 'bibtex-autokey
702 :type 'integer)
704 (defcustom bibtex-autokey-use-crossref t
705 "If non-nil use fields from crossreferenced entry if necessary.
706 If this variable is non-nil and some field has no entry, but a
707 valid crossref entry, the field from the crossreferenced entry is used.
708 See `bibtex-generate-autokey' for details."
709 :group 'bibtex-autokey
710 :type 'boolean)
712 (defcustom bibtex-autokey-titlewords 5
713 "Number of title words to use for the automatically generated reference key.
714 If this is set to anything but a number, all title words are used.
715 Possibly more words from the title are used according to
716 `bibtex-autokey-titlewords-stretch'.
717 See `bibtex-generate-autokey' for details."
718 :group 'bibtex-autokey
719 :type '(choice (const :tag "All" infty)
720 integer))
722 (defcustom bibtex-autokey-title-terminators "[.!?:;]\\|--"
723 "Regexp defining the termination of the main part of the title.
724 Case of the regexps is ignored. See `bibtex-generate-autokey' for details."
725 :group 'bibtex-autokey
726 :type 'regexp)
728 (defcustom bibtex-autokey-titlewords-stretch 2
729 "Number of words that can additionally be used from the title.
730 These words are used only, if a sentence from the title can be ended then.
731 See `bibtex-generate-autokey' for details."
732 :group 'bibtex-autokey
733 :type 'integer)
735 (defcustom bibtex-autokey-titleword-ignore
736 '("A" "An" "On" "The" "Eine?" "Der" "Die" "Das"
737 "[^[:upper:]].*" ".*[^[:upper:]0-9].*")
738 "Determines words from the title that are not to be used in the key.
739 Each item of the list is a regexp. If a word of the title matches a
740 regexp from that list, it is not included in the title part of the key.
741 See `bibtex-generate-autokey' for details."
742 :group 'bibtex-autokey
743 :type '(repeat regexp))
745 (defcustom bibtex-autokey-titleword-case-convert-function 'downcase
746 "Function called for each titleword to perform case conversion.
747 See `bibtex-generate-autokey' for details."
748 :group 'bibtex-autokey
749 :type '(choice (const :tag "Preserve case" identity)
750 (const :tag "Downcase" downcase)
751 (const :tag "Capitalize" capitalize)
752 (const :tag "Upcase" upcase)
753 (function :tag "Conversion function")))
754 (defvaralias 'bibtex-autokey-titleword-case-convert
755 'bibtex-autokey-titleword-case-convert-function)
757 (defcustom bibtex-autokey-titleword-abbrevs nil
758 "Determines exceptions to the usual abbreviation mechanism.
759 An alist of (OLD-REGEXP . NEW-STRING) pairs. Case is ignored
760 in matching against OLD-REGEXP, and the first matching pair is used.
761 See `bibtex-generate-autokey' for details."
762 :group 'bibtex-autokey
763 :type '(repeat (cons (regexp :tag "Old")
764 (string :tag "New"))))
766 (defcustom bibtex-autokey-titleword-change-strings
767 bibtex-autokey-transcriptions
768 "Alist of (OLD-REGEXP . NEW-STRING) pairs.
769 Any part of title word matching a OLD-REGEXP is replaced by NEW-STRING.
770 Case is significant in OLD-REGEXP. All regexps are tried in the
771 order in which they appear in the list.
772 See `bibtex-generate-autokey' for details."
773 :group 'bibtex-autokey
774 :type '(repeat (cons (regexp :tag "Old")
775 (string :tag "New"))))
777 (defcustom bibtex-autokey-titleword-length 5
778 "Number of characters from title words to incorporate into key.
779 If this is set to anything but a number, all characters are used.
780 See `bibtex-generate-autokey' for details."
781 :group 'bibtex-autokey
782 :type '(choice (const :tag "All" infty)
783 integer))
785 (defcustom bibtex-autokey-titleword-separator "_"
786 "String to be put between the title words.
787 See `bibtex-generate-autokey' for details."
788 :group 'bibtex-autokey
789 :type 'string)
791 (defcustom bibtex-autokey-name-year-separator ""
792 "String to be put between name part and year part of key.
793 See `bibtex-generate-autokey' for details."
794 :group 'bibtex-autokey
795 :type 'string)
797 (defcustom bibtex-autokey-year-title-separator ":_"
798 "String to be put between name part and year part of key.
799 See `bibtex-generate-autokey' for details."
800 :group 'bibtex-autokey
801 :type 'string)
803 (defcustom bibtex-autokey-edit-before-use t
804 "If non-nil, user is allowed to edit the generated key before it is used."
805 :group 'bibtex-autokey
806 :type 'boolean)
808 (defcustom bibtex-autokey-before-presentation-function nil
809 "If non-nil, function to call before generated key is presented.
810 The function must take one argument (the automatically generated key),
811 and must return a string (the key to use)."
812 :group 'bibtex-autokey
813 :type '(choice (const nil) function))
815 (defcustom bibtex-entry-offset 0
816 "Offset for BibTeX entries.
817 Added to the value of all other variables which determine columns."
818 :group 'bibtex
819 :type 'integer)
821 (defcustom bibtex-field-indentation 2
822 "Starting column for the name part in BibTeX fields."
823 :group 'bibtex
824 :type 'integer)
826 (defcustom bibtex-text-indentation
827 (+ bibtex-field-indentation
828 (length "organization = "))
829 "Starting column for the text part in BibTeX fields.
830 Should be equal to the space needed for the longest name part."
831 :group 'bibtex
832 :type 'integer)
834 (defcustom bibtex-contline-indentation
835 (+ bibtex-text-indentation 1)
836 "Starting column for continuation lines of BibTeX fields."
837 :group 'bibtex
838 :type 'integer)
840 (defcustom bibtex-align-at-equal-sign nil
841 "If non-nil, align fields at equal sign instead of field text.
842 If non-nil, the column for the equal sign is the value of
843 `bibtex-text-indentation', minus 2."
844 :group 'bibtex
845 :type 'boolean)
847 (defcustom bibtex-comma-after-last-field nil
848 "If non-nil, a comma is put at end of last field in the entry template."
849 :group 'bibtex
850 :type 'boolean)
852 (defcustom bibtex-autoadd-commas t
853 "If non-nil automatically add missing commas at end of BibTeX fields."
854 :group 'bibtex
855 :type 'boolean)
857 (defcustom bibtex-autofill-types '("Proceedings")
858 "Automatically fill fields if possible for those BibTeX entry types."
859 :group 'bibtex
860 :type '(repeat string))
862 (defcustom bibtex-summary-function 'bibtex-summary
863 "Function to call for generating a summary of current BibTeX entry.
864 It takes no arguments. Point must be at beginning of entry.
865 Used by `bibtex-complete-crossref-cleanup' and `bibtex-copy-summary-as-kill'."
866 :group 'bibtex
867 :type '(choice (const :tag "Default" bibtex-summary)
868 (function :tag "Personalized function")))
870 (defcustom bibtex-generate-url-list
871 '((("url" . ".*:.*")))
872 "List of schemes for generating the URL of a BibTeX entry.
873 These schemes are used by `bibtex-url'.
875 Each scheme should have one of these forms:
877 ((FIELD . REGEXP))
878 ((FIELD . REGEXP) STEP...)
879 ((FIELD . REGEXP) STRING STEP...)
881 FIELD is a field name as returned by `bibtex-parse-entry'.
882 REGEXP is matched against the text of FIELD. If the match succeeds,
883 then this scheme is used. If no STRING and STEPs are specified
884 the matched text is used as the URL, otherwise the URL is built
885 by evaluating STEPs. If no STRING is specified the STEPs must result
886 in strings which are concatenated. Otherwise the resulting objects
887 are passed through `format' using STRING as format control string.
889 A STEP is a list (FIELD REGEXP REPLACE). The text of FIELD
890 is matched against REGEXP, and is replaced with REPLACE.
891 REPLACE can be a string, or a number (which selects the corresponding
892 submatch), or a function called with the field's text as argument
893 and with the `match-data' properly set.
895 Case is always ignored. Always remove the field delimiters.
896 If `bibtex-expand-strings' is non-nil, BibTeX strings are expanded
897 for generating the URL.
899 The following is a complex example, see http://link.aps.org/linkfaq.html.
901 (((\"journal\" . \"\\\\=<\\(PR[ABCDEL]?\\|RMP\\)\\\\=>\")
902 \"http://link.aps.org/abstract/%s/v%s/p%s\"
903 (\"journal\" \".*\" downcase)
904 (\"volume\" \".*\" 0)
905 (\"pages\" \"\\`[A-Z]?[0-9]+\" 0)))"
906 :group 'bibtex
907 :type '(repeat
908 (cons :tag "Scheme"
909 (cons :tag "Matcher" :extra-offset 4
910 (string :tag "BibTeX field")
911 (regexp :tag "Regexp"))
912 (choice
913 (const :tag "Take match as is" nil)
914 (cons :tag "Formatted"
915 (string :tag "Format control string")
916 (repeat :tag "Steps to generate URL"
917 (list (string :tag "BibTeX field")
918 (regexp :tag "Regexp")
919 (choice (string :tag "Replacement")
920 (integer :tag "Sub-match")
921 (function :tag "Filter")))))
922 (repeat :tag "Concatenated"
923 (list (string :tag "BibTeX field")
924 (regexp :tag "Regexp")
925 (choice (string :tag "Replacement")
926 (integer :tag "Sub-match")
927 (function :tag "Filter"))))))))
928 (put 'bibtex-generate-url-list 'risky-local-variable t)
930 (defcustom bibtex-cite-matcher-alist
931 '(("\\\\cite[ \t\n]*{\\([^}]+\\)}" . 1))
932 "Alist of rules to identify cited keys in a BibTeX entry.
933 Each rule should be of the form (REGEXP . SUBEXP), where SUBEXP
934 specifies which parenthesized expression in REGEXP is a cited key.
935 Case is significant.
936 Used by `bibtex-search-crossref' and for font-locking."
937 :group 'bibtex
938 :type '(repeat (cons (regexp :tag "Regexp")
939 (integer :tag "Number"))))
941 (defcustom bibtex-expand-strings nil
942 "If non-nil, expand strings when extracting the content of a BibTeX field."
943 :group 'bibtex
944 :type 'boolean)
946 ;; `bibtex-font-lock-keywords' is a user option, too. But since the
947 ;; patterns used to define this variable are defined in a later
948 ;; section of this file, it is defined later.
951 ;; Syntax Table and Keybindings
952 (defvar bibtex-mode-syntax-table
953 (let ((st (make-syntax-table)))
954 (modify-syntax-entry ?\" "\"" st)
955 (modify-syntax-entry ?$ "$$ " st)
956 (modify-syntax-entry ?% "< " st)
957 (modify-syntax-entry ?' "w " st)
958 (modify-syntax-entry ?@ "w " st)
959 (modify-syntax-entry ?\\ "\\" st)
960 (modify-syntax-entry ?\f "> " st)
961 (modify-syntax-entry ?\n "> " st)
962 ;; Keys cannot have = in them (wrong font-lock of @string{foo=bar}).
963 (modify-syntax-entry ?= "." st)
964 (modify-syntax-entry ?~ " " st)
966 "Syntax table used in BibTeX mode buffers.")
968 (defvar bibtex-mode-map
969 (let ((km (make-sparse-keymap)))
970 ;; The Key `C-c&' is reserved for reftex.el
971 (define-key km "\t" 'bibtex-find-text)
972 (define-key km "\n" 'bibtex-next-field)
973 (define-key km "\M-\t" 'bibtex-complete)
974 (define-key km "\C-c\"" 'bibtex-remove-delimiters)
975 (define-key km "\C-c{" 'bibtex-remove-delimiters)
976 (define-key km "\C-c}" 'bibtex-remove-delimiters)
977 (define-key km "\C-c\C-c" 'bibtex-clean-entry)
978 (define-key km "\C-c\C-q" 'bibtex-fill-entry)
979 (define-key km "\C-c\C-s" 'bibtex-search-entry)
980 (define-key km "\C-c\C-x" 'bibtex-search-crossref)
981 (define-key km "\C-c\C-t" 'bibtex-copy-summary-as-kill)
982 (define-key km "\C-c?" 'bibtex-print-help-message)
983 (define-key km "\C-c\C-p" 'bibtex-pop-previous)
984 (define-key km "\C-c\C-n" 'bibtex-pop-next)
985 (define-key km "\C-c\C-k" 'bibtex-kill-field)
986 (define-key km "\C-c\M-k" 'bibtex-copy-field-as-kill)
987 (define-key km "\C-c\C-w" 'bibtex-kill-entry)
988 (define-key km "\C-c\M-w" 'bibtex-copy-entry-as-kill)
989 (define-key km "\C-c\C-y" 'bibtex-yank)
990 (define-key km "\C-c\M-y" 'bibtex-yank-pop)
991 (define-key km "\C-c\C-d" 'bibtex-empty-field)
992 (define-key km "\C-c\C-f" 'bibtex-make-field)
993 (define-key km "\C-c\C-u" 'bibtex-entry-update)
994 (define-key km "\C-c$" 'bibtex-ispell-abstract)
995 (define-key km "\M-\C-a" 'bibtex-beginning-of-entry)
996 (define-key km "\M-\C-e" 'bibtex-end-of-entry)
997 (define-key km "\C-\M-l" 'bibtex-reposition-window)
998 (define-key km "\C-\M-h" 'bibtex-mark-entry)
999 (define-key km "\C-c\C-b" 'bibtex-entry)
1000 (define-key km "\C-c\C-rn" 'bibtex-narrow-to-entry)
1001 (define-key km "\C-c\C-rw" 'widen)
1002 (define-key km "\C-c\C-l" 'bibtex-url)
1003 (define-key km "\C-c\C-o" 'bibtex-remove-OPT-or-ALT)
1004 (define-key km "\C-c\C-e\C-i" 'bibtex-InProceedings)
1005 (define-key km "\C-c\C-ei" 'bibtex-InCollection)
1006 (define-key km "\C-c\C-eI" 'bibtex-InBook)
1007 (define-key km "\C-c\C-e\C-a" 'bibtex-Article)
1008 (define-key km "\C-c\C-e\C-b" 'bibtex-InBook)
1009 (define-key km "\C-c\C-eb" 'bibtex-Book)
1010 (define-key km "\C-c\C-eB" 'bibtex-Booklet)
1011 (define-key km "\C-c\C-e\C-c" 'bibtex-InCollection)
1012 (define-key km "\C-c\C-e\C-m" 'bibtex-Manual)
1013 (define-key km "\C-c\C-em" 'bibtex-MastersThesis)
1014 (define-key km "\C-c\C-eM" 'bibtex-Misc)
1015 (define-key km "\C-c\C-e\C-p" 'bibtex-InProceedings)
1016 (define-key km "\C-c\C-ep" 'bibtex-Proceedings)
1017 (define-key km "\C-c\C-eP" 'bibtex-PhdThesis)
1018 (define-key km "\C-c\C-e\M-p" 'bibtex-Preamble)
1019 (define-key km "\C-c\C-e\C-s" 'bibtex-String)
1020 (define-key km "\C-c\C-e\C-t" 'bibtex-TechReport)
1021 (define-key km "\C-c\C-e\C-u" 'bibtex-Unpublished)
1023 "Keymap used in BibTeX mode.")
1025 (easy-menu-define
1026 bibtex-edit-menu bibtex-mode-map "BibTeX-Edit Menu in BibTeX mode"
1027 '("BibTeX-Edit"
1028 ("Moving inside an Entry"
1029 ["End of Field" bibtex-find-text t]
1030 ["Next Field" bibtex-next-field t]
1031 ["Beginning of Entry" bibtex-beginning-of-entry t]
1032 ["End of Entry" bibtex-end-of-entry t]
1033 "--"
1034 ["Make Entry Visible" bibtex-reposition-window t])
1035 ("Moving in BibTeX Buffers"
1036 ["Search Entry" bibtex-search-entry t]
1037 ["Search Crossref Entry" bibtex-search-crossref t])
1038 "--"
1039 ("Operating on Current Field"
1040 ["Fill Field" fill-paragraph t]
1041 ["Remove Delimiters" bibtex-remove-delimiters t]
1042 ["Remove OPT or ALT Prefix" bibtex-remove-OPT-or-ALT t]
1043 ["Clear Field" bibtex-empty-field t]
1044 "--"
1045 ["Kill Field" bibtex-kill-field t]
1046 ["Copy Field to Kill Ring" bibtex-copy-field-as-kill t]
1047 ["Paste Most Recently Killed Field" bibtex-yank t]
1048 ["Paste Previously Killed Field" bibtex-yank-pop t]
1049 "--"
1050 ["Make New Field" bibtex-make-field t]
1051 "--"
1052 ["Snatch from Similar Following Field" bibtex-pop-next t]
1053 ["Snatch from Similar Preceding Field" bibtex-pop-previous t]
1054 "--"
1055 ["String or Key Complete" bibtex-complete t]
1056 "--"
1057 ["Help about Current Field" bibtex-print-help-message t])
1058 ("Operating on Current Entry"
1059 ["Fill Entry" bibtex-fill-entry t]
1060 ["Clean Entry" bibtex-clean-entry t]
1061 ["Update Entry" bibtex-entry-update t]
1062 "--"
1063 ["Kill Entry" bibtex-kill-entry t]
1064 ["Copy Entry to Kill Ring" bibtex-copy-entry-as-kill t]
1065 ["Paste Most Recently Killed Entry" bibtex-yank t]
1066 ["Paste Previously Killed Entry" bibtex-yank-pop t]
1067 "--"
1068 ["Copy Summary to Kill Ring" bibtex-copy-summary-as-kill t]
1069 ["Browse URL" bibtex-url t]
1070 "--"
1071 ["Ispell Entry" bibtex-ispell-entry t]
1072 ["Ispell Entry Abstract" bibtex-ispell-abstract t]
1073 "--"
1074 ["Narrow to Entry" bibtex-narrow-to-entry t]
1075 ["Mark Entry" bibtex-mark-entry t]
1076 "--"
1077 ["View Cite Locations (RefTeX)" reftex-view-crossref-from-bibtex
1078 (fboundp 'reftex-view-crossref-from-bibtex)])
1079 ("Operating on Buffer or Region"
1080 ["Validate Entries" bibtex-validate t]
1081 ["Sort Entries" bibtex-sort-buffer t]
1082 ["Reformat Entries" bibtex-reformat t]
1083 ["Count Entries" bibtex-count-entries t]
1084 "--"
1085 ["Convert Alien Buffer" bibtex-convert-alien t])
1086 ("Operating on Multiple Buffers"
1087 ["(Re)Initialize BibTeX Buffers" bibtex-initialize t]
1088 ["Validate Entries" bibtex-validate-globally t])))
1090 (easy-menu-define
1091 bibtex-entry-menu bibtex-mode-map "Entry-Types Menu in BibTeX mode"
1092 (list "Entry-Types"
1093 ["Article in Journal" bibtex-Article t]
1094 ["Article in Conference Proceedings" bibtex-InProceedings t]
1095 ["Article in a Collection" bibtex-InCollection t]
1096 ["Chapter or Pages in a Book" bibtex-InBook t]
1097 ["Conference Proceedings" bibtex-Proceedings t]
1098 ["Book" bibtex-Book t]
1099 ["Booklet (Bound, but no Publisher/Institution)" bibtex-Booklet t]
1100 ["PhD. Thesis" bibtex-PhdThesis t]
1101 ["Master's Thesis" bibtex-MastersThesis t]
1102 ["Technical Report" bibtex-TechReport t]
1103 ["Technical Manual" bibtex-Manual t]
1104 ["Unpublished" bibtex-Unpublished t]
1105 ["Miscellaneous" bibtex-Misc t]
1106 "--"
1107 ["String" bibtex-String t]
1108 ["Preamble" bibtex-Preamble t]))
1111 ;; Internal Variables
1113 (defvar bibtex-field-braces-opt nil
1114 "Optimized value of `bibtex-field-braces-alist'.
1115 Created by `bibtex-field-re-init'.
1116 It is a an alist with elements (FIELD . REGEXP).")
1118 (defvar bibtex-field-strings-opt nil
1119 "Optimized value of `bibtex-field-strings-alist'.
1120 Created by `bibtex-field-re-init'.
1121 It is a an alist with elements (FIELD RULE1 RULE2 ...),
1122 where each RULE is (REGEXP . TO-STR).")
1124 (defvar bibtex-pop-previous-search-point nil
1125 "Next point where `bibtex-pop-previous' starts looking for a similar entry.")
1127 (defvar bibtex-pop-next-search-point nil
1128 "Next point where `bibtex-pop-next' starts looking for a similar entry.")
1130 (defvar bibtex-field-kill-ring nil
1131 "Ring of least recently killed fields.
1132 At most `bibtex-field-kill-ring-max' items are kept here.")
1134 (defvar bibtex-field-kill-ring-yank-pointer nil
1135 "The tail of `bibtex-field-kill-ring' whose car is the last item yanked.")
1137 (defvar bibtex-entry-kill-ring nil
1138 "Ring of least recently killed entries.
1139 At most `bibtex-entry-kill-ring-max' items are kept here.")
1141 (defvar bibtex-entry-kill-ring-yank-pointer nil
1142 "The tail of `bibtex-entry-kill-ring' whose car is the last item yanked.")
1144 (defvar bibtex-last-kill-command nil
1145 "Type of the last kill command (either 'field or 'entry).")
1147 (defvar bibtex-strings
1148 (lazy-completion-table bibtex-strings
1149 (lambda ()
1150 (bibtex-parse-strings (bibtex-string-files-init))))
1151 "Completion table for BibTeX string keys.
1152 Initialized from `bibtex-predefined-strings' and `bibtex-string-files'.")
1153 (make-variable-buffer-local 'bibtex-strings)
1154 (put 'bibtex-strings 'risky-local-variable t)
1156 (defvar bibtex-reference-keys
1157 (lazy-completion-table bibtex-reference-keys
1158 (lambda () (bibtex-parse-keys nil t)))
1159 "Completion table for BibTeX reference keys.
1160 The CDRs of the elements are t for header keys and nil for crossref keys.")
1161 (make-variable-buffer-local 'bibtex-reference-keys)
1162 (put 'bibtex-reference-keys 'risky-local-variable t)
1164 (defvar bibtex-buffer-last-parsed-tick nil
1165 "Value of `buffer-modified-tick' last time buffer was parsed for keys.")
1167 (defvar bibtex-parse-idle-timer nil
1168 "Stores if timer is already installed.")
1170 (defvar bibtex-progress-lastperc nil
1171 "Last reported percentage for the progress message.")
1173 (defvar bibtex-progress-lastmes nil
1174 "Last reported progress message.")
1176 (defvar bibtex-progress-interval nil
1177 "Interval for progress messages.")
1179 (defvar bibtex-key-history nil
1180 "History list for reading keys.")
1182 (defvar bibtex-entry-type-history nil
1183 "History list for reading entry types.")
1185 (defvar bibtex-field-history nil
1186 "History list for reading field names.")
1188 (defvar bibtex-reformat-previous-options nil
1189 "Last reformat options given.")
1191 (defvar bibtex-reformat-previous-reference-keys nil
1192 "Last reformat reference keys option given.")
1194 (defconst bibtex-field-name "[^\"#%'(),={} \t\n0-9][^\"#%'(),={} \t\n]*"
1195 "Regexp matching the name of a BibTeX field.")
1197 (defconst bibtex-name-part
1198 (concat ",[ \t\n]*\\(" bibtex-field-name "\\)")
1199 "Regexp matching the name part of a BibTeX field.")
1201 (defconst bibtex-reference-key "[][[:alnum:].:;?!`'/*@+|()<>&_^$-]+"
1202 "Regexp matching the reference key part of a BibTeX entry.")
1204 (defconst bibtex-field-const "[][[:alnum:].:;?!`'/*@+=|<>&_^$-]+"
1205 "Regexp matching a BibTeX field constant.")
1207 (defvar bibtex-entry-type
1208 (concat "@[ \t]*\\(?:"
1209 (regexp-opt (mapcar 'car bibtex-entry-field-alist)) "\\)")
1210 "Regexp matching the type of a BibTeX entry.")
1212 (defvar bibtex-entry-head
1213 (concat "^[ \t]*\\("
1214 bibtex-entry-type
1215 "\\)[ \t]*[({][ \t\n]*\\("
1216 bibtex-reference-key
1217 "\\)")
1218 "Regexp matching the header line of a BibTeX entry (including key).")
1220 (defvar bibtex-entry-maybe-empty-head
1221 (concat bibtex-entry-head "?")
1222 "Regexp matching the header line of a BibTeX entry (possibly without key).")
1224 (defconst bibtex-any-entry-maybe-empty-head
1225 (concat "^[ \t]*\\(@[ \t]*" bibtex-field-name "\\)[ \t]*[({][ \t\n]*\\("
1226 bibtex-reference-key "\\)?")
1227 "Regexp matching the header line of any BibTeX entry (possibly without key).")
1229 (defvar bibtex-any-valid-entry-type
1230 (concat "^[ \t]*@[ \t]*\\(?:"
1231 (regexp-opt (append '("String" "Preamble")
1232 (mapcar 'car bibtex-entry-field-alist))) "\\)")
1233 "Regexp matching any valid BibTeX entry (including String and Preamble).")
1235 (defconst bibtex-type-in-head 1
1236 "Regexp subexpression number of the type part in `bibtex-entry-head'.")
1238 (defconst bibtex-key-in-head 2
1239 "Regexp subexpression number of the key part in `bibtex-entry-head'.")
1241 (defconst bibtex-string-type "^[ \t]*\\(@[ \t]*String\\)[ \t]*[({][ \t\n]*"
1242 "Regexp matching the name of a BibTeX String entry.")
1244 (defconst bibtex-string-maybe-empty-head
1245 (concat bibtex-string-type "\\(" bibtex-reference-key "\\)?")
1246 "Regexp matching the header line of a BibTeX String entry.")
1248 (defconst bibtex-preamble-prefix
1249 "[ \t]*\\(@[ \t]*Preamble\\)[ \t]*[({][ \t\n]*"
1250 "Regexp matching the prefix part of a BibTeX Preamble entry.")
1252 (defconst bibtex-font-lock-syntactic-keywords
1253 `((,(concat "^[ \t]*\\(" (substring bibtex-comment-start 0 1) "\\)"
1254 (substring bibtex-comment-start 1) "\\>")
1255 1 '(11))))
1257 (defvar bibtex-font-lock-keywords
1258 ;; entry type and reference key
1259 `((,bibtex-any-entry-maybe-empty-head
1260 (,bibtex-type-in-head font-lock-function-name-face)
1261 (,bibtex-key-in-head font-lock-constant-face nil t))
1262 ;; optional field names (treated as comments)
1263 (,(concat "^[ \t]*\\(OPT" bibtex-field-name "\\)[ \t]*=")
1264 1 font-lock-comment-face)
1265 ;; field names
1266 (,(concat "^[ \t]*\\(" bibtex-field-name "\\)[ \t]*=")
1267 1 font-lock-variable-name-face)
1268 ;; url
1269 (bibtex-font-lock-url) (bibtex-font-lock-crossref)
1270 ;; cite
1271 ,@(mapcar (lambda (matcher)
1272 `((lambda (bound) (bibtex-font-lock-cite ',matcher bound))))
1273 bibtex-cite-matcher-alist))
1274 "*Default expressions to highlight in BibTeX mode.")
1276 (defvar bibtex-font-lock-url-regexp
1277 ;; Assume that field names begin at the beginning of a line.
1278 (concat "^[ \t]*"
1279 (regexp-opt (delete-dups (mapcar 'caar bibtex-generate-url-list)) t)
1280 "[ \t]*=[ \t]*")
1281 "Regexp for `bibtex-font-lock-url' derived from `bibtex-generate-url-list'.")
1283 (defvar bibtex-string-empty-key nil
1284 "If non-nil, `bibtex-parse-string' accepts empty key.")
1286 (defvar bibtex-sort-entry-class-alist nil
1287 "Alist mapping entry types to their sorting index.
1288 Auto-generated from `bibtex-sort-entry-class'.
1289 Used when `bibtex-maintain-sorted-entries' is `entry-class'.")
1292 (defun bibtex-parse-association (parse-lhs parse-rhs)
1293 "Parse a string of the format <left-hand-side = right-hand-side>.
1294 The functions PARSE-LHS and PARSE-RHS are used to parse the corresponding
1295 substrings. These functions are expected to return nil if parsing is not
1296 successful. If the returned values of both functions are non-nil,
1297 return a cons pair of these values. Do not move point."
1298 (save-match-data
1299 (save-excursion
1300 (let ((left (funcall parse-lhs))
1301 right)
1302 (if (and left
1303 (looking-at "[ \t\n]*=[ \t\n]*")
1304 (goto-char (match-end 0))
1305 (setq right (funcall parse-rhs)))
1306 (cons left right))))))
1308 (defun bibtex-parse-field-name ()
1309 "Parse the name part of a BibTeX field.
1310 If the field name is found, return a triple consisting of the position of the
1311 very first character of the match, the actual starting position of the name
1312 part and end position of the match. Move point to end of field name.
1313 If `bibtex-autoadd-commas' is non-nil add missing comma at end of preceding
1314 BibTeX field as necessary."
1315 (cond ((looking-at bibtex-name-part)
1316 (goto-char (match-end 0))
1317 (list (match-beginning 0) (match-beginning 1) (match-end 0)))
1318 ;; Maybe add a missing comma.
1319 ((and bibtex-autoadd-commas
1320 (looking-at (concat "[ \t\n]*\\(?:" bibtex-field-name
1321 "\\)[ \t\n]*=")))
1322 (skip-chars-backward " \t\n")
1323 ;; It can be confusing if non-editing commands try to
1324 ;; modify the buffer.
1325 (if buffer-read-only
1326 (error "Comma missing at buffer position %s" (point)))
1327 (insert ",")
1328 (forward-char -1)
1329 ;; Now try again.
1330 (bibtex-parse-field-name))))
1332 (defconst bibtex-braced-string-syntax-table
1333 (let ((st (make-syntax-table)))
1334 (modify-syntax-entry ?\{ "(}" st)
1335 (modify-syntax-entry ?\} "){" st)
1336 (modify-syntax-entry ?\[ "." st)
1337 (modify-syntax-entry ?\] "." st)
1338 (modify-syntax-entry ?\( "." st)
1339 (modify-syntax-entry ?\) "." st)
1340 (modify-syntax-entry ?\\ "." st)
1341 (modify-syntax-entry ?\" "." st)
1343 "Syntax-table to parse matched braces.")
1345 (defconst bibtex-quoted-string-syntax-table
1346 (let ((st (make-syntax-table)))
1347 (modify-syntax-entry ?\\ "\\" st)
1348 (modify-syntax-entry ?\" "\"" st)
1350 "Syntax-table to parse matched quotes.")
1352 (defun bibtex-parse-field-string ()
1353 "Parse a BibTeX field string enclosed by braces or quotes.
1354 If a syntactically correct string is found, a pair containing the start and
1355 end position of the field string is returned, nil otherwise.
1356 Do not move point."
1357 (let ((end-point
1358 (or (and (eq (following-char) ?\")
1359 (save-excursion
1360 (with-syntax-table bibtex-quoted-string-syntax-table
1361 (forward-sexp 1))
1362 (point)))
1363 (and (eq (following-char) ?\{)
1364 (save-excursion
1365 (with-syntax-table bibtex-braced-string-syntax-table
1366 (forward-sexp 1))
1367 (point))))))
1368 (if end-point
1369 (cons (point) end-point))))
1371 (defun bibtex-parse-field-text ()
1372 "Parse the text part of a BibTeX field.
1373 The text part is either a string, or an empty string, or a constant followed
1374 by one or more <# (string|constant)> pairs. If a syntactically correct text
1375 is found, a pair containing the start and end position of the text is
1376 returned, nil otherwise. Move point to end of field text."
1377 (let ((starting-point (point))
1378 end-point failure boundaries)
1379 (while (not (or end-point failure))
1380 (cond ((looking-at bibtex-field-const)
1381 (goto-char (match-end 0)))
1382 ((setq boundaries (bibtex-parse-field-string))
1383 (goto-char (cdr boundaries)))
1384 ((setq failure t)))
1385 (if (looking-at "[ \t\n]*#[ \t\n]*")
1386 (goto-char (match-end 0))
1387 (setq end-point (point))))
1388 (skip-chars-forward " \t\n")
1389 (if (and (not failure)
1390 end-point)
1391 (list starting-point end-point (point)))))
1393 (defun bibtex-parse-field ()
1394 "Parse the BibTeX field beginning at the position of point.
1395 If a syntactically correct field is found, return a cons pair containing
1396 the boundaries of the name and text parts of the field. Do not move point."
1397 (bibtex-parse-association 'bibtex-parse-field-name
1398 'bibtex-parse-field-text))
1400 (defsubst bibtex-start-of-field (bounds)
1401 (nth 0 (car bounds)))
1402 (defsubst bibtex-start-of-name-in-field (bounds)
1403 (nth 1 (car bounds)))
1404 (defsubst bibtex-end-of-name-in-field (bounds)
1405 (nth 2 (car bounds)))
1406 (defsubst bibtex-start-of-text-in-field (bounds)
1407 (nth 1 bounds))
1408 (defsubst bibtex-end-of-text-in-field (bounds)
1409 (nth 2 bounds))
1410 (defsubst bibtex-end-of-field (bounds)
1411 (nth 3 bounds))
1413 (defun bibtex-search-forward-field (name &optional bound)
1414 "Search forward to find a BibTeX field of name NAME.
1415 If a syntactically correct field is found, return a pair containing
1416 the boundaries of the name and text parts of the field. The search
1417 is limited by optional arg BOUND. If BOUND is t the search is limited
1418 by the end of the current entry. Do not move point."
1419 (save-match-data
1420 (save-excursion
1421 (if (eq bound t)
1422 (let ((regexp (concat bibtex-name-part "[ \t\n]*=\\|"
1423 bibtex-any-entry-maybe-empty-head))
1424 (case-fold-search t) bounds)
1425 (catch 'done
1426 (if (looking-at "[ \t]*@") (goto-char (match-end 0)))
1427 (while (and (not bounds)
1428 (re-search-forward regexp nil t))
1429 (if (match-beginning 2)
1430 ;; We found a new entry
1431 (throw 'done nil)
1432 ;; We found a field
1433 (goto-char (match-beginning 0))
1434 (setq bounds (bibtex-parse-field))))
1435 ;; Step through all fields so that we cannot overshoot.
1436 (while bounds
1437 (goto-char (bibtex-start-of-name-in-field bounds))
1438 (if (looking-at name) (throw 'done bounds))
1439 (goto-char (bibtex-end-of-field bounds))
1440 (setq bounds (bibtex-parse-field)))))
1441 ;; Bounded search or bound is nil (i.e. we cannot overshoot).
1442 ;; Indeed, the search is bounded when `bibtex-search-forward-field'
1443 ;; is called many times. So we optimize this part of this function.
1444 (let ((name-part (concat ",[ \t\n]*\\(" name "\\)[ \t\n]*=[ \t\n]*"))
1445 (case-fold-search t) left right)
1446 (while (and (not right)
1447 (re-search-forward name-part bound t))
1448 (setq left (list (match-beginning 0) (match-beginning 1)
1449 (match-end 1))
1450 ;; Don't worry that the field text could be past bound.
1451 right (bibtex-parse-field-text)))
1452 (if right (cons left right)))))))
1454 (defun bibtex-search-backward-field (name &optional bound)
1455 "Search backward to find a BibTeX field of name NAME.
1456 If a syntactically correct field is found, return a pair containing
1457 the boundaries of the name and text parts of the field. The search
1458 is limited by the optional arg BOUND. If BOUND is t the search is
1459 limited by the beginning of the current entry. Do not move point."
1460 (save-match-data
1461 (if (eq bound t)
1462 (setq bound (save-excursion (bibtex-beginning-of-entry))))
1463 (let ((name-part (concat ",[ \t\n]*\\(" name "\\)[ \t\n]*=[ \t\n]*"))
1464 (case-fold-search t) left right)
1465 (save-excursion
1466 ;; the parsing functions are not designed for parsing backwards :-(
1467 (when (search-backward "," bound t)
1468 (or (save-excursion
1469 (when (looking-at name-part)
1470 (setq left (list (match-beginning 0) (match-beginning 1)
1471 (match-end 1)))
1472 (goto-char (match-end 0))
1473 (setq right (bibtex-parse-field-text))))
1474 (while (and (not right)
1475 (re-search-backward name-part bound t))
1476 (setq left (list (match-beginning 0) (match-beginning 1)
1477 (match-end 1)))
1478 (save-excursion
1479 (goto-char (match-end 0))
1480 (setq right (bibtex-parse-field-text)))))
1481 (if right (cons left right)))))))
1483 (defun bibtex-name-in-field (bounds &optional remove-opt-alt)
1484 "Get content of name in BibTeX field defined via BOUNDS.
1485 If optional arg REMOVE-OPT-ALT is non-nil remove \"OPT\" and \"ALT\"."
1486 (let ((name (buffer-substring-no-properties
1487 (bibtex-start-of-name-in-field bounds)
1488 (bibtex-end-of-name-in-field bounds))))
1489 (if (and remove-opt-alt
1490 (string-match "\\`\\(OPT\\|ALT\\)" name))
1491 (substring name 3)
1492 name)))
1494 (defun bibtex-text-in-field-bounds (bounds &optional content)
1495 "Get text in BibTeX field defined via BOUNDS.
1496 If optional arg CONTENT is non-nil extract content of field
1497 by removing field delimiters and concatenating the resulting string.
1498 If `bibtex-expand-strings' is non-nil, also expand BibTeX strings."
1499 (if content
1500 (save-excursion
1501 (goto-char (bibtex-start-of-text-in-field bounds))
1502 (let ((epoint (bibtex-end-of-text-in-field bounds))
1503 content opoint)
1504 (while (< (setq opoint (point)) epoint)
1505 (if (looking-at bibtex-field-const)
1506 (let ((mtch (match-string-no-properties 0)))
1507 (push (or (if bibtex-expand-strings
1508 (cdr (assoc-string mtch (bibtex-strings) t)))
1509 mtch) content)
1510 (goto-char (match-end 0)))
1511 (let ((bounds (bibtex-parse-field-string)))
1512 (push (buffer-substring-no-properties
1513 (1+ (car bounds)) (1- (cdr bounds))) content)
1514 (goto-char (cdr bounds))))
1515 (re-search-forward "\\=[ \t\n]*#[ \t\n]*" nil t))
1516 (apply 'concat (nreverse content))))
1517 (buffer-substring-no-properties (bibtex-start-of-text-in-field bounds)
1518 (bibtex-end-of-text-in-field bounds))))
1520 (defun bibtex-text-in-field (field &optional follow-crossref)
1521 "Get content of field FIELD of current BibTeX entry.
1522 Return nil if not found.
1523 If optional arg FOLLOW-CROSSREF is non-nil, follow crossref."
1524 (save-excursion
1525 (let* ((end (if follow-crossref (bibtex-end-of-entry) t))
1526 (beg (bibtex-beginning-of-entry)) ; move point
1527 (bounds (bibtex-search-forward-field field end)))
1528 (cond (bounds (bibtex-text-in-field-bounds bounds t))
1529 ((and follow-crossref
1530 (progn (goto-char beg)
1531 (setq bounds (bibtex-search-forward-field
1532 "\\(OPT\\)?crossref" end))))
1533 (let ((crossref-field (bibtex-text-in-field-bounds bounds t)))
1534 (if (bibtex-search-crossref crossref-field)
1535 ;; Do not pass FOLLOW-CROSSREF because we want
1536 ;; to follow crossrefs only one level of recursion.
1537 (bibtex-text-in-field field))))))))
1539 (defun bibtex-parse-string-prefix ()
1540 "Parse the prefix part of a BibTeX string entry, including reference key.
1541 If the string prefix is found, return a triple consisting of the position of
1542 the very first character of the match, the actual starting position of the
1543 reference key and the end position of the match.
1544 If `bibtex-string-empty-key' is non-nil accept empty string key."
1545 (let ((case-fold-search t))
1546 (if (looking-at bibtex-string-type)
1547 (let ((start (point)))
1548 (goto-char (match-end 0))
1549 (cond ((looking-at bibtex-reference-key)
1550 (goto-char (match-end 0))
1551 (list start
1552 (match-beginning 0)
1553 (match-end 0)))
1554 ((and bibtex-string-empty-key
1555 (looking-at "="))
1556 (skip-chars-backward " \t\n")
1557 (list start (point) (point))))))))
1559 (defun bibtex-parse-string-postfix ()
1560 "Parse the postfix part of a BibTeX string entry, including the text.
1561 If the string postfix is found, return a triple consisting of the position of
1562 the actual starting and ending position of the text and the very last
1563 character of the string entry. Move point past BibTeX string entry."
1564 (let* ((case-fold-search t)
1565 (bounds (bibtex-parse-field-text)))
1566 (when bounds
1567 (goto-char (nth 1 bounds))
1568 (when (looking-at "[ \t\n]*[})]")
1569 (goto-char (match-end 0))
1570 (list (car bounds)
1571 (nth 1 bounds)
1572 (match-end 0))))))
1574 (defun bibtex-parse-string (&optional empty-key)
1575 "Parse a BibTeX string entry beginning at the position of point.
1576 If a syntactically correct entry is found, return a cons pair containing
1577 the boundaries of the reference key and text parts of the entry.
1578 If EMPTY-KEY is non-nil, key may be empty. Do not move point."
1579 (let ((bibtex-string-empty-key empty-key))
1580 (bibtex-parse-association 'bibtex-parse-string-prefix
1581 'bibtex-parse-string-postfix)))
1583 (defun bibtex-search-forward-string (&optional empty-key)
1584 "Search forward to find a BibTeX string entry.
1585 If a syntactically correct entry is found, a pair containing the boundaries of
1586 the reference key and text parts of the string is returned.
1587 If EMPTY-KEY is non-nil, key may be empty. Do not move point."
1588 (save-excursion
1589 (save-match-data
1590 (let ((case-fold-search t) bounds)
1591 (while (and (not bounds)
1592 (search-forward-regexp bibtex-string-type nil t))
1593 (save-excursion (goto-char (match-beginning 0))
1594 (setq bounds (bibtex-parse-string empty-key))))
1595 bounds))))
1597 (defun bibtex-reference-key-in-string (bounds)
1598 "Return the key part of a BibTeX string defined via BOUNDS."
1599 (buffer-substring-no-properties (nth 1 (car bounds))
1600 (nth 2 (car bounds))))
1602 (defun bibtex-text-in-string (bounds &optional content)
1603 "Get text in BibTeX string field defined via BOUNDS.
1604 If optional arg CONTENT is non-nil extract content
1605 by removing field delimiters and concatenating the resulting string.
1606 If `bibtex-expand-strings' is non-nil, also expand BibTeX strings."
1607 (bibtex-text-in-field-bounds bounds content))
1609 (defsubst bibtex-start-of-text-in-string (bounds)
1610 (nth 0 (cdr bounds)))
1611 (defsubst bibtex-end-of-text-in-string (bounds)
1612 (nth 1 (cdr bounds)))
1613 (defsubst bibtex-end-of-string (bounds)
1614 (nth 2 (cdr bounds)))
1616 (defsubst bibtex-type-in-head ()
1617 "Extract BibTeX type in head."
1618 ;; ignore @
1619 (buffer-substring-no-properties (1+ (match-beginning bibtex-type-in-head))
1620 (match-end bibtex-type-in-head)))
1622 (defsubst bibtex-key-in-head (&optional empty)
1623 "Extract BibTeX key in head. Return optional arg EMPTY if key is empty."
1624 (or (match-string-no-properties bibtex-key-in-head)
1625 empty))
1627 (defun bibtex-parse-preamble ()
1628 "Parse BibTeX preamble.
1629 Point must be at beginning of preamble. Do not move point."
1630 (let ((case-fold-search t))
1631 (when (looking-at bibtex-preamble-prefix)
1632 (let ((start (match-beginning 0)) (pref-start (match-beginning 1))
1633 (bounds (save-excursion (goto-char (match-end 0))
1634 (bibtex-parse-string-postfix))))
1635 (if bounds (cons (list start pref-start) bounds))))))
1637 ;; Helper Functions
1639 (defsubst bibtex-string= (str1 str2)
1640 "Return t if STR1 and STR2 are equal, ignoring case."
1641 (eq t (compare-strings str1 0 nil str2 0 nil t)))
1643 (defun bibtex-delete-whitespace ()
1644 "Delete all whitespace starting at point."
1645 (if (looking-at "[ \t\n]+")
1646 (delete-region (point) (match-end 0))))
1648 (defun bibtex-current-line ()
1649 "Compute line number of point regardless whether the buffer is narrowed."
1650 (+ (count-lines 1 (point))
1651 (if (bolp) 1 0)))
1653 (defun bibtex-valid-entry (&optional empty-key)
1654 "Parse a valid BibTeX entry (maybe without key if EMPTY-KEY is t).
1655 A valid entry is a syntactical correct one with type contained in
1656 `bibtex-entry-field-alist'. Ignore @String and @Preamble entries.
1657 Return a cons pair with buffer positions of beginning and end of entry
1658 if a valid entry is found, nil otherwise. Do not move point.
1659 After a call to this function `match-data' corresponds to the header
1660 of the entry, see regexp `bibtex-entry-head'."
1661 (let ((case-fold-search t) end)
1662 (if (looking-at (if empty-key bibtex-entry-maybe-empty-head
1663 bibtex-entry-head))
1664 (save-excursion
1665 (save-match-data
1666 (goto-char (match-end 0))
1667 (let ((entry-closer
1668 (if (save-excursion
1669 (goto-char (match-end bibtex-type-in-head))
1670 (looking-at "[ \t]*("))
1671 ",?[ \t\n]*)" ; entry opened with `('
1672 ",?[ \t\n]*}")) ; entry opened with `{'
1673 bounds)
1674 (skip-chars-forward " \t\n")
1675 ;; loop over all BibTeX fields
1676 (while (setq bounds (bibtex-parse-field))
1677 (goto-char (bibtex-end-of-field bounds)))
1678 ;; This matches the infix* part.
1679 (if (looking-at entry-closer) (setq end (match-end 0)))))
1680 (if end (cons (match-beginning 0) end))))))
1682 (defun bibtex-skip-to-valid-entry (&optional backward)
1683 "Move point to beginning of the next valid BibTeX entry.
1684 Do not move if we are already at beginning of a valid BibTeX entry.
1685 With optional argument BACKWARD non-nil, move backward to
1686 beginning of previous valid one. A valid entry is a syntactical correct one
1687 with type contained in `bibtex-entry-field-alist' or, if
1688 `bibtex-sort-ignore-string-entries' is nil, a syntactical correct string
1689 entry. Return buffer position of beginning and end of entry if a valid
1690 entry is found, nil otherwise."
1691 (interactive "P")
1692 (let ((case-fold-search t)
1693 found bounds)
1694 (beginning-of-line)
1695 ;; Loop till we look at a valid entry.
1696 (while (not (or found (if backward (bobp) (eobp))))
1697 (cond ((setq found (or (bibtex-valid-entry)
1698 (and (not bibtex-sort-ignore-string-entries)
1699 (setq bounds (bibtex-parse-string))
1700 (cons (bibtex-start-of-field bounds)
1701 (bibtex-end-of-string bounds))))))
1702 (backward (re-search-backward "^[ \t]*@" nil 'move))
1703 (t (if (re-search-forward "\n\\([ \t]*@\\)" nil 'move)
1704 (goto-char (match-beginning 1))))))
1705 found))
1707 (defun bibtex-map-entries (fun)
1708 "Call FUN for each BibTeX entry in buffer (possibly narrowed).
1709 FUN is called with three arguments, the key of the entry and the buffer
1710 positions of beginning and end of entry. Also, point is at beginning of
1711 entry and `match-data' corresponds to the header of the entry,
1712 see regexp `bibtex-entry-head'. If `bibtex-sort-ignore-string-entries'
1713 is non-nil, FUN is not called for @String entries."
1714 (let ((case-fold-search t)
1715 found)
1716 (save-excursion
1717 (goto-char (point-min))
1718 (while (setq found (bibtex-skip-to-valid-entry))
1719 (looking-at bibtex-any-entry-maybe-empty-head)
1720 (funcall fun (bibtex-key-in-head "") (car found) (cdr found))
1721 (goto-char (cdr found))))))
1723 (defun bibtex-progress-message (&optional flag interval)
1724 "Echo a message about progress of current buffer.
1725 If FLAG is a string, the message is initialized (in this case a
1726 value for INTERVAL may be given as well (if not this is set to 5)).
1727 If FLAG is `done', the message is deinitialized.
1728 If FLAG is nil, a message is echoed if point was incremented at least
1729 `bibtex-progress-interval' percent since last message was echoed."
1730 (cond ((stringp flag)
1731 (setq bibtex-progress-lastmes flag
1732 bibtex-progress-interval (or interval 5)
1733 bibtex-progress-lastperc 0))
1734 ((eq flag 'done)
1735 (message "%s (done)" bibtex-progress-lastmes)
1736 (setq bibtex-progress-lastmes nil))
1738 (let* ((size (- (point-max) (point-min)))
1739 (perc (if (= size 0)
1741 (/ (* 100 (- (point) (point-min))) size))))
1742 (when (>= perc (+ bibtex-progress-lastperc
1743 bibtex-progress-interval))
1744 (setq bibtex-progress-lastperc perc)
1745 (message "%s (%d%%)" bibtex-progress-lastmes perc))))))
1747 (defun bibtex-field-left-delimiter ()
1748 "Return a string dependent on `bibtex-field-delimiters'."
1749 (if (eq bibtex-field-delimiters 'braces)
1751 "\""))
1753 (defun bibtex-field-right-delimiter ()
1754 "Return a string dependent on `bibtex-field-delimiters'."
1755 (if (eq bibtex-field-delimiters 'braces)
1757 "\""))
1759 (defun bibtex-entry-left-delimiter ()
1760 "Return a string dependent on `bibtex-entry-delimiters'."
1761 (if (eq bibtex-entry-delimiters 'braces)
1763 "("))
1765 (defun bibtex-entry-right-delimiter ()
1766 "Return a string dependent on `bibtex-entry-delimiters'."
1767 (if (eq bibtex-entry-delimiters 'braces)
1769 ")"))
1771 (defun bibtex-flash-head (prompt)
1772 "Flash at BibTeX entry head before point, if it exists."
1773 (let ((case-fold-search t)
1774 (pnt (point)))
1775 (save-excursion
1776 (bibtex-beginning-of-entry)
1777 (when (and (looking-at bibtex-any-entry-maybe-empty-head)
1778 (< (point) pnt))
1779 (goto-char (match-beginning bibtex-type-in-head))
1780 (if (and (< 0 blink-matching-delay)
1781 (pos-visible-in-window-p (point)))
1782 (sit-for blink-matching-delay)
1783 (message "%s%s" prompt (buffer-substring-no-properties
1784 (point) (match-end bibtex-key-in-head))))))))
1786 (defun bibtex-make-optional-field (field)
1787 "Make an optional field named FIELD in current BibTeX entry."
1788 (if (consp field)
1789 (bibtex-make-field (cons (concat "OPT" (car field)) (cdr field)))
1790 (bibtex-make-field (concat "OPT" field))))
1792 (defun bibtex-move-outside-of-entry ()
1793 "Make sure point is outside of a BibTeX entry."
1794 (let ((orig-point (point)))
1795 (bibtex-end-of-entry)
1796 (when (< (point) orig-point)
1797 ;; We moved backward, so we weren't inside an entry to begin with.
1798 ;; Leave point at the beginning of a line, and preferably
1799 ;; at the beginning of a paragraph.
1800 (goto-char orig-point)
1801 (beginning-of-line 1)
1802 (unless (= ?\n (char-before (1- (point))))
1803 (re-search-forward "^[ \t]*[@\n]" nil 'move)
1804 (backward-char 1)))
1805 (skip-chars-forward " \t\n")))
1807 (defun bibtex-beginning-of-first-entry ()
1808 "Go to beginning of line of first BibTeX entry in buffer.
1809 If `bibtex-sort-ignore-string-entries' is non-nil, @String entries
1810 are ignored. Return point"
1811 (goto-char (point-min))
1812 (bibtex-skip-to-valid-entry)
1813 (point))
1815 (defun bibtex-enclosing-field (&optional comma noerr)
1816 "Search for BibTeX field enclosing point.
1817 For `bibtex-mode''s internal algorithms, a field begins at the comma
1818 following the preceding field. Usually, this is not what the user expects.
1819 Thus if COMMA is non-nil, the \"current field\" includes the terminating comma.
1820 Unless NOERR is non-nil, signal an error if no enclosing field is found.
1821 On success return bounds, nil otherwise. Do not move point."
1822 (save-excursion
1823 (when comma
1824 (end-of-line)
1825 (skip-chars-backward " \t")
1826 (if (= (preceding-char) ?,) (forward-char -1)))
1828 (let ((bounds (bibtex-search-backward-field bibtex-field-name t)))
1829 (cond ((and bounds
1830 (<= (bibtex-start-of-field bounds) (point))
1831 (>= (bibtex-end-of-field bounds) (point)))
1832 bounds)
1833 ((not noerr)
1834 (error "Can't find enclosing BibTeX field"))))))
1836 (defun bibtex-beginning-first-field (&optional beg)
1837 "Move point to beginning of first field.
1838 Optional arg BEG is beginning of entry."
1839 (if beg (goto-char beg) (bibtex-beginning-of-entry))
1840 (looking-at bibtex-any-entry-maybe-empty-head)
1841 (goto-char (match-end 0)))
1843 (defun bibtex-insert-kill (n &optional comma)
1844 "Reinsert the Nth stretch of killed BibTeX text (field or entry).
1845 Optional arg COMMA is as in `bibtex-enclosing-field'."
1846 (unless bibtex-last-kill-command (error "BibTeX kill ring is empty"))
1847 (let ((fun (lambda (kryp kr) ; adapted from `current-kill'
1848 (car (set kryp (nthcdr (mod (- n (length (eval kryp)))
1849 (length kr)) kr))))))
1850 (if (eq bibtex-last-kill-command 'field)
1851 (progn
1852 ;; insert past the current field
1853 (goto-char (bibtex-end-of-field (bibtex-enclosing-field comma)))
1854 (push-mark)
1855 (bibtex-make-field (funcall fun 'bibtex-field-kill-ring-yank-pointer
1856 bibtex-field-kill-ring) t nil t))
1857 ;; insert past the current entry
1858 (bibtex-skip-to-valid-entry)
1859 (push-mark)
1860 (insert (funcall fun 'bibtex-entry-kill-ring-yank-pointer
1861 bibtex-entry-kill-ring)))))
1863 (defun bibtex-format-entry ()
1864 "Helper function for `bibtex-clean-entry'.
1865 Formats current entry according to variable `bibtex-entry-format'."
1866 ;; initialize `bibtex-field-braces-opt' if necessary
1867 (if (and bibtex-field-braces-alist (not bibtex-field-braces-opt))
1868 (setq bibtex-field-braces-opt
1869 (bibtex-field-re-init bibtex-field-braces-alist 'braces)))
1870 ;; initialize `bibtex-field-strings-opt' if necessary
1871 (if (and bibtex-field-strings-alist (not bibtex-field-strings-opt))
1872 (setq bibtex-field-strings-opt
1873 (bibtex-field-re-init bibtex-field-strings-alist 'strings)))
1875 (let ((case-fold-search t)
1876 (format (if (eq bibtex-entry-format t)
1877 '(realign opts-or-alts required-fields numerical-fields
1878 page-dashes whitespace inherit-booktitle
1879 last-comma delimiters unify-case braces
1880 strings)
1881 bibtex-entry-format))
1882 bounds crossref-key req-field-list default-field-list field-list
1883 alt-fields error-field-name)
1884 (unwind-protect
1885 ;; formatting (undone if error occurs)
1886 (atomic-change-group
1887 (save-excursion
1888 (save-restriction
1889 (bibtex-narrow-to-entry)
1891 ;; There are more elegant high-level functions for several tasks
1892 ;; done by `bibtex-format-entry'. However, they contain some
1893 ;; redundancy compared with what we need to do anyway.
1894 ;; So for speed-up we avoid using them.
1895 ;; (`bibtex-format-entry' is called often by `bibtex-reformat'.)
1897 ;; identify entry type
1898 (goto-char (point-min))
1899 (or (re-search-forward bibtex-entry-type nil t)
1900 (error "Not inside a BibTeX entry"))
1901 (let* ((beg-type (1+ (match-beginning 0)))
1902 (end-type (match-end 0))
1903 (entry-list (assoc-string (buffer-substring-no-properties
1904 beg-type end-type)
1905 bibtex-entry-field-alist t)))
1907 ;; unify case of entry type
1908 (when (memq 'unify-case format)
1909 (delete-region beg-type end-type)
1910 (insert (car entry-list)))
1912 ;; update left entry delimiter
1913 (when (memq 'delimiters format)
1914 (goto-char end-type)
1915 (skip-chars-forward " \t\n")
1916 (delete-char 1)
1917 (insert (bibtex-entry-left-delimiter)))
1919 ;; Do we have a crossref key?
1920 (goto-char (point-min))
1921 (if (setq bounds (bibtex-search-forward-field "crossref"))
1922 (let ((text (bibtex-text-in-field-bounds bounds t)))
1923 (unless (equal "" text)
1924 (setq crossref-key text))))
1926 ;; list of required fields appropriate for an entry with
1927 ;; or without crossref key.
1928 (setq req-field-list (if (and crossref-key (nth 2 entry-list))
1929 (car (nth 2 entry-list))
1930 (car (nth 1 entry-list)))
1931 ;; default list of fields that may appear in this entry
1932 default-field-list (append (nth 0 (nth 1 entry-list))
1933 (nth 1 (nth 1 entry-list))
1934 bibtex-user-optional-fields)))
1936 ;; process all fields
1937 (bibtex-beginning-first-field (point-min))
1938 (while (setq bounds (bibtex-parse-field))
1939 (let* ((beg-field (copy-marker (bibtex-start-of-field bounds)))
1940 (end-field (copy-marker (bibtex-end-of-field bounds) t))
1941 (beg-name (copy-marker (bibtex-start-of-name-in-field bounds)))
1942 (end-name (copy-marker (bibtex-end-of-name-in-field bounds)))
1943 (beg-text (copy-marker (bibtex-start-of-text-in-field bounds)))
1944 (end-text (copy-marker (bibtex-end-of-text-in-field bounds) t))
1945 (opt-alt (string-match "OPT\\|ALT"
1946 (buffer-substring-no-properties
1947 beg-name (+ beg-name 3))))
1948 (field-name (buffer-substring-no-properties
1949 (if opt-alt (+ beg-name 3) beg-name) end-name))
1950 (empty-field (equal "" (bibtex-text-in-field-bounds bounds t)))
1951 deleted)
1953 ;; keep track of alternatives
1954 (if (nth 3 (assoc-string field-name req-field-list t))
1955 (push field-name alt-fields))
1957 (if (memq 'opts-or-alts format)
1958 ;; delete empty optional and alternative fields
1959 ;; (but keep empty required fields)
1960 (cond ((and empty-field
1961 (or opt-alt
1962 (let ((field (assoc-string
1963 field-name req-field-list t)))
1964 (or (not field) ; OPT field
1965 (nth 3 field))))) ; ALT field
1966 (delete-region beg-field end-field)
1967 (setq deleted t))
1968 ;; otherwise nonempty field: delete "OPT" or "ALT"
1969 (opt-alt
1970 (goto-char beg-name)
1971 (delete-char 3))))
1973 (unless deleted
1974 (push field-name field-list)
1976 ;; remove delimiters from purely numerical fields
1977 (when (and (memq 'numerical-fields format)
1978 (progn (goto-char beg-text)
1979 (looking-at "\\(\"[0-9]+\"\\)\\|\\({[0-9]+}\\)")))
1980 (goto-char end-text)
1981 (delete-char -1)
1982 (goto-char beg-text)
1983 (delete-char 1))
1985 ;; update delimiters
1986 (when (memq 'delimiters format)
1987 (goto-char beg-text)
1988 (when (looking-at "[{\"]")
1989 (delete-char 1)
1990 (insert (bibtex-field-left-delimiter)))
1991 (goto-char (1- (marker-position end-text)))
1992 (when (looking-at "[}\"]")
1993 (delete-char 1)
1994 (insert (bibtex-field-right-delimiter))))
1996 ;; update page dashes
1997 (if (and (memq 'page-dashes format)
1998 (bibtex-string= field-name "pages")
1999 (progn (goto-char beg-text)
2000 (looking-at
2001 "\\([\"{][0-9]+\\)[ \t\n]*--?[ \t\n]*\\([0-9]+[\"}]\\)")))
2002 (replace-match "\\1-\\2"))
2004 ;; remove whitespace at beginning and end of field
2005 (when (memq 'whitespace format)
2006 (goto-char beg-text)
2007 (if (looking-at "\\([{\"]\\)[ \t\n]+")
2008 (replace-match "\\1"))
2009 (goto-char end-text)
2010 (if (looking-back "[ \t\n]+\\([}\"]\\)" beg-text t)
2011 (replace-match "\\1")))
2013 ;; enclose field text by braces according to
2014 ;; `bibtex-field-braces-alist'.
2015 (let (case-fold-search temp) ; Case-sensitive search
2016 (when (and (memq 'braces format)
2017 (setq temp (cdr (assoc-string field-name
2018 bibtex-field-braces-opt t))))
2019 (goto-char beg-text)
2020 (while (re-search-forward temp end-text t)
2021 (let ((beg (match-beginning 0))
2022 (bounds (bibtex-find-text-internal nil t)))
2023 (unless (or (nth 4 bounds) ; string constant
2024 ;; match already surrounded by braces
2025 ;; (braces are inside field delimiters)
2026 (and (< (point) (1- (nth 2 bounds)))
2027 (< (1+ (nth 1 bounds)) beg)
2028 (looking-at "}")
2029 (save-excursion (goto-char (1- beg))
2030 (looking-at "{"))))
2031 (insert "}")
2032 (goto-char beg)
2033 (insert "{")))))
2035 ;; replace field text by BibTeX string constants
2036 ;; according to `bibtex-field-strings-alist'.
2037 (when (and (memq 'strings format)
2038 (setq temp (cdr (assoc-string field-name
2039 bibtex-field-strings-opt t))))
2040 (goto-char beg-text)
2041 (dolist (re temp)
2042 (while (re-search-forward (car re) end-text t)
2043 (let ((bounds (save-match-data
2044 (bibtex-find-text-internal nil t))))
2045 (unless (nth 4 bounds)
2046 ;; if match not at right subfield boundary...
2047 (if (< (match-end 0) (1- (nth 2 bounds)))
2048 (insert " # " (bibtex-field-left-delimiter))
2049 (delete-char 1))
2050 (replace-match (cdr re))
2051 (goto-char (match-beginning 0))
2052 ;; if match not at left subfield boundary...
2053 (if (< (1+ (nth 1 bounds)) (match-beginning 0))
2054 (insert (bibtex-field-right-delimiter) " # ")
2055 (delete-backward-char 1))))))))
2057 ;; use book title of crossref'd entry
2058 (if (and (memq 'inherit-booktitle format)
2059 empty-field
2060 (bibtex-string= field-name "booktitle")
2061 crossref-key)
2062 (let ((title (save-excursion
2063 (save-restriction
2064 (widen)
2065 (if (bibtex-search-entry crossref-key t)
2066 (bibtex-text-in-field "title"))))))
2067 (when title
2068 (setq empty-field nil)
2069 (goto-char (1+ beg-text))
2070 (insert title))))
2072 ;; if empty field is a required field, complain
2073 (when (and empty-field
2074 (memq 'required-fields format)
2075 (assoc-string field-name req-field-list t))
2076 (setq error-field-name field-name)
2077 (error "Mandatory field `%s' is empty" field-name))
2079 ;; unify case of field name
2080 (if (memq 'unify-case format)
2081 (let ((fname (car (assoc-string field-name
2082 default-field-list t))))
2083 (if fname
2084 (progn
2085 (delete-region beg-name end-name)
2086 (goto-char beg-name)
2087 (insert fname))
2088 ;; there are no rules we could follow
2089 (downcase-region beg-name end-name))))
2091 ;; update point
2092 (goto-char end-field))))
2094 ;; check whether all required fields are present
2095 (if (memq 'required-fields format)
2096 (let ((found 0) alt-list)
2097 (dolist (fname req-field-list)
2098 (cond ((nth 3 fname) ; t if field has alternative flag
2099 (push (car fname) alt-list)
2100 (if (member-ignore-case (car fname) field-list)
2101 (setq found (1+ found))))
2102 ((not (member-ignore-case (car fname) field-list))
2103 ;; If we use the crossref field, a required field
2104 ;; can have the OPT prefix. So if it was empty,
2105 ;; we have deleted by now. Nonetheless we can
2106 ;; move point on this empty field.
2107 (setq error-field-name (car fname))
2108 (error "Mandatory field `%s' is missing" (car fname)))))
2109 (if alt-list
2110 (cond ((= found 0)
2111 (if alt-fields
2112 (setq error-field-name (car (last alt-fields))))
2113 (error "Alternative mandatory field `%s' is missing"
2114 alt-list))
2115 ((> found 1)
2116 (if alt-fields
2117 (setq error-field-name (car (last alt-fields))))
2118 (error "Alternative fields `%s' are defined %s times"
2119 alt-list found))))))
2121 ;; update comma after last field
2122 (if (memq 'last-comma format)
2123 (cond ((and bibtex-comma-after-last-field
2124 (not (looking-at ",")))
2125 (insert ","))
2126 ((and (not bibtex-comma-after-last-field)
2127 (looking-at ","))
2128 (delete-char 1))))
2130 ;; update right entry delimiter
2131 (if (looking-at ",")
2132 (forward-char))
2133 (when (memq 'delimiters format)
2134 (skip-chars-forward " \t\n")
2135 (delete-char 1)
2136 (insert (bibtex-entry-right-delimiter)))
2138 ;; realign and fill entry
2139 (if (memq 'realign format)
2140 (bibtex-fill-entry)))))
2142 ;; Unwindform: move point to location where error occured if possible
2143 (if error-field-name
2144 (let (bounds)
2145 (when (save-excursion
2146 (bibtex-beginning-of-entry)
2147 (setq bounds
2148 (bibtex-search-forward-field
2149 ;; If we use the crossref field, a required field
2150 ;; can have the OPT prefix
2151 (concat "\\(OPT\\|ALT\\)?" error-field-name) t)))
2152 (goto-char (bibtex-start-of-text-in-field bounds))
2153 (bibtex-find-text)))))))
2155 (defun bibtex-field-re-init (regexp-alist type)
2156 "Calculate optimized value for bibtex-regexp-TYPE-opt.
2157 This value is based on bibtex-regexp-TYPE-alist. TYPE is 'braces or 'strings.
2158 Return optimized value to be used by `bibtex-format-entry'."
2159 (setq regexp-alist
2160 (mapcar (lambda (e)
2161 (list (car e)
2162 (replace-regexp-in-string "[ \t\n]+" "[ \t\n]+" (nth 1 e))
2163 (nth 2 e))) ; nil for 'braces'.
2164 regexp-alist))
2165 (let (opt-list)
2166 ;; Loop over field names
2167 (dolist (field (delete-dups (apply 'append (mapcar 'car regexp-alist))))
2168 (let (rules)
2169 ;; Collect all matches we have for this field name
2170 (dolist (e regexp-alist)
2171 (if (assoc-string field (car e) t)
2172 (push (cons (nth 1 e) (nth 2 e)) rules)))
2173 (if (eq type 'braces)
2174 ;; concatenate all regexps to a single regexp
2175 (setq rules (concat "\\(?:" (mapconcat 'car rules "\\|") "\\)")))
2176 ;; create list of replacement rules.
2177 (push (cons field rules) opt-list)))
2178 opt-list))
2181 (defun bibtex-autokey-abbrev (string len)
2182 "Return an abbreviation of STRING with at least LEN characters.
2183 If LEN is positive the abbreviation is terminated only after a consonant
2184 or at the word end. If LEN is negative the abbreviation is strictly
2185 enforced using abs (LEN) characters. If LEN is not a number, STRING
2186 is returned unchanged."
2187 (cond ((or (not (numberp len))
2188 (<= (length string) (abs len)))
2189 string)
2190 ((equal len 0)
2192 ((< len 0)
2193 (substring string 0 (abs len)))
2194 (t (let* ((case-fold-search t)
2195 (abort-char (string-match "[^aeiou]" string (1- len))))
2196 (if abort-char
2197 (substring string 0 (1+ abort-char))
2198 string)))))
2200 (defun bibtex-autokey-get-field (field &optional change-list)
2201 "Get content of BibTeX field FIELD. Return empty string if not found.
2202 Optional arg CHANGE-LIST is a list of substitution patterns that is
2203 applied to the content of FIELD. It is an alist with pairs
2204 \(OLD-REGEXP . NEW-STRING\)."
2205 (let* ((bibtex-expand-strings bibtex-autokey-expand-strings)
2206 (content (bibtex-text-in-field field bibtex-autokey-use-crossref))
2207 case-fold-search)
2208 (unless content (setq content ""))
2209 (dolist (pattern change-list content)
2210 (setq content (replace-regexp-in-string (car pattern)
2211 (cdr pattern)
2212 content t)))))
2214 (defun bibtex-autokey-get-names ()
2215 "Get contents of the name field of the current entry.
2216 Do some modifications based on `bibtex-autokey-name-change-strings'.
2217 Return the names as a concatenated string obeying `bibtex-autokey-names'
2218 and `bibtex-autokey-names-stretch'."
2219 (let ((names (bibtex-autokey-get-field "author\\|editor"
2220 bibtex-autokey-name-change-strings)))
2221 ;; Some entries do not have a name field.
2222 (if (string= "" names)
2223 names
2224 (let* ((case-fold-search t)
2225 (name-list (mapcar 'bibtex-autokey-demangle-name
2226 (split-string names "[ \t\n]+and[ \t\n]+")))
2227 additional-names)
2228 (unless (or (not (numberp bibtex-autokey-names))
2229 (<= (length name-list)
2230 (+ bibtex-autokey-names
2231 bibtex-autokey-names-stretch)))
2232 ;; Take `bibtex-autokey-names' elements from beginning of name-list
2233 (setq name-list (nreverse (nthcdr (- (length name-list)
2234 bibtex-autokey-names)
2235 (nreverse name-list)))
2236 additional-names bibtex-autokey-additional-names))
2237 (concat (mapconcat 'identity name-list
2238 bibtex-autokey-name-separator)
2239 additional-names)))))
2241 (defun bibtex-autokey-demangle-name (fullname)
2242 "Get the last part from a well-formed FULLNAME and perform abbreviations."
2243 (let* (case-fold-search
2244 (name (cond ((string-match "\\([[:upper:]][^, ]*\\)[^,]*," fullname)
2245 ;; Name is of the form "von Last, First" or
2246 ;; "von Last, Jr, First"
2247 ;; --> Take the first capital part before the comma
2248 (match-string 1 fullname))
2249 ((string-match "\\([^, ]*\\)," fullname)
2250 ;; Strange name: we have a comma, but nothing capital
2251 ;; So we accept even lowercase names
2252 (match-string 1 fullname))
2253 ((string-match "\\(\\<[[:lower:]][^ ]* +\\)+\\([[:upper:]][^ ]*\\)"
2254 fullname)
2255 ;; name is of the form "First von Last", "von Last",
2256 ;; "First von von Last", or "d'Last"
2257 ;; --> take the first capital part after the "von" parts
2258 (match-string 2 fullname))
2259 ((string-match "\\([^ ]+\\) *\\'" fullname)
2260 ;; name is of the form "First Middle Last" or "Last"
2261 ;; --> take the last token
2262 (match-string 1 fullname))
2263 (t (error "Name `%s' is incorrectly formed" fullname)))))
2264 (funcall bibtex-autokey-name-case-convert-function
2265 (bibtex-autokey-abbrev name bibtex-autokey-name-length))))
2267 (defun bibtex-autokey-get-year ()
2268 "Return year field contents as a string obeying `bibtex-autokey-year-length'."
2269 (let ((yearfield (bibtex-autokey-get-field "year")))
2270 (substring yearfield (max 0 (- (length yearfield)
2271 bibtex-autokey-year-length)))))
2273 (defun bibtex-autokey-get-title ()
2274 "Get title field contents up to a terminator.
2275 Return the result as a string"
2276 (let ((case-fold-search t)
2277 (titlestring
2278 (bibtex-autokey-get-field "title"
2279 bibtex-autokey-titleword-change-strings)))
2280 ;; ignore everything past a terminator
2281 (if (string-match bibtex-autokey-title-terminators titlestring)
2282 (setq titlestring (substring titlestring 0 (match-beginning 0))))
2283 ;; gather words from titlestring into a list. Ignore
2284 ;; specific words and use only a specific amount of words.
2285 (let ((counter 0)
2286 titlewords titlewords-extra word)
2287 (while (and (or (not (numberp bibtex-autokey-titlewords))
2288 (< counter (+ bibtex-autokey-titlewords
2289 bibtex-autokey-titlewords-stretch)))
2290 (string-match "\\b\\w+" titlestring))
2291 (setq word (match-string 0 titlestring)
2292 titlestring (substring titlestring (match-end 0)))
2293 ;; Ignore words matched by one of the elements of
2294 ;; `bibtex-autokey-titleword-ignore'
2295 (unless (let ((lst bibtex-autokey-titleword-ignore))
2296 (while (and lst
2297 (not (string-match (concat "\\`\\(?:" (car lst)
2298 "\\)\\'") word)))
2299 (setq lst (cdr lst)))
2300 lst)
2301 (setq counter (1+ counter))
2302 (if (or (not (numberp bibtex-autokey-titlewords))
2303 (<= counter bibtex-autokey-titlewords))
2304 (push word titlewords)
2305 (push word titlewords-extra))))
2306 ;; Obey `bibtex-autokey-titlewords-stretch':
2307 ;; If by now we have processed all words in titlestring, we include
2308 ;; titlewords-extra in titlewords. Otherwise, we ignore titlewords-extra.
2309 (unless (string-match "\\b\\w+" titlestring)
2310 (setq titlewords (append titlewords-extra titlewords)))
2311 (mapconcat 'bibtex-autokey-demangle-title (nreverse titlewords)
2312 bibtex-autokey-titleword-separator))))
2314 (defun bibtex-autokey-demangle-title (titleword)
2315 "Do some abbreviations on TITLEWORD.
2316 The rules are defined in `bibtex-autokey-titleword-abbrevs'
2317 and `bibtex-autokey-titleword-length'."
2318 (let ((case-fold-search t)
2319 (alist bibtex-autokey-titleword-abbrevs))
2320 (while (and alist
2321 (not (string-match (concat "\\`\\(?:" (caar alist) "\\)\\'")
2322 titleword)))
2323 (setq alist (cdr alist)))
2324 (if alist
2325 (cdar alist)
2326 (funcall bibtex-autokey-titleword-case-convert-function
2327 (bibtex-autokey-abbrev titleword bibtex-autokey-titleword-length)))))
2329 (defun bibtex-generate-autokey ()
2330 "Generate automatically a key for a BibTeX entry.
2331 Use the author/editor, the year and the title field.
2332 The algorithm works as follows.
2334 The name part:
2335 1. Use the author or editor field to generate the name part of the key.
2336 Expand BibTeX strings if `bibtex-autokey-expand-strings' is non-nil.
2337 2. Change the content of the name field according to
2338 `bibtex-autokey-name-change-strings' (see there for further detail).
2339 3. Use the first `bibtex-autokey-names' names in the name field. If there
2340 are up to `bibtex-autokey-names' + `bibtex-autokey-names-stretch' names,
2341 use all names.
2342 4. Use only the last names to form the name part. From these last names,
2343 take at least `bibtex-autokey-name-length' characters (truncate only
2344 after a consonant or at a word end).
2345 5. Convert all last names using the function
2346 `bibtex-autokey-name-case-convert-function'.
2347 6. Build the name part of the key by concatenating all abbreviated last
2348 names with the string `bibtex-autokey-name-separator' between any two.
2349 If there are more names in the name field than names used in the name
2350 part, append the string `bibtex-autokey-additional-names'.
2352 The year part:
2353 1. Build the year part of the key by truncating the content of the year
2354 field to the rightmost `bibtex-autokey-year-length' digits (useful
2355 values are 2 and 4).
2356 2. If the year field (or any other field required to generate the key)
2357 is absent, but the entry has a valid crossref field and
2358 `bibtex-autokey-use-crossref' is non-nil, use the field of the
2359 crossreferenced entry instead.
2361 The title part
2362 1. Change the content of the title field according to
2363 `bibtex-autokey-titleword-change-strings' (see there for further detail).
2364 2. Truncate the title before the first match of
2365 `bibtex-autokey-title-terminators' and delete those words which appear
2366 in `bibtex-autokey-titleword-ignore'. Build the title part using the
2367 first `bibtex-autokey-titlewords' words from this truncated title.
2368 If the truncated title ends after up to `bibtex-autokey-titlewords' +
2369 `bibtex-autokey-titlewords-stretch' words, use all words from the
2370 truncated title.
2371 3. For every title word that appears in `bibtex-autokey-titleword-abbrevs'
2372 use the corresponding abbreviation (see documentation of this variable
2373 for further detail).
2374 4. From every title word not generated by an abbreviation, take at least
2375 `bibtex-autokey-titleword-length' characters (truncate only after
2376 a consonant or at a word end).
2377 5. Convert all title words using the function
2378 `bibtex-autokey-titleword-case-convert-function'.
2379 6. Build the title part by concatenating all abbreviated title words with
2380 the string `bibtex-autokey-titleword-separator' between any two.
2382 Concatenate the key:
2383 1. Concatenate `bibtex-autokey-prefix-string', the name part, the year
2384 part and the title part. If the name part and the year part are both
2385 non-empty insert `bibtex-autokey-name-year-separator' between the two.
2386 If the title part and the year (or name) part are non-empty, insert
2387 `bibtex-autokey-year-title-separator' between the two.
2388 2. If `bibtex-autokey-before-presentation-function' is non-nil, it must be
2389 a function taking one argument. Call this function with the generated
2390 key as the argument. Use the return value of this function (a string)
2391 as the key.
2392 3. If `bibtex-autokey-edit-before-use' is non-nil, present the key in the
2393 minibuffer to the user for editing. Insert the key given by the user."
2394 (let* ((names (bibtex-autokey-get-names))
2395 (year (bibtex-autokey-get-year))
2396 (title (bibtex-autokey-get-title))
2397 (autokey (concat bibtex-autokey-prefix-string
2398 names
2399 (unless (or (equal names "")
2400 (equal year ""))
2401 bibtex-autokey-name-year-separator)
2402 year
2403 (unless (or (and (equal names "")
2404 (equal year ""))
2405 (equal title ""))
2406 bibtex-autokey-year-title-separator)
2407 title)))
2408 (if bibtex-autokey-before-presentation-function
2409 (funcall bibtex-autokey-before-presentation-function autokey)
2410 autokey)))
2413 (defun bibtex-global-key-alist ()
2414 "Return global key alist based on `bibtex-files'."
2415 (if bibtex-files
2416 (apply 'append
2417 (mapcar (lambda (buf)
2418 (with-current-buffer buf bibtex-reference-keys))
2419 (bibtex-initialize t)))
2420 bibtex-reference-keys))
2422 (defun bibtex-read-key (prompt &optional key global)
2423 "Read BibTeX key from minibuffer using PROMPT and default KEY.
2424 If optional arg GLOBAL is non-nil, completion is based on the keys in
2425 `bibtex-reference-keys' of `bibtex-files',"
2426 (let (completion-ignore-case)
2427 (completing-read prompt (if global (bibtex-global-key-alist)
2428 bibtex-reference-keys)
2429 nil nil key 'bibtex-key-history)))
2431 (defun bibtex-read-string-key (&optional key)
2432 "Read BibTeX string key from minibuffer using default KEY."
2433 (let ((completion-ignore-case t))
2434 (completing-read "String key: " bibtex-strings
2435 nil nil key 'bibtex-key-history)))
2437 (defun bibtex-parse-keys (&optional abortable verbose)
2438 "Set `bibtex-reference-keys' to the keys used in the whole buffer.
2439 Find both entry keys and crossref entries. If ABORTABLE is non-nil abort
2440 on user input. If VERBOSE is non-nil give messages about progress.
2441 Return alist of keys if parsing was completed, `aborted' otherwise.
2442 If `bibtex-parse-keys-fast' is non-nil, use fast but simplified algorithm
2443 for parsing BibTeX keys. If parsing fails, try to set this variable to nil."
2444 (if (eq major-mode 'bibtex-mode)
2445 (let (ref-keys crossref-keys)
2446 (save-excursion
2447 (save-match-data
2448 (if verbose
2449 (bibtex-progress-message
2450 (concat (buffer-name) ": parsing reference keys")))
2451 (catch 'userkey
2452 (goto-char (point-min))
2453 (if bibtex-parse-keys-fast
2454 (let ((case-fold-search t)
2455 (re (concat bibtex-entry-head "\\|"
2456 ",[ \t\n]*crossref[ \t\n]*=[ \t\n]*"
2457 "\\(\"[^\"]*\"\\|{[^}]*}\\)[ \t\n]*[,})]")))
2458 (while (re-search-forward re nil t)
2459 (if (and abortable (input-pending-p))
2460 ;; user has aborted by typing a key: return `aborted'
2461 (throw 'userkey 'aborted))
2462 (cond ((match-end 3)
2463 ;; This is a crossref.
2464 (let ((key (buffer-substring-no-properties
2465 (1+ (match-beginning 3)) (1- (match-end 3)))))
2466 (unless (assoc key crossref-keys)
2467 (push (list key) crossref-keys))))
2468 ;; only keys of known entries
2469 ((assoc-string (bibtex-type-in-head)
2470 bibtex-entry-field-alist t)
2471 ;; This is an entry.
2472 (let ((key (bibtex-key-in-head)))
2473 (unless (assoc key ref-keys)
2474 (push (cons key t) ref-keys)))))))
2476 (let (;; ignore @String entries because they are handled
2477 ;; separately by `bibtex-parse-strings'
2478 (bibtex-sort-ignore-string-entries t)
2479 bounds)
2480 (bibtex-map-entries
2481 (lambda (key beg end)
2482 (if (and abortable
2483 (input-pending-p))
2484 ;; user has aborted by typing a key: return `aborted'
2485 (throw 'userkey 'aborted))
2486 (if verbose (bibtex-progress-message))
2487 (unless (assoc key ref-keys)
2488 (push (cons key t) ref-keys))
2489 (if (and (setq bounds (bibtex-search-forward-field "crossref" end))
2490 (setq key (bibtex-text-in-field-bounds bounds t))
2491 (not (assoc key crossref-keys)))
2492 (push (list key) crossref-keys))))))
2494 (dolist (key crossref-keys)
2495 (unless (assoc (car key) ref-keys) (push key ref-keys)))
2496 (if verbose
2497 (bibtex-progress-message 'done))
2498 ;; successful operation --> return `bibtex-reference-keys'
2499 (setq bibtex-reference-keys ref-keys)))))))
2501 (defun bibtex-parse-strings (&optional add abortable)
2502 "Set `bibtex-strings' to the string definitions in the whole buffer.
2503 If ADD is non-nil add the new strings to `bibtex-strings' instead of
2504 simply resetting it. If ADD is an alist of strings, also add ADD to
2505 `bibtex-strings'. If ABORTABLE is non-nil abort on user input.
2506 Return alist of strings if parsing was completed, `aborted' otherwise."
2507 (save-excursion
2508 (save-match-data
2509 (goto-char (point-min))
2510 (let ((strings (if (and add
2511 (listp bibtex-strings))
2512 bibtex-strings))
2513 bounds key)
2514 (if (listp add)
2515 (dolist (string add)
2516 (unless (assoc-string (car string) strings t)
2517 (push string strings))))
2518 (catch 'userkey
2519 (while (setq bounds (bibtex-search-forward-string))
2520 (if (and abortable
2521 (input-pending-p))
2522 ;; user has aborted by typing a key --> return `aborted'
2523 (throw 'userkey 'aborted))
2524 (setq key (bibtex-reference-key-in-string bounds))
2525 (unless (assoc-string key strings t)
2526 (push (cons key (bibtex-text-in-string bounds t))
2527 strings))
2528 (goto-char (bibtex-end-of-text-in-string bounds)))
2529 ;; successful operation --> return `bibtex-strings'
2530 (setq bibtex-strings strings))))))
2532 (defun bibtex-strings ()
2533 "Return `bibtex-strings'. Initialize this variable if necessary."
2534 (if (listp bibtex-strings) bibtex-strings
2535 (bibtex-parse-strings (bibtex-string-files-init))))
2537 (defun bibtex-string-files-init ()
2538 "Return initialization for `bibtex-strings'.
2539 Use `bibtex-predefined-strings' and BibTeX files `bibtex-string-files'."
2540 (save-match-data
2541 (let ((dirlist (split-string (or bibtex-string-file-path default-directory)
2542 ":+"))
2543 (case-fold-search)
2544 string-files fullfilename compl bounds found)
2545 ;; collect absolute file names of valid string files
2546 (dolist (filename bibtex-string-files)
2547 (unless (string-match "\\.bib\\'" filename)
2548 (setq filename (concat filename ".bib")))
2549 ;; test filenames
2550 (if (file-name-absolute-p filename)
2551 (if (file-readable-p filename)
2552 (push filename string-files)
2553 (error "BibTeX strings file %s not found" filename))
2554 (dolist (dir dirlist)
2555 (when (file-readable-p
2556 (setq fullfilename (expand-file-name filename dir)))
2557 (push fullfilename string-files)
2558 (setq found t)))
2559 (unless found
2560 (error "File %s not in paths defined via bibtex-string-file-path"
2561 filename))))
2562 ;; parse string files
2563 (dolist (filename string-files)
2564 (with-temp-buffer
2565 (insert-file-contents filename)
2566 (goto-char (point-min))
2567 (while (setq bounds (bibtex-search-forward-string))
2568 (push (cons (bibtex-reference-key-in-string bounds)
2569 (bibtex-text-in-string bounds t))
2570 compl)
2571 (goto-char (bibtex-end-of-string bounds)))))
2572 (append bibtex-predefined-strings (nreverse compl)))))
2574 (defun bibtex-parse-buffers-stealthily ()
2575 "Parse buffer in the background during idle time.
2576 Called by `run-with-idle-timer'. Whenever Emacs has been idle
2577 for `bibtex-parse-keys-timeout' seconds, parse all BibTeX buffers
2578 which have been modified after last parsing.
2579 Parsing initializes `bibtex-reference-keys' and `bibtex-strings'."
2580 (save-excursion
2581 (let ((buffers (buffer-list))
2582 (strings-init (bibtex-string-files-init)))
2583 (while (and buffers (not (input-pending-p)))
2584 (set-buffer (car buffers))
2585 (if (and (eq major-mode 'bibtex-mode)
2586 (not (eq (buffer-modified-tick)
2587 bibtex-buffer-last-parsed-tick)))
2588 (save-restriction
2589 (widen)
2590 ;; Output no progress messages in `bibtex-parse-keys'
2591 ;; because when in `y-or-n-p' that can hide the question.
2592 (if (and (listp (bibtex-parse-keys t))
2593 ;; update `bibtex-strings'
2594 (listp (bibtex-parse-strings strings-init t)))
2596 ;; remember that parsing was successful
2597 (setq bibtex-buffer-last-parsed-tick (buffer-modified-tick)))))
2598 (setq buffers (cdr buffers))))))
2600 ;;;###autoload
2601 (defun bibtex-initialize (&optional current force select)
2602 "(Re)Initialize BibTeX buffers.
2603 Visit the BibTeX files defined by `bibtex-files' and return a list
2604 of corresponding buffers.
2605 Initialize in these buffers `bibtex-reference-keys' if not yet set.
2606 List of BibTeX buffers includes current buffer if CURRENT is non-nil.
2607 If FORCE is non-nil, (re)initialize `bibtex-reference-keys' even if
2608 already set. If SELECT is non-nil interactively select a BibTeX buffer.
2609 When called interactively, FORCE is t, CURRENT is t if current buffer uses
2610 `bibtex-mode', and SELECT is t if current buffer does not use `bibtex-mode',"
2611 (interactive (list (eq major-mode 'bibtex-mode) t
2612 (not (eq major-mode 'bibtex-mode))))
2613 (let ((file-path (split-string (or bibtex-file-path default-directory) ":+"))
2614 file-list dir-list buffer-list)
2615 ;; generate list of BibTeX files
2616 (dolist (file bibtex-files)
2617 (cond ((eq file 'bibtex-file-path)
2618 (setq dir-list (append dir-list file-path)))
2619 ((file-accessible-directory-p file)
2620 (push file dir-list))
2621 ((progn (unless (string-match "\\.bib\\'" file)
2622 (setq file (concat file ".bib")))
2623 (file-name-absolute-p file))
2624 (push file file-list))
2626 (let (expanded-file-name found)
2627 (dolist (dir file-path)
2628 (when (file-readable-p
2629 (setq expanded-file-name (expand-file-name file dir)))
2630 (push expanded-file-name file-list)
2631 (setq found t)))
2632 (unless found
2633 (error "File `%s' not in paths defined via bibtex-file-path"
2634 file))))))
2635 (dolist (file file-list)
2636 (unless (file-readable-p file)
2637 (error "BibTeX file `%s' not found" file)))
2638 ;; expand dir-list
2639 (dolist (dir dir-list)
2640 (setq file-list
2641 (append file-list (directory-files dir t "\\.bib\\'" t))))
2642 (delete-dups file-list)
2643 ;; visit files in FILE-LIST
2644 (dolist (file file-list)
2645 (if (file-readable-p file)
2646 (push (find-file-noselect file) buffer-list)))
2647 ;; include current buffer iff we want it
2648 (cond ((and current (not (memq (current-buffer) buffer-list)))
2649 (push (current-buffer) buffer-list))
2650 ((and (not current) (memq (current-buffer) buffer-list))
2651 (setq buffer-list (delq (current-buffer) buffer-list))))
2652 ;; parse keys
2653 (dolist (buffer buffer-list)
2654 (with-current-buffer buffer
2655 (if (or force (nlistp bibtex-reference-keys))
2656 (bibtex-parse-keys))))
2657 ;; select BibTeX buffer
2658 (if select
2659 (if buffer-list
2660 (switch-to-buffer
2661 (completing-read "Switch to BibTeX buffer: "
2662 (mapcar 'buffer-name buffer-list)
2663 nil t
2664 (if current (buffer-name (current-buffer)))))
2665 (message "No BibTeX buffers defined")))
2666 buffer-list))
2668 (defun bibtex-complete-internal (completions)
2669 "Complete word fragment before point to longest prefix of COMPLETIONS.
2670 COMPLETIONS is an alist of strings. If point is not after the part
2671 of a word, all strings are listed. Return completion."
2672 ;; Return value is used by cleanup functions.
2673 ;; Code inspired by `lisp-complete-symbol'.
2674 (let* ((case-fold-search t)
2675 (beg (save-excursion
2676 (re-search-backward "[ \t{\"]")
2677 (forward-char)
2678 (point)))
2679 (end (point))
2680 (pattern (buffer-substring-no-properties beg end))
2681 (completion (try-completion pattern completions)))
2682 (cond ((not completion)
2683 (error "Can't find completion for `%s'" pattern))
2684 ((eq completion t)
2685 pattern)
2686 ((not (string= pattern completion))
2687 (delete-region beg end)
2688 (insert completion)
2689 ;; Don't leave around a completions buffer that's out of date.
2690 (let ((win (get-buffer-window "*Completions*" 0)))
2691 (if win (with-selected-window win (bury-buffer))))
2692 completion)
2694 (let ((minibuf-is-in-use
2695 (eq (minibuffer-window) (selected-window))))
2696 (unless minibuf-is-in-use (message "Making completion list..."))
2697 (with-output-to-temp-buffer "*Completions*"
2698 (display-completion-list
2699 (sort (all-completions pattern completions) 'string<) pattern))
2700 (unless minibuf-is-in-use
2701 (message "Making completion list...done")))
2702 nil))))
2704 (defun bibtex-complete-string-cleanup (str compl)
2705 "Cleanup after inserting string STR.
2706 Remove enclosing field delimiters for STR. Display message with
2707 expansion of STR using expansion list COMPL."
2708 ;; point is at position inside field where completion was requested
2709 (save-excursion
2710 (let ((abbr (cdr (if (stringp str)
2711 (assoc-string str compl t)))))
2712 (if abbr (message "Abbreviation for `%s'" abbr))
2713 (bibtex-remove-delimiters))))
2715 (defun bibtex-complete-crossref-cleanup (key)
2716 "Display summary message on entry KEY after completion of a crossref key.
2717 Use `bibtex-summary-function' to generate summary."
2718 (save-excursion
2719 (if (and (stringp key)
2720 (bibtex-search-entry key t))
2721 (message "Ref: %s" (funcall bibtex-summary-function)))))
2723 (defun bibtex-copy-summary-as-kill (&optional arg)
2724 "Push summery of current BibTeX entry to kill ring.
2725 Use `bibtex-summary-function' to generate summary.
2726 If prefix ARG is non-nil push BibTeX entry's URL to kill ring
2727 that is generated by calling `bibtex-url'."
2728 (interactive "P")
2729 (if arg (let ((url (bibtex-url nil t)))
2730 (if url (kill-new (message "%s" url))
2731 (message "No URL known")))
2732 (save-excursion
2733 (bibtex-beginning-of-entry)
2734 (if (looking-at bibtex-entry-maybe-empty-head)
2735 (kill-new (message "%s" (funcall bibtex-summary-function)))
2736 (error "No entry found")))))
2738 (defun bibtex-summary ()
2739 "Return summary of current BibTeX entry.
2740 Used as default value of `bibtex-summary-function'."
2741 ;; It would be neat to make this function customizable. How?
2742 (if (looking-at bibtex-entry-maybe-empty-head)
2743 (let* ((bibtex-autokey-name-case-convert-function 'identity)
2744 (bibtex-autokey-name-length 'infty)
2745 (bibtex-autokey-names 1)
2746 (bibtex-autokey-names-stretch 0)
2747 (bibtex-autokey-name-separator " ")
2748 (bibtex-autokey-additional-names " etal")
2749 (names (bibtex-autokey-get-names))
2750 (bibtex-autokey-year-length 4)
2751 (year (bibtex-autokey-get-year))
2752 (bibtex-autokey-titlewords 5)
2753 (bibtex-autokey-titlewords-stretch 2)
2754 (bibtex-autokey-titleword-case-convert-function 'identity)
2755 (bibtex-autokey-titleword-length 5)
2756 (bibtex-autokey-titleword-separator " ")
2757 (title (bibtex-autokey-get-title))
2758 (journal (bibtex-autokey-get-field
2759 "journal" bibtex-autokey-transcriptions))
2760 (volume (bibtex-autokey-get-field "volume"))
2761 (pages (bibtex-autokey-get-field "pages" '(("-.*\\'" . "")))))
2762 (mapconcat (lambda (arg)
2763 (if (not (string= "" (cdr arg)))
2764 (concat (car arg) (cdr arg))))
2765 `((" " . ,names) (" " . ,year) (": " . ,title)
2766 (", " . ,journal) (" " . ,volume) (":" . ,pages))
2767 ""))
2768 (error "Entry not found")))
2770 (defun bibtex-pop (arg direction)
2771 "Fill current field from the ARGth same field's text in DIRECTION.
2772 Generic function used by `bibtex-pop-previous' and `bibtex-pop-next'."
2773 ;; parse current field
2774 (let* ((bounds (bibtex-enclosing-field t))
2775 (start-old-field (bibtex-start-of-field bounds))
2776 (start-old-text (bibtex-start-of-text-in-field bounds))
2777 (end-old-text (bibtex-end-of-text-in-field bounds))
2778 (field-name (bibtex-name-in-field bounds t))
2779 failure)
2780 (save-excursion
2781 ;; if executed several times in a row, start each search where
2782 ;; the last one was finished
2783 (cond ((eq last-command 'bibtex-pop)
2784 (goto-char (if (eq direction 'previous)
2785 bibtex-pop-previous-search-point
2786 bibtex-pop-next-search-point)))
2787 ((eq direction 'previous)
2788 (bibtex-beginning-of-entry))
2789 (t (bibtex-end-of-entry)))
2790 ;; Search for arg'th previous/next similar field
2791 (while (and (not failure)
2792 (>= (setq arg (1- arg)) 0))
2793 ;; The search of BibTeX fields is not bounded by entry boundaries
2794 (if (eq direction 'previous)
2795 (if (setq bounds (bibtex-search-backward-field field-name))
2796 (goto-char (bibtex-start-of-field bounds))
2797 (setq failure t))
2798 (if (setq bounds (bibtex-search-forward-field field-name))
2799 (goto-char (bibtex-end-of-field bounds))
2800 (setq failure t))))
2801 (if failure
2802 (error "No %s matching BibTeX field"
2803 (if (eq direction 'previous) "previous" "next"))
2804 ;; Found a matching field. Remember boundaries.
2805 (let ((new-text (bibtex-text-in-field-bounds bounds))
2806 (nbeg (copy-marker (bibtex-start-of-field bounds)))
2807 (nend (copy-marker (bibtex-end-of-field bounds))))
2808 (bibtex-flash-head "From: ")
2809 ;; Go back to where we started, delete old text, and pop new.
2810 (goto-char end-old-text)
2811 (delete-region start-old-text end-old-text)
2812 (if (= nbeg start-old-field)
2813 (insert (bibtex-field-left-delimiter)
2814 (bibtex-field-right-delimiter))
2815 (insert new-text))
2816 (setq bibtex-pop-previous-search-point (marker-position nbeg)
2817 bibtex-pop-next-search-point (marker-position nend))))))
2818 (bibtex-find-text nil nil nil t)
2819 (setq this-command 'bibtex-pop))
2821 (defun bibtex-beginning-of-field ()
2822 "Move point backward to beginning of field.
2823 This function uses a simple, fast algorithm assuming that the field
2824 begins at the beginning of a line. We use this function for font-locking."
2825 (let ((field-reg (concat "^[ \t]*" bibtex-field-name "[ \t]*=")))
2826 (beginning-of-line)
2827 (unless (looking-at field-reg)
2828 (re-search-backward field-reg nil t))))
2830 (defun bibtex-font-lock-url (bound &optional no-button)
2831 "Font-lock for URLs. BOUND limits the search.
2832 If NO-BUTTON is non-nil do not generate buttons."
2833 (let ((case-fold-search t)
2834 (pnt (point))
2835 name bounds start end found)
2836 (bibtex-beginning-of-field)
2837 (while (and (not found)
2838 (<= (point) bound)
2839 (prog1 (re-search-forward bibtex-font-lock-url-regexp bound t)
2840 (setq name (match-string-no-properties 1)))
2841 (setq bounds (bibtex-parse-field-text))
2842 (progn
2843 (setq start (car bounds) end (nth 1 bounds))
2844 ;; Always ignore field delimiters
2845 (if (memq (char-before end) '(?\} ?\"))
2846 (setq end (1- end)))
2847 (if (memq (char-after start) '(?\{ ?\"))
2848 (setq start (1+ start)))
2849 (if (< start pnt) (setq start (min pnt end)))
2850 (<= start bound)))
2851 (if (<= pnt start)
2852 (let ((lst bibtex-generate-url-list) url)
2853 (while (and (not found) (setq url (car (pop lst))))
2854 (goto-char start)
2855 (setq found (and (bibtex-string= name (car url))
2856 (re-search-forward (cdr url) end t))))))
2857 (unless found (goto-char end)))
2858 (if (and found (not no-button))
2859 (bibtex-button (match-beginning 0) (match-end 0)
2860 'bibtex-url (match-beginning 0)))
2861 found))
2863 (defun bibtex-font-lock-crossref (bound)
2864 "Font-lock for crossref fields. BOUND limits the search."
2865 (let ((case-fold-search t)
2866 (pnt (point))
2867 (crossref-reg (concat "^[ \t]*crossref[ \t]*=[ \t\n]*"
2868 "\\(\"[^\"]*\"\\|{[^}]*}\\)[ \t\n]*[,})]"))
2869 start end found)
2870 (bibtex-beginning-of-field)
2871 (while (and (not found)
2872 (re-search-forward crossref-reg bound t))
2873 (setq start (1+ (match-beginning 1))
2874 end (1- (match-end 1))
2875 found (>= start pnt)))
2876 (if found (bibtex-button start end 'bibtex-search-crossref
2877 (buffer-substring-no-properties start end)
2878 start t))
2879 found))
2881 (defun bibtex-font-lock-cite (matcher bound)
2882 "Font-lock for cited keys.
2883 MATCHER identifies the cited key, see `bibtex-cite-matcher-alist'.
2884 BOUND limits the search."
2885 (let (case-fold-search)
2886 (if (re-search-forward (car matcher) bound t)
2887 (let ((start (match-beginning (cdr matcher)))
2888 (end (match-end (cdr matcher))))
2889 (bibtex-button start end 'bibtex-search-crossref
2890 (buffer-substring-no-properties start end)
2891 start t t)
2892 t))))
2894 (defun bibtex-button-action (button)
2895 "Call BUTTON's BibTeX function."
2896 (apply (button-get button 'bibtex-function)
2897 (button-get button 'bibtex-args)))
2899 (define-button-type 'bibtex-url
2900 'action 'bibtex-button-action
2901 'bibtex-function 'bibtex-url
2902 'help-echo (purecopy "mouse-2, RET: follow URL"))
2904 (define-button-type 'bibtex-search-crossref
2905 'action 'bibtex-button-action
2906 'bibtex-function 'bibtex-search-crossref
2907 'help-echo (purecopy "mouse-2, RET: follow crossref"))
2909 (defun bibtex-button (beg end type &rest args)
2910 "Make a BibTeX button from BEG to END of type TYPE in the current buffer."
2911 (make-text-button beg end 'type type 'bibtex-args args))
2914 ;; Interactive Functions:
2916 ;;;###autoload
2917 (defun bibtex-mode ()
2918 "Major mode for editing BibTeX files.
2920 General information on working with BibTeX mode:
2922 Use commands such as \\[bibtex-Book] to get a template for a specific entry.
2923 Then fill in all desired fields using \\[bibtex-next-field] to jump from field
2924 to field. After having filled in all desired fields in the entry, clean the
2925 new entry with the command \\[bibtex-clean-entry].
2927 Some features of BibTeX mode are available only by setting the variable
2928 `bibtex-maintain-sorted-entries' to non-nil. However, then BibTeX mode
2929 works only with buffers containing valid (syntactical correct) and sorted
2930 entries. This is usually the case, if you have created a buffer completely
2931 with BibTeX mode and finished every new entry with \\[bibtex-clean-entry].
2933 For third party BibTeX files, call the command \\[bibtex-convert-alien]
2934 to fully take advantage of all features of BibTeX mode.
2937 Special information:
2939 A command such as \\[bibtex-Book] outlines the fields for a BibTeX book entry.
2941 The names of optional fields start with the string OPT, and are thus ignored
2942 by BibTeX. The names of alternative fields from which only one is required
2943 start with the string ALT. The OPT or ALT string may be removed from
2944 the name of a field with \\[bibtex-remove-OPT-or-ALT].
2945 \\[bibtex-make-field] inserts a new field after the current one.
2946 \\[bibtex-kill-field] kills the current field entirely.
2947 \\[bibtex-yank] yanks the last recently killed field after the current field.
2948 \\[bibtex-remove-delimiters] removes the double-quotes or braces around the text of the current field.
2949 \\[bibtex-empty-field] replaces the text of the current field with the default \"\" or {}.
2950 \\[bibtex-find-text] moves point to the end of the current field.
2951 \\[bibtex-complete] completes word fragment before point according to context.
2953 The command \\[bibtex-clean-entry] cleans the current entry, i.e. it removes OPT/ALT
2954 from the names of all non-empty optional or alternative fields, checks that
2955 no required fields are empty, and does some formatting dependent on the value
2956 of `bibtex-entry-format'. Furthermore, it can automatically generate a key
2957 for the BibTeX entry, see `bibtex-generate-autokey'.
2958 Note: some functions in BibTeX mode depend on entries being in a special
2959 format (all fields beginning on separate lines), so it is usually a bad
2960 idea to remove `realign' from `bibtex-entry-format'.
2962 BibTeX mode supports Imenu and hideshow minor mode (`hs-minor-mode').
2964 ----------------------------------------------------------
2965 Entry to BibTeX mode calls the value of `bibtex-mode-hook'
2966 if that value is non-nil.
2968 \\{bibtex-mode-map}"
2969 (interactive)
2970 (kill-all-local-variables)
2971 (use-local-map bibtex-mode-map)
2972 (setq major-mode 'bibtex-mode)
2973 (setq mode-name "BibTeX")
2974 (set-syntax-table bibtex-mode-syntax-table)
2975 (make-local-variable 'bibtex-buffer-last-parsed-tick)
2976 ;; Install stealthy parse function if not already installed
2977 (unless bibtex-parse-idle-timer
2978 (setq bibtex-parse-idle-timer (run-with-idle-timer
2979 bibtex-parse-keys-timeout t
2980 'bibtex-parse-buffers-stealthily)))
2981 (set (make-local-variable 'paragraph-start) "[ \f\n\t]*$")
2982 (set (make-local-variable 'comment-start) bibtex-comment-start)
2983 (set (make-local-variable 'comment-start-skip)
2984 (concat (regexp-quote bibtex-comment-start) "\\>[ \t]*"))
2985 (set (make-local-variable 'comment-column) 0)
2986 (set (make-local-variable 'defun-prompt-regexp) "^[ \t]*@[[:alnum:]]+[ \t]*")
2987 (set (make-local-variable 'outline-regexp) "[ \t]*@")
2988 (set (make-local-variable 'fill-paragraph-function) 'bibtex-fill-field)
2989 (set (make-local-variable 'fill-prefix) (make-string (+ bibtex-entry-offset
2990 bibtex-contline-indentation)
2991 ?\s))
2992 (set (make-local-variable 'font-lock-defaults)
2993 '(bibtex-font-lock-keywords
2994 nil t ((?$ . "\"")
2995 ;; Mathematical expressions should be fontified as strings
2996 (?\" . ".")
2997 ;; Quotes are field delimiters and quote-delimited
2998 ;; entries should be fontified in the same way as
2999 ;; brace-delimited ones
3002 (font-lock-syntactic-keywords . bibtex-font-lock-syntactic-keywords)
3003 (font-lock-extra-managed-props . (category))
3004 (font-lock-mark-block-function
3005 . (lambda ()
3006 (set-mark (bibtex-end-of-entry))
3007 (bibtex-beginning-of-entry)))))
3008 (setq imenu-generic-expression
3009 (list (list nil bibtex-entry-head bibtex-key-in-head))
3010 imenu-case-fold-search t)
3011 (make-local-variable 'choose-completion-string-functions)
3012 ;; XEmacs needs `easy-menu-add', Emacs does not care
3013 (easy-menu-add bibtex-edit-menu)
3014 (easy-menu-add bibtex-entry-menu)
3015 (run-mode-hooks 'bibtex-mode-hook))
3017 (defun bibtex-field-list (entry-type)
3018 "Return list of allowed fields for entry ENTRY-TYPE.
3019 More specifically, the return value is a cons pair (REQUIRED . OPTIONAL),
3020 where REQUIRED and OPTIONAL are lists of the required and optional field
3021 names for ENTRY-TYPE according to `bibtex-entry-field-alist',
3022 `bibtex-include-OPTkey', `bibtex-include-OPTcrossref',
3023 and `bibtex-user-optional-fields'."
3024 (let ((e (assoc-string entry-type bibtex-entry-field-alist t))
3025 required optional)
3026 (unless e
3027 (error "Fields for BibTeX entry type %s not defined" entry-type))
3028 (if (and (member-ignore-case entry-type bibtex-include-OPTcrossref)
3029 (nth 2 e))
3030 (setq required (nth 0 (nth 2 e))
3031 optional (nth 1 (nth 2 e)))
3032 (setq required (nth 0 (nth 1 e))
3033 optional (nth 1 (nth 1 e))))
3034 (if bibtex-include-OPTkey
3035 (push (list "key"
3036 "Used for reference key creation if author and editor fields are missing"
3037 (if (or (stringp bibtex-include-OPTkey)
3038 (functionp bibtex-include-OPTkey))
3039 bibtex-include-OPTkey))
3040 optional))
3041 (if (member-ignore-case entry-type bibtex-include-OPTcrossref)
3042 (push '("crossref" "Reference key of the cross-referenced entry")
3043 optional))
3044 (setq optional (append optional bibtex-user-optional-fields))
3045 (cons required optional)))
3047 (defun bibtex-entry (entry-type)
3048 "Insert a new BibTeX entry of type ENTRY-TYPE.
3049 After insertion call the value of `bibtex-add-entry-hook' if that value
3050 is non-nil."
3051 (interactive
3052 (let ((completion-ignore-case t))
3053 (list (completing-read "Entry Type: " bibtex-entry-field-alist
3054 nil t nil 'bibtex-entry-type-history))))
3055 (let ((key (if bibtex-maintain-sorted-entries
3056 (bibtex-read-key (format "%s key: " entry-type))))
3057 (field-list (bibtex-field-list entry-type)))
3058 (unless (bibtex-prepare-new-entry (list key nil entry-type))
3059 (error "Entry with key `%s' already exists" key))
3060 (indent-to-column bibtex-entry-offset)
3061 (insert "@" entry-type (bibtex-entry-left-delimiter))
3062 (if key (insert key))
3063 (save-excursion
3064 (mapc 'bibtex-make-field (car field-list))
3065 (mapc 'bibtex-make-optional-field (cdr field-list))
3066 (if bibtex-comma-after-last-field
3067 (insert ","))
3068 (insert "\n")
3069 (indent-to-column bibtex-entry-offset)
3070 (insert (bibtex-entry-right-delimiter) "\n\n"))
3071 (bibtex-next-field t)
3072 (if (member-ignore-case entry-type bibtex-autofill-types)
3073 (bibtex-autofill-entry))
3074 (run-hooks 'bibtex-add-entry-hook)))
3076 (defun bibtex-entry-update (&optional entry-type)
3077 "Update an existing BibTeX entry.
3078 In the BibTeX entry at point, make new fields for those items that may occur
3079 according to `bibtex-field-list', but are not yet present.
3080 Also, add field delimiters to numerical fields if they are not present.
3081 If ENTRY-TYPE is non-nil, change first the entry type to ENTRY-TYPE.
3082 When called interactively with a prefix arg, query for a value of ENTRY-TYPE."
3083 (interactive
3084 (list (if current-prefix-arg
3085 (let ((completion-ignore-case t))
3086 (completing-read "New entry type: " bibtex-entry-field-alist
3087 nil t nil 'bibtex-entry-type-history)))))
3088 (save-excursion
3089 (bibtex-beginning-of-entry)
3090 (when (looking-at bibtex-entry-maybe-empty-head)
3091 (goto-char (match-end 0))
3092 (if entry-type
3093 (save-excursion
3094 (replace-match (concat "@" entry-type) nil nil nil 1))
3095 (setq entry-type (bibtex-type-in-head)))
3096 (let* ((field-list (bibtex-field-list entry-type))
3097 (required (copy-tree (car field-list)))
3098 (optional (copy-tree (cdr field-list)))
3099 bounds)
3100 (while (setq bounds (bibtex-parse-field))
3101 (let ((fname (bibtex-name-in-field bounds t))
3102 (end (copy-marker (bibtex-end-of-field bounds) t)))
3103 (setq required (delete (assoc-string fname required t) required)
3104 optional (delete (assoc-string fname optional t) optional))
3105 (when (string-match "\\`[0-9]+\\'"
3106 (bibtex-text-in-field-bounds bounds))
3107 (goto-char (bibtex-end-of-text-in-field bounds))
3108 (insert (bibtex-field-right-delimiter))
3109 (goto-char (bibtex-start-of-text-in-field bounds))
3110 (insert (bibtex-field-left-delimiter)))
3111 (goto-char end)))
3112 (skip-chars-backward " \t\n")
3113 (dolist (field required) (bibtex-make-field field))
3114 (dolist (field optional) (bibtex-make-optional-field field))))))
3116 (defun bibtex-parse-entry (&optional content)
3117 "Parse entry at point, return an alist.
3118 The alist elements have the form (FIELD . TEXT), where FIELD can also be
3119 the special strings \"=type=\" and \"=key=\". For the FIELD \"=key=\"
3120 TEXT may be nil. Remove \"OPT\" and \"ALT\" from FIELD.
3121 Move point to the end of the last field.
3122 If optional arg CONTENT is non-nil extract content of text fields."
3123 (let (alist bounds)
3124 (when (looking-at bibtex-entry-maybe-empty-head)
3125 (push (cons "=type=" (bibtex-type-in-head)) alist)
3126 (push (cons "=key=" (bibtex-key-in-head)) alist)
3127 (goto-char (match-end 0))
3128 (while (setq bounds (bibtex-parse-field))
3129 (push (cons (bibtex-name-in-field bounds t)
3130 (bibtex-text-in-field-bounds bounds content))
3131 alist)
3132 (goto-char (bibtex-end-of-field bounds))))
3133 alist))
3135 (defun bibtex-autofill-entry ()
3136 "Try to fill fields of current BibTeX entry based on neighboring entries.
3137 The current entry must have a key. Determine the neighboring entry
3138 \(previouse or next\) whose key is more similar to the key of the current
3139 entry. For all empty fields of the current entry insert the corresponding
3140 field contents of the neighboring entry. Finally try to update the text
3141 based on the difference between the keys of the neighboring and the current
3142 entry (for example, the year parts of the keys)."
3143 (interactive)
3144 (bibtex-beginning-of-entry)
3145 (when (looking-at bibtex-entry-head)
3146 (let ((type (bibtex-type-in-head))
3147 (key (bibtex-key-in-head))
3148 (key-end (match-end bibtex-key-in-head))
3149 (case-fold-search t)
3150 (bibtex-sort-ignore-string-entries t)
3151 tmp other-key other bounds)
3152 ;; The fields we want to change start right after the key.
3153 (goto-char key-end)
3154 ;; First see whether to use the previous or the next entry
3155 ;; for "inspiration".
3156 (save-excursion
3157 (goto-char (1- (match-beginning 0)))
3158 (bibtex-beginning-of-entry)
3159 (if (and (looking-at bibtex-entry-head)
3160 (bibtex-string= type (bibtex-type-in-head))
3161 ;; In case we found ourselves :-(
3162 (not (equal key (setq tmp (bibtex-key-in-head)))))
3163 (setq other-key tmp
3164 other (point))))
3165 (save-excursion
3166 (bibtex-end-of-entry)
3167 (bibtex-skip-to-valid-entry)
3168 (if (and (looking-at bibtex-entry-head)
3169 (bibtex-string= type (bibtex-type-in-head))
3170 ;; In case we found ourselves :-(
3171 (not (equal key (setq tmp (bibtex-key-in-head))))
3172 (or (not other-key)
3173 ;; Check which is the best match.
3174 (< (length (try-completion "" (list key other-key)))
3175 (length (try-completion "" (list key tmp))))))
3176 (setq other-key tmp
3177 other (point))))
3178 ;; Then fill the new entry's fields with the chosen other entry.
3179 (when other
3180 (setq other (save-excursion (goto-char other) (bibtex-parse-entry)))
3181 (setq key-end (point)) ;In case parse-entry changed the buffer.
3182 (while (setq bounds (bibtex-parse-field))
3183 (let ((text (assoc-string (bibtex-name-in-field bounds t)
3184 other t)))
3185 (if (not (and text
3186 (equal "" (bibtex-text-in-field-bounds bounds t))))
3187 (goto-char (bibtex-end-of-field bounds))
3188 (goto-char (bibtex-start-of-text-in-field bounds))
3189 (delete-region (point) (bibtex-end-of-text-in-field bounds))
3190 (insert (cdr text)))))
3191 ;; Finally try to update the text based on the difference between
3192 ;; the two keys.
3193 (let* ((prefix (try-completion "" (list key other-key)))
3194 ;; If the keys are foo91 and foo92, don't replace 1 for 2
3195 ;; but 91 for 92 instead.
3196 (_ (if (string-match "[0-9]+\\'" prefix)
3197 (setq prefix (substring prefix 0 (match-beginning 0)))))
3198 (suffix (substring key (length prefix)))
3199 (other-suffix (substring other-key (length prefix))))
3200 (while (re-search-backward (regexp-quote other-suffix) key-end 'move)
3201 (replace-match suffix)))))))
3203 (defun bibtex-print-help-message (&optional field comma)
3204 "Print helpful information about current FIELD in current BibTeX entry.
3205 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3206 interactive calls."
3207 (interactive (list nil t))
3208 (unless field (setq field (car (bibtex-find-text-internal nil nil comma))))
3209 (if (string-match "@" field)
3210 (cond ((bibtex-string= field "@string")
3211 (message "String definition"))
3212 ((bibtex-string= field "@preamble")
3213 (message "Preamble definition"))
3214 (t (message "Entry key")))
3215 (let* ((case-fold-search t)
3216 (type (save-excursion
3217 (bibtex-beginning-of-entry)
3218 (looking-at bibtex-entry-maybe-empty-head)
3219 (bibtex-type-in-head)))
3220 (field-list (bibtex-field-list type))
3221 (comment (assoc-string field (append (car field-list)
3222 (cdr field-list)) t)))
3223 (if comment (message "%s" (nth 1 comment))
3224 (message "No comment available")))))
3226 (defun bibtex-make-field (field &optional move interactive nodelim)
3227 "Make a field named FIELD in current BibTeX entry.
3228 FIELD is either a string or a list of the form
3229 \(FIELD-NAME COMMENT-STRING INIT ALTERNATIVE-FLAG) as in
3230 `bibtex-entry-field-alist'.
3231 If MOVE is non-nil, move point past the present field before making
3232 the new field. If INTERACTIVE is non-nil, move point to the end of
3233 the new field. Otherwise move point past the new field.
3234 MOVE and INTERACTIVE are t when called interactively.
3235 INIT is surrounded by field delimiters, unless NODELIM is non-nil."
3236 (interactive
3237 (list (let ((completion-ignore-case t)
3238 (field-list (bibtex-field-list
3239 (save-excursion
3240 (bibtex-beginning-of-entry)
3241 (looking-at bibtex-any-entry-maybe-empty-head)
3242 (bibtex-type-in-head)))))
3243 (completing-read "BibTeX field name: "
3244 (append (car field-list) (cdr field-list))
3245 nil nil nil bibtex-field-history))
3246 t t))
3247 (unless (consp field)
3248 (setq field (list field)))
3249 (when move
3250 (bibtex-find-text)
3251 (if (looking-at "[}\"]")
3252 (forward-char)))
3253 (insert ",\n")
3254 (indent-to-column (+ bibtex-entry-offset bibtex-field-indentation))
3255 (if (nth 3 field) (insert "ALT"))
3256 (insert (car field) " ")
3257 (if bibtex-align-at-equal-sign
3258 (indent-to-column (+ bibtex-entry-offset
3259 (- bibtex-text-indentation 2))))
3260 (insert "= ")
3261 (unless bibtex-align-at-equal-sign
3262 (indent-to-column (+ bibtex-entry-offset
3263 bibtex-text-indentation)))
3264 (let ((init (nth 2 field)))
3265 (if (not init) (setq init "")
3266 (if (functionp init) (setq init (funcall init)))
3267 (unless (stringp init) (error "`%s' is not a string" init)))
3268 ;; NODELIM is required by `bibtex-insert-kill'
3269 (if nodelim (insert init)
3270 (insert (bibtex-field-left-delimiter) init
3271 (bibtex-field-right-delimiter))))
3272 (when interactive
3273 ;; (bibtex-find-text nil nil bibtex-help-message)
3274 (if (memq (preceding-char) '(?} ?\")) (forward-char -1))
3275 (if bibtex-help-message (bibtex-print-help-message (car field)))))
3277 (defun bibtex-beginning-of-entry ()
3278 "Move to beginning of BibTeX entry (beginning of line).
3279 If inside an entry, move to the beginning of it, otherwise move to the
3280 beginning of the previous entry. If point is ahead of all BibTeX entries
3281 move point to the beginning of buffer. Return the new location of point."
3282 (interactive)
3283 (skip-chars-forward " \t")
3284 (if (looking-at "@")
3285 (forward-char))
3286 (re-search-backward "^[ \t]*@" nil 'move)
3287 (point))
3289 (defun bibtex-end-of-entry ()
3290 "Move to end of BibTeX entry (past the closing brace).
3291 If inside an entry, move to the end of it, otherwise move to the end
3292 of the previous entry. Do not move if ahead of first entry.
3293 Return the new location of point."
3294 (interactive)
3295 (let ((case-fold-search t)
3296 (pnt (point))
3297 (_ (bibtex-beginning-of-entry))
3298 (bounds (bibtex-valid-entry t)))
3299 (cond (bounds (goto-char (cdr bounds))) ; regular entry
3300 ;; @String or @Preamble
3301 ((setq bounds (or (bibtex-parse-string t) (bibtex-parse-preamble)))
3302 (goto-char (bibtex-end-of-string bounds)))
3303 ((looking-at bibtex-any-valid-entry-type)
3304 ;; Parsing of entry failed
3305 (error "Syntactically incorrect BibTeX entry starts here"))
3306 (t (if (interactive-p) (message "Not on a known BibTeX entry."))
3307 (goto-char pnt)))
3308 (point)))
3310 (defun bibtex-goto-line (arg)
3311 "Goto line ARG, counting from beginning of (narrowed) buffer."
3312 ;; code adapted from `goto-line'
3313 (goto-char (point-min))
3314 (if (eq selective-display t)
3315 (re-search-forward "[\n\C-m]" nil 'end (1- arg))
3316 (forward-line (1- arg))))
3318 (defun bibtex-reposition-window ()
3319 "Make the current BibTeX entry visible.
3320 If entry is smaller than `window-body-height', entry is centered in window.
3321 Otherwise display the beginning of entry."
3322 (interactive)
3323 (let ((pnt (point))
3324 (beg (line-number-at-pos (bibtex-beginning-of-entry)))
3325 (end (line-number-at-pos (bibtex-end-of-entry))))
3326 (if (> (window-body-height) (- end beg))
3327 ;; entry fits in current window
3328 (progn
3329 (bibtex-goto-line (/ (+ 1 beg end) 2))
3330 (recenter)
3331 (goto-char pnt))
3332 ;; entry too large for current window
3333 (bibtex-goto-line beg)
3334 (recenter 0)
3335 (if (> (1+ (- (line-number-at-pos pnt) beg))
3336 (window-body-height))
3337 (bibtex-goto-line beg)
3338 (goto-char pnt)))))
3340 (defun bibtex-mark-entry ()
3341 "Put mark at beginning, point at end of current BibTeX entry."
3342 (interactive)
3343 (push-mark (bibtex-beginning-of-entry))
3344 (bibtex-end-of-entry))
3346 (defun bibtex-count-entries (&optional count-string-entries)
3347 "Count number of entries in current buffer or region.
3348 With prefix argument COUNT-STRING-ENTRIES count all entries,
3349 otherwise count all entries except @String entries.
3350 If mark is active count entries in region, if not in whole buffer."
3351 (interactive "P")
3352 (let ((number 0)
3353 (bibtex-sort-ignore-string-entries (not count-string-entries)))
3354 (save-restriction
3355 (if mark-active (narrow-to-region (region-beginning) (region-end)))
3356 (bibtex-map-entries (lambda (key beg end) (setq number (1+ number)))))
3357 (message "%s contains %d entries."
3358 (if mark-active "Region" "Buffer")
3359 number)))
3361 (defun bibtex-ispell-entry ()
3362 "Check BibTeX entry for spelling errors."
3363 (interactive)
3364 (ispell-region (save-excursion (bibtex-beginning-of-entry))
3365 (save-excursion (bibtex-end-of-entry))))
3367 (defun bibtex-ispell-abstract ()
3368 "Check abstract of BibTeX entry for spelling errors."
3369 (interactive)
3370 (let ((bounds (save-excursion
3371 (bibtex-beginning-of-entry)
3372 (bibtex-search-forward-field "abstract" t))))
3373 (if bounds
3374 (ispell-region (bibtex-start-of-text-in-field bounds)
3375 (bibtex-end-of-text-in-field bounds))
3376 (error "No abstract in entry"))))
3378 (defun bibtex-narrow-to-entry ()
3379 "Narrow buffer to current BibTeX entry."
3380 (interactive)
3381 (save-excursion
3382 (widen)
3383 (narrow-to-region (bibtex-beginning-of-entry)
3384 (bibtex-end-of-entry))))
3386 (defun bibtex-entry-index ()
3387 "Return index of BibTeX entry head at or past position of point.
3388 The index is a list (KEY CROSSREF-KEY ENTRY-TYPE) that is used for sorting
3389 the entries of the BibTeX buffer. CROSSREF-KEY is nil unless the value
3390 of `bibtex-maintain-sorted-entries' is `crossref'. Move point to the end
3391 of the head of the entry found. Return nil if no entry found."
3392 (let ((case-fold-search t))
3393 (if (re-search-forward bibtex-entry-maybe-empty-head nil t)
3394 (let ((key (bibtex-key-in-head))
3395 ;; all entry types should be downcase (for ease of comparison)
3396 (entry-type (downcase (bibtex-type-in-head))))
3397 ;; Don't search CROSSREF-KEY if we don't need it.
3398 (if (eq bibtex-maintain-sorted-entries 'crossref)
3399 (let ((bounds (bibtex-search-forward-field
3400 "\\(OPT\\)?crossref" t)))
3401 (list key
3402 (if bounds (bibtex-text-in-field-bounds bounds t))
3403 entry-type))
3404 (list key nil entry-type))))))
3406 (defun bibtex-init-sort-entry-class-alist ()
3407 "Initialize `bibtex-sort-entry-class-alist' (buffer-local)."
3408 (unless (local-variable-p 'bibtex-sort-entry-class-alist)
3409 (set (make-local-variable 'bibtex-sort-entry-class-alist)
3410 (let ((i -1) alist)
3411 (dolist (class bibtex-sort-entry-class alist)
3412 (setq i (1+ i))
3413 (dolist (entry class)
3414 ;; All entry types should be downcase (for ease of comparison).
3415 (push (cons (if (stringp entry) (downcase entry) entry) i)
3416 alist)))))))
3418 (defun bibtex-lessp (index1 index2)
3419 "Predicate for sorting BibTeX entries with indices INDEX1 and INDEX2.
3420 Each index is a list (KEY CROSSREF-KEY ENTRY-TYPE).
3421 The predicate depends on the variable `bibtex-maintain-sorted-entries'.
3422 If its value is nil use plain sorting."
3423 (cond ((not index1) (not index2)) ; indices can be nil
3424 ((not index2) nil)
3425 ((eq bibtex-maintain-sorted-entries 'crossref)
3426 ;; CROSSREF-KEY may be nil or it can point to an entry
3427 ;; in another BibTeX file. In both cases we ignore CROSSREF-KEY.
3428 (if (and (nth 1 index1)
3429 (cdr (assoc-string (nth 1 index1) bibtex-reference-keys)))
3430 (if (and (nth 1 index2)
3431 (cdr (assoc-string (nth 1 index2) bibtex-reference-keys)))
3432 (or (string-lessp (nth 1 index1) (nth 1 index2))
3433 (and (string-equal (nth 1 index1) (nth 1 index2))
3434 (string-lessp (nth 0 index1) (nth 0 index2))))
3435 (not (string-lessp (nth 0 index2) (nth 1 index1))))
3436 (if (and (nth 1 index2)
3437 (cdr (assoc-string (nth 1 index2) bibtex-reference-keys)))
3438 (string-lessp (nth 0 index1) (nth 1 index2))
3439 (string-lessp (nth 0 index1) (nth 0 index2)))))
3440 ((eq bibtex-maintain-sorted-entries 'entry-class)
3441 (let ((n1 (cdr (or (assoc (nth 2 index1) bibtex-sort-entry-class-alist)
3442 (assoc 'catch-all bibtex-sort-entry-class-alist)
3443 '(nil . 1000)))) ; if there is nothing else
3444 (n2 (cdr (or (assoc (nth 2 index2) bibtex-sort-entry-class-alist)
3445 (assoc 'catch-all bibtex-sort-entry-class-alist)
3446 '(nil . 1000))))) ; if there is nothing else
3447 (or (< n1 n2)
3448 (and (= n1 n2)
3449 (string-lessp (car index1) (car index2))))))
3450 (t ; (eq bibtex-maintain-sorted-entries 'plain)
3451 (string-lessp (car index1) (car index2)))))
3453 (defun bibtex-sort-buffer ()
3454 "Sort BibTeX buffer alphabetically by key.
3455 The predicate for sorting is defined via `bibtex-maintain-sorted-entries'.
3456 If its value is nil use plain sorting. Text outside of BibTeX entries is not
3457 affected. If `bibtex-sort-ignore-string-entries' is non-nil, @String entries
3458 are ignored."
3459 (interactive)
3460 (bibtex-beginning-of-first-entry) ; Needed by `sort-subr'
3461 (bibtex-init-sort-entry-class-alist) ; Needed by `bibtex-lessp'.
3462 (if (and (eq bibtex-maintain-sorted-entries 'crossref)
3463 (nlistp bibtex-reference-keys))
3464 (bibtex-parse-keys)) ; Needed by `bibtex-lessp'.
3465 (sort-subr nil
3466 'bibtex-skip-to-valid-entry ; NEXTREC function
3467 'bibtex-end-of-entry ; ENDREC function
3468 'bibtex-entry-index ; STARTKEY function
3469 nil ; ENDKEY function
3470 'bibtex-lessp)) ; PREDICATE
3472 (defun bibtex-search-crossref (crossref-key &optional pnt split noerror)
3473 "Move point to the beginning of BibTeX entry CROSSREF-KEY.
3474 If `bibtex-files' is non-nil, search all these files.
3475 Otherwise the search is limited to the current buffer.
3476 Return position of entry if CROSSREF-KEY is found or nil otherwise.
3477 If CROSSREF-KEY is in the same buffer like current entry but before it
3478 an error is signaled. If NOERRER is non-nil this error is suppressed.
3479 Optional arg PNT is the position of the referencing entry. It defaults
3480 to position of point. If optional arg SPLIT is non-nil, split window
3481 so that both the referencing and the crossrefed entry are displayed.
3483 If called interactively, CROSSREF-KEY defaults to either the crossref key
3484 of current entry or a key matched by `bibtex-cite-matcher-alist',
3485 whatever is nearer to the position of point. SPLIT is t. NOERROR is nil
3486 for a crossref key, t otherwise."
3487 (interactive
3488 (save-excursion
3489 (let* ((pnt (point))
3490 (_ (bibtex-beginning-of-entry))
3491 (end (cdr (bibtex-valid-entry t)))
3492 (_ (unless end (error "Not inside valid entry")))
3493 (beg (match-end 0)) ; set by `bibtex-valid-entry'
3494 (bounds (bibtex-search-forward-field "crossref" end))
3495 case-fold-search best temp crossref-key)
3496 (if bounds
3497 (setq crossref-key (bibtex-text-in-field-bounds bounds t)
3498 best (cons (bibtex-dist pnt (bibtex-end-of-field bounds)
3499 (bibtex-start-of-field bounds))
3500 crossref-key)))
3501 (dolist (matcher bibtex-cite-matcher-alist)
3502 (goto-char beg)
3503 (while (re-search-forward (car matcher) end t)
3504 (setq temp (bibtex-dist pnt (match-end (cdr matcher))
3505 (match-beginning (cdr matcher))))
3506 ;; Accept the key closest to the position of point.
3507 (if (or (not best) (< temp (car best)))
3508 (setq best (cons temp (match-string-no-properties
3509 (cdr matcher)))))))
3510 (goto-char pnt)
3511 (setq temp (bibtex-read-key "Find crossref key: " (cdr best) t))
3512 (list temp (point) t (not (and crossref-key
3513 (string= temp crossref-key)))))))
3515 (let (buffer pos eqb)
3516 (save-excursion
3517 (setq pos (bibtex-search-entry crossref-key t)
3518 buffer (current-buffer)))
3519 (setq eqb (eq buffer (current-buffer)))
3520 (cond ((not pos)
3521 (if split (message "Crossref key `%s' not found" crossref-key)))
3522 (split ; called (quasi) interactively
3523 (unless pnt (setq pnt (point)))
3524 (goto-char pnt)
3525 (if (and eqb (= pos (save-excursion (bibtex-beginning-of-entry))))
3526 (message "Key `%s' is current entry" crossref-key)
3527 (if eqb (select-window (split-window))
3528 (pop-to-buffer buffer))
3529 (goto-char pos)
3530 (bibtex-reposition-window)
3531 (beginning-of-line)
3532 (if (and eqb (> pnt pos) (not noerror))
3533 (error "The referencing entry must precede the crossrefed entry!"))))
3534 ;; `bibtex-search-crossref' is called noninteractively during
3535 ;; clean-up of an entry. Then it is not possible to check
3536 ;; whether the current entry and the crossrefed entry have
3537 ;; the correct sorting order.
3538 (eqb (goto-char pos))
3539 (t (set-buffer buffer) (goto-char pos)))
3540 pos))
3541 ;; backward compatibility
3542 (defalias 'bibtex-find-crossref 'bibtex-search-crossref)
3544 (defun bibtex-dist (pos beg end)
3545 "Return distance between POS and region delimited by BEG and END."
3546 (cond ((and (<= beg pos) (<= pos end)) 0)
3547 ((< pos beg) (- beg pos))
3548 (t (- pos end))))
3550 ;;;###autoload
3551 (defun bibtex-search-entry (key &optional global start display)
3552 "Move point to the beginning of BibTeX entry named KEY.
3553 Return position of entry if KEY is found or nil if not found.
3554 With GLOBAL non-nil, search KEY in `bibtex-files'. Otherwise the search
3555 is limited to the current buffer. Optional arg START is buffer position
3556 where the search starts. If it is nil, start search at beginning of buffer.
3557 If DISPLAY is non-nil, display the buffer containing KEY.
3558 Otherwise, use `set-buffer'.
3559 When called interactively, GLOBAL is t if there is a prefix arg or the current
3560 mode is not `bibtex-mode', START is nil, and DISPLAY is t."
3561 (interactive
3562 (let ((global (or current-prefix-arg (not (eq major-mode 'bibtex-mode)))))
3563 (list (bibtex-read-key "Find key: " nil global) global nil t)))
3564 (if (and global bibtex-files)
3565 (let ((buffer-list (bibtex-initialize t))
3566 buffer found)
3567 (while (and (not found)
3568 (setq buffer (pop buffer-list)))
3569 (with-current-buffer buffer
3570 (if (and (listp bibtex-reference-keys)
3571 (cdr (assoc-string key bibtex-reference-keys)))
3572 ;; `bibtex-search-entry' moves point if key found
3573 (setq found (bibtex-search-entry key)))))
3574 (cond ((and found display)
3575 (let ((same-window-buffer-names
3576 (cons (buffer-name buffer) same-window-buffer-names)))
3577 (pop-to-buffer buffer)
3578 (bibtex-reposition-window)))
3579 (found (set-buffer buffer))
3580 (display (message "Key `%s' not found" key)))
3581 found)
3583 (let* ((case-fold-search t)
3584 (pnt (save-excursion
3585 (goto-char (or start (point-min)))
3586 (if (re-search-forward (concat "^[ \t]*\\("
3587 bibtex-entry-type
3588 "\\)[ \t]*[({][ \t\n]*\\("
3589 (regexp-quote key)
3590 "\\)[ \t\n]*[,=]")
3591 nil t)
3592 (match-beginning 0)))))
3593 (cond (pnt
3594 (goto-char pnt)
3595 (if display (bibtex-reposition-window)))
3596 (display (message "Key `%s' not found" key)))
3597 pnt)))
3598 ;; backward compatibility
3599 (defalias 'bibtex-find-entry 'bibtex-search-entry)
3601 (defun bibtex-prepare-new-entry (index)
3602 "Prepare a new BibTeX entry with index INDEX.
3603 INDEX is a list (KEY CROSSREF-KEY ENTRY-TYPE).
3604 Move point where the entry KEY should be placed.
3605 If `bibtex-maintain-sorted-entries' is non-nil, perform a binary
3606 search to look for place for KEY. This requires that buffer is sorted,
3607 see `bibtex-validate'.
3608 Return t if preparation was successful or nil if entry KEY already exists."
3609 (bibtex-init-sort-entry-class-alist) ; Needed by `bibtex-lessp'.
3610 (if (and (eq bibtex-maintain-sorted-entries 'crossref)
3611 (nlistp bibtex-reference-keys))
3612 (bibtex-parse-keys)) ; Needed by `bibtex-lessp'.
3613 (let ((key (nth 0 index))
3614 key-exist)
3615 (cond ((or (null key)
3616 (and (stringp key)
3617 (string-equal key ""))
3618 (and (not (setq key-exist (bibtex-search-entry key)))
3619 (not bibtex-maintain-sorted-entries)))
3620 (bibtex-move-outside-of-entry))
3621 ;; if key-exist is non-nil due to the previous cond clause
3622 ;; then point will be at beginning of entry named key.
3623 (key-exist)
3624 (t ; `bibtex-maintain-sorted-entries' is non-nil
3625 (let* ((case-fold-search t)
3626 (left (save-excursion (bibtex-beginning-of-first-entry)))
3627 (bounds (save-excursion (goto-char (point-max))
3628 (bibtex-skip-to-valid-entry t)))
3629 (right (if bounds (cdr bounds) (point-min)))
3630 (found (if (>= left right) left))
3631 actual-index new)
3632 (save-excursion
3633 ;; Binary search
3634 (while (not found)
3635 (goto-char (/ (+ left right) 2))
3636 (bibtex-skip-to-valid-entry t)
3637 (setq actual-index (bibtex-entry-index))
3638 (cond ((bibtex-lessp index actual-index)
3639 (setq new (bibtex-beginning-of-entry))
3640 (if (equal right new)
3641 (setq found right)
3642 (setq right new)))
3644 (bibtex-end-of-entry)
3645 (bibtex-skip-to-valid-entry)
3646 (setq new (point))
3647 (if (equal left new)
3648 (setq found right)
3649 (setq left new))))))
3650 (goto-char found)
3651 (bibtex-beginning-of-entry)
3652 (setq actual-index (save-excursion (bibtex-entry-index)))
3653 (when (or (not actual-index)
3654 (bibtex-lessp actual-index index))
3655 ;; buffer contains no valid entries or
3656 ;; greater than last entry --> append
3657 (bibtex-end-of-entry)
3658 (unless (bobp) (newline (forward-line 2)))
3659 (beginning-of-line)))))
3660 (unless key-exist t)))
3662 (defun bibtex-validate (&optional test-thoroughly)
3663 "Validate if buffer or region is syntactically correct.
3664 Check also for duplicate keys and correct sort order provided
3665 `bibtex-maintain-sorted-entries' is non-nil.
3666 With optional argument TEST-THOROUGHLY non-nil check also for
3667 the absence of required fields and for questionable month fields.
3668 If mark is active, validate current region, if not the whole buffer.
3669 Only check known entry types, so you can put comments outside of entries.
3670 Return t if test was successful, nil otherwise."
3671 (interactive "P")
3672 (let* ((case-fold-search t)
3673 error-list syntax-error)
3674 (save-excursion
3675 (save-restriction
3676 (if mark-active (narrow-to-region (region-beginning) (region-end)))
3678 ;; Check syntactical structure of entries
3679 (goto-char (point-min))
3680 (bibtex-progress-message "Checking syntactical structure")
3681 (let (bounds end)
3682 (while (setq end (re-search-forward "^[ \t]*@" nil t))
3683 (bibtex-progress-message)
3684 (goto-char (match-beginning 0))
3685 (cond ((setq bounds (bibtex-valid-entry))
3686 (goto-char (cdr bounds)))
3687 ((setq bounds (or (bibtex-parse-string)
3688 (bibtex-parse-preamble)))
3689 (goto-char (bibtex-end-of-string bounds)))
3690 ((looking-at bibtex-any-valid-entry-type)
3691 (push (cons (bibtex-current-line)
3692 "Syntax error (check esp. commas, braces, and quotes)")
3693 error-list)
3694 (goto-char (match-end 0)))
3695 (t (goto-char end)))))
3696 (bibtex-progress-message 'done)
3698 (if error-list
3699 ;; Continue only if there were no syntax errors.
3700 (setq syntax-error t)
3702 ;; Check for duplicate keys and correct sort order
3703 (bibtex-init-sort-entry-class-alist) ; Needed by `bibtex-lessp'.
3704 (bibtex-parse-keys) ; Possibly needed by `bibtex-lessp'.
3705 ; Always needed by subsequent global key check.
3706 (let (previous current key-list)
3707 (bibtex-progress-message "Checking for duplicate keys")
3708 (bibtex-map-entries
3709 (lambda (key beg end)
3710 (bibtex-progress-message)
3711 (setq current (bibtex-entry-index))
3712 (cond ((not previous))
3713 ((member key key-list)
3714 (push (cons (bibtex-current-line)
3715 (format "Duplicate key `%s'" key))
3716 error-list))
3717 ((and bibtex-maintain-sorted-entries
3718 (not (bibtex-lessp previous current)))
3719 (push (cons (bibtex-current-line)
3720 "Entries out of order")
3721 error-list)))
3722 (push key key-list)
3723 (setq previous current)))
3724 (bibtex-progress-message 'done))
3726 ;; Check for duplicate keys in `bibtex-files'.
3727 ;; `bibtex-validate' only compares keys in current buffer with keys
3728 ;; in `bibtex-files'. `bibtex-validate-globally' compares keys for
3729 ;; each file in `bibtex-files' with keys of all other files in
3730 ;; `bibtex-files'.
3731 ;; We don't want to be fooled by outdated `bibtex-reference-keys'.
3732 (dolist (buffer (bibtex-initialize nil t))
3733 (dolist (key (with-current-buffer buffer bibtex-reference-keys))
3734 (when (and (cdr key)
3735 (cdr (assoc-string (car key) bibtex-reference-keys)))
3736 (bibtex-search-entry (car key))
3737 (push (cons (bibtex-current-line)
3738 (format "Duplicate key `%s' in %s" (car key)
3739 (abbreviate-file-name (buffer-file-name buffer))))
3740 error-list))))
3742 (when test-thoroughly
3743 (bibtex-progress-message
3744 "Checking required fields and month fields")
3745 (let ((bibtex-sort-ignore-string-entries t))
3746 (bibtex-map-entries
3747 (lambda (key beg end)
3748 (bibtex-progress-message)
3749 (let* ((entry-list (assoc-string (bibtex-type-in-head)
3750 bibtex-entry-field-alist t))
3751 (req (copy-sequence (elt (elt entry-list 1) 0)))
3752 (creq (copy-sequence (elt (elt entry-list 2) 0)))
3753 crossref-there bounds alt-there field)
3754 (bibtex-beginning-first-field beg)
3755 (while (setq bounds (bibtex-parse-field))
3756 (let ((field-name (bibtex-name-in-field bounds)))
3757 (if (and (bibtex-string= field-name "month")
3758 ;; Check only abbreviated month fields.
3759 (let ((month (bibtex-text-in-field-bounds bounds)))
3760 (not (or (string-match "\\`[\"{].+[\"}]\\'" month)
3761 (assoc-string
3762 month
3763 bibtex-predefined-month-strings t)))))
3764 (push (cons (bibtex-current-line)
3765 "Questionable month field")
3766 error-list))
3767 (setq field (assoc-string field-name req t)
3768 req (delete field req)
3769 creq (delete (assoc-string field-name creq t) creq))
3770 (if (nth 3 field)
3771 (if alt-there
3772 (push (cons (bibtex-current-line)
3773 "More than one non-empty alternative")
3774 error-list)
3775 (setq alt-there t)))
3776 (if (bibtex-string= field-name "crossref")
3777 (setq crossref-there t)))
3778 (goto-char (bibtex-end-of-field bounds)))
3779 (if crossref-there (setq req creq))
3780 (let (alt)
3781 (dolist (field req)
3782 (if (nth 3 field)
3783 (push (car field) alt)
3784 (push (cons (save-excursion (goto-char beg)
3785 (bibtex-current-line))
3786 (format "Required field `%s' missing"
3787 (car field)))
3788 error-list)))
3789 ;; The following fails if there are more than two
3790 ;; alternatives in a BibTeX entry, which isn't
3791 ;; the case momentarily.
3792 (if (cdr alt)
3793 (push (cons (save-excursion (goto-char beg)
3794 (bibtex-current-line))
3795 (format "Alternative fields `%s'/`%s' missing"
3796 (car alt) (cadr alt)))
3797 error-list)))))))
3798 (bibtex-progress-message 'done)))))
3800 (if error-list
3801 (let ((file (file-name-nondirectory (buffer-file-name)))
3802 (dir default-directory)
3803 (err-buf "*BibTeX validation errors*"))
3804 (setq error-list (sort error-list 'car-less-than-car))
3805 (with-current-buffer (get-buffer-create err-buf)
3806 (setq default-directory dir)
3807 (unless (eq major-mode 'compilation-mode) (compilation-mode))
3808 (toggle-read-only -1)
3809 (delete-region (point-min) (point-max))
3810 (insert "BibTeX mode command `bibtex-validate'\n"
3811 (if syntax-error
3812 "Maybe undetected errors due to syntax errors. Correct and validate again.\n"
3813 "\n"))
3814 (dolist (err error-list)
3815 (insert (format "%s:%d: %s\n" file (car err) (cdr err))))
3816 (set-buffer-modified-p nil)
3817 (toggle-read-only 1)
3818 (goto-line 3)) ; first error message
3819 (display-buffer err-buf)
3820 nil) ; return `nil' (i.e., buffer is invalid)
3821 (message "%s is syntactically correct"
3822 (if mark-active "Region" "Buffer"))
3823 t))) ; return `t' (i.e., buffer is valid)
3825 (defun bibtex-validate-globally (&optional strings)
3826 "Check for duplicate keys in `bibtex-files'.
3827 With optional prefix arg STRINGS, check for duplicate strings, too.
3828 Return t if test was successful, nil otherwise."
3829 (interactive "P")
3830 (let ((buffer-list (bibtex-initialize t))
3831 buffer-key-list current-buf current-keys error-list)
3832 ;; Check for duplicate keys within BibTeX buffer
3833 (dolist (buffer buffer-list)
3834 (save-excursion
3835 (set-buffer buffer)
3836 (let (entry-type key key-list)
3837 (goto-char (point-min))
3838 (while (re-search-forward bibtex-entry-head nil t)
3839 (setq entry-type (bibtex-type-in-head)
3840 key (bibtex-key-in-head))
3841 (if (or (and strings (bibtex-string= entry-type "string"))
3842 (assoc-string entry-type bibtex-entry-field-alist t))
3843 (if (member key key-list)
3844 (push (format "%s:%d: Duplicate key `%s'\n"
3845 (buffer-file-name)
3846 (bibtex-current-line) key)
3847 error-list)
3848 (push key key-list))))
3849 (push (cons buffer key-list) buffer-key-list))))
3851 ;; Check for duplicate keys among BibTeX buffers
3852 (while (setq current-buf (pop buffer-list))
3853 (setq current-keys (cdr (assq current-buf buffer-key-list)))
3854 (with-current-buffer current-buf
3855 (dolist (buffer buffer-list)
3856 (dolist (key (cdr (assq buffer buffer-key-list)))
3857 (when (assoc-string key current-keys)
3858 (bibtex-search-entry key)
3859 (push (format "%s:%d: Duplicate key `%s' in %s\n"
3860 (buffer-file-name) (bibtex-current-line) key
3861 (abbreviate-file-name (buffer-file-name buffer)))
3862 error-list))))))
3864 ;; Process error list
3865 (if error-list
3866 (let ((err-buf "*BibTeX validation errors*"))
3867 (with-current-buffer (get-buffer-create err-buf)
3868 (unless (eq major-mode 'compilation-mode) (compilation-mode))
3869 (toggle-read-only -1)
3870 (delete-region (point-min) (point-max))
3871 (insert "BibTeX mode command `bibtex-validate-globally'\n\n")
3872 (dolist (err (sort error-list 'string-lessp)) (insert err))
3873 (set-buffer-modified-p nil)
3874 (toggle-read-only 1)
3875 (goto-line 3)) ; first error message
3876 (display-buffer err-buf)
3877 nil) ; return `nil' (i.e., buffer is invalid)
3878 (message "No duplicate keys.")
3879 t))) ; return `t' (i.e., buffer is valid)
3881 (defun bibtex-next-field (begin &optional comma)
3882 "Move point to end of text of next BibTeX field or entry head.
3883 With prefix BEGIN non-nil, move point to its beginning. Optional arg COMMA
3884 is as in `bibtex-enclosing-field'. It is t for interactive calls."
3885 (interactive (list current-prefix-arg t))
3886 (let ((bounds (bibtex-find-text-internal t nil comma))
3887 end-of-entry)
3888 (if (not bounds)
3889 (setq end-of-entry t)
3890 (goto-char (nth 3 bounds))
3891 (if (assoc-string (car bounds) '("@String" "@Preamble") t)
3892 (setq end-of-entry t)
3893 ;; BibTeX key or field
3894 (if (looking-at ",[ \t\n]*") (goto-char (match-end 0)))
3895 ;; end of entry
3896 (if (looking-at "[)}][ \t\n]*") (setq end-of-entry t))))
3897 (if (and end-of-entry
3898 (re-search-forward bibtex-any-entry-maybe-empty-head nil t))
3899 (goto-char (match-beginning 0)))
3900 (bibtex-find-text begin nil bibtex-help-message)))
3902 (defun bibtex-find-text (&optional begin noerror help comma)
3903 "Move point to end of text of current BibTeX field or entry head.
3904 With optional prefix BEGIN non-nil, move point to its beginning.
3905 Unless NOERROR is non-nil, an error is signaled if point is not
3906 on a BibTeX field. If optional arg HELP is non-nil print help message.
3907 When called interactively, the value of HELP is `bibtex-help-message'.
3908 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
3909 interactive calls."
3910 (interactive (list current-prefix-arg nil bibtex-help-message t))
3911 (let ((bounds (bibtex-find-text-internal t nil comma)))
3912 (cond (bounds
3913 (if begin
3914 (progn (goto-char (nth 1 bounds))
3915 (if (looking-at "[{\"]")
3916 (forward-char)))
3917 (goto-char (nth 2 bounds))
3918 (if (memq (preceding-char) '(?} ?\"))
3919 (forward-char -1)))
3920 (if help (bibtex-print-help-message (car bounds))))
3921 ((not noerror) (error "Not on BibTeX field")))))
3923 (defun bibtex-find-text-internal (&optional noerror subfield comma)
3924 "Find text part of current BibTeX field or entry head.
3925 Return list (NAME START-TEXT END-TEXT END STRING-CONST) with field name
3926 or entry type, start and end of text, and end of field or entry head.
3927 STRING-CONST is a flag which is non-nil if current subfield delimited by #
3928 is a BibTeX string constant. Return value is nil if field or entry head
3929 are not found.
3930 If optional arg NOERROR is non-nil, an error message is suppressed
3931 if text is not found. If optional arg SUBFIELD is non-nil START-TEXT
3932 and END-TEXT correspond to the current subfield delimited by #.
3933 Optional arg COMMA is as in `bibtex-enclosing-field'."
3934 (save-excursion
3935 (let ((pnt (point))
3936 (bounds (bibtex-enclosing-field comma t))
3937 (case-fold-search t)
3938 name start-text end-text end failure done no-sub string-const)
3939 (bibtex-beginning-of-entry)
3940 (cond (bounds
3941 (setq name (bibtex-name-in-field bounds t)
3942 start-text (bibtex-start-of-text-in-field bounds)
3943 end-text (bibtex-end-of-text-in-field bounds)
3944 end (bibtex-end-of-field bounds)))
3945 ;; @String
3946 ((setq bounds (bibtex-parse-string t))
3947 (if (<= pnt (bibtex-end-of-string bounds))
3948 (setq name "@String" ;; not a field name!
3949 start-text (bibtex-start-of-text-in-string bounds)
3950 end-text (bibtex-end-of-text-in-string bounds)
3951 end (bibtex-end-of-string bounds))
3952 (setq failure t)))
3953 ;; @Preamble
3954 ((setq bounds (bibtex-parse-preamble))
3955 (if (<= pnt (bibtex-end-of-string bounds))
3956 (setq name "@Preamble" ;; not a field name!
3957 start-text (bibtex-start-of-text-in-string bounds)
3958 end-text (bibtex-end-of-text-in-string bounds)
3959 end (bibtex-end-of-string bounds))
3960 (setq failure t)))
3961 ;; BibTeX head
3962 ((looking-at bibtex-entry-maybe-empty-head)
3963 (goto-char (match-end 0))
3964 (if comma (save-match-data
3965 (re-search-forward "\\=[ \t\n]*," nil t)))
3966 (if (<= pnt (point))
3967 (setq name (match-string-no-properties bibtex-type-in-head)
3968 start-text (or (match-beginning bibtex-key-in-head)
3969 (match-end 0))
3970 end-text (or (match-end bibtex-key-in-head)
3971 (match-end 0))
3972 end end-text
3973 no-sub t) ; subfields do not make sense
3974 (setq failure t)))
3975 (t (setq failure t)))
3976 (when (and subfield (not failure))
3977 (setq failure no-sub)
3978 (unless failure
3979 (goto-char start-text)
3980 (while (not done)
3981 (if (or (prog1 (looking-at bibtex-field-const)
3982 (setq end-text (match-end 0)
3983 string-const t))
3984 (prog1 (setq bounds (bibtex-parse-field-string))
3985 (setq end-text (cdr bounds)
3986 string-const nil)))
3987 (progn
3988 (if (and (<= start-text pnt) (<= pnt end-text))
3989 (setq done t)
3990 (goto-char end-text))
3991 (if (looking-at "[ \t\n]*#[ \t\n]*")
3992 (setq start-text (goto-char (match-end 0)))))
3993 (setq done t failure t)))))
3994 (cond ((not failure)
3995 (list name start-text end-text end string-const))
3996 ((and no-sub (not noerror))
3997 (error "Not on text part of BibTeX field"))
3998 ((not noerror) (error "Not on BibTeX field"))))))
4000 (defun bibtex-remove-OPT-or-ALT (&optional comma)
4001 "Remove the string starting optional/alternative fields.
4002 Align text and go thereafter to end of text. Optional arg COMMA
4003 is as in `bibtex-enclosing-field'. It is t for interactive calls."
4004 (interactive (list t))
4005 (let ((case-fold-search t)
4006 (bounds (bibtex-enclosing-field comma)))
4007 (save-excursion
4008 (goto-char (bibtex-start-of-name-in-field bounds))
4009 (when (looking-at "OPT\\|ALT")
4010 (delete-region (match-beginning 0) (match-end 0))
4011 ;; make field non-OPT
4012 (search-forward "=")
4013 (forward-char -1)
4014 (delete-horizontal-space)
4015 (if bibtex-align-at-equal-sign
4016 (indent-to-column (- bibtex-text-indentation 2))
4017 (insert " "))
4018 (search-forward "=")
4019 (delete-horizontal-space)
4020 (if bibtex-align-at-equal-sign
4021 (insert " ")
4022 (indent-to-column bibtex-text-indentation))))))
4024 (defun bibtex-remove-delimiters (&optional comma)
4025 "Remove \"\" or {} around current BibTeX field text.
4026 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
4027 interactive calls."
4028 (interactive (list t))
4029 (let ((bounds (bibtex-find-text-internal nil t comma)))
4030 (unless (nth 4 bounds)
4031 (delete-region (1- (nth 2 bounds)) (nth 2 bounds))
4032 (delete-region (nth 1 bounds) (1+ (nth 1 bounds))))))
4034 (defun bibtex-kill-field (&optional copy-only comma)
4035 "Kill the entire enclosing BibTeX field.
4036 With prefix arg COPY-ONLY, copy the current field to `bibtex-field-kill-ring',
4037 but do not actually kill it. Optional arg COMMA is as in
4038 `bibtex-enclosing-field'. It is t for interactive calls."
4039 (interactive (list current-prefix-arg t))
4040 (save-excursion
4041 (let* ((case-fold-search t)
4042 (bounds (bibtex-enclosing-field comma))
4043 (end (bibtex-end-of-field bounds))
4044 (beg (bibtex-start-of-field bounds)))
4045 (goto-char end)
4046 (skip-chars-forward ",")
4047 (push (list (bibtex-name-in-field bounds) nil
4048 (bibtex-text-in-field-bounds bounds))
4049 bibtex-field-kill-ring)
4050 (if (> (length bibtex-field-kill-ring) bibtex-field-kill-ring-max)
4051 (setcdr (nthcdr (1- bibtex-field-kill-ring-max)
4052 bibtex-field-kill-ring)
4053 nil))
4054 (setq bibtex-field-kill-ring-yank-pointer bibtex-field-kill-ring)
4055 (unless copy-only
4056 (delete-region beg end))))
4057 (setq bibtex-last-kill-command 'field))
4059 (defun bibtex-copy-field-as-kill (&optional comma)
4060 "Copy the BibTeX field at point to the kill ring.
4061 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
4062 interactive calls."
4063 (interactive (list t))
4064 (bibtex-kill-field t comma))
4066 (defun bibtex-kill-entry (&optional copy-only)
4067 "Kill the entire enclosing BibTeX entry.
4068 With prefix arg COPY-ONLY, copy the current entry to `bibtex-entry-kill-ring',
4069 but do not actually kill it."
4070 (interactive "P")
4071 (save-excursion
4072 (let* ((case-fold-search t)
4073 (beg (bibtex-beginning-of-entry))
4074 (end (progn (bibtex-end-of-entry)
4075 (if (re-search-forward
4076 bibtex-any-entry-maybe-empty-head nil 'move)
4077 (goto-char (match-beginning 0)))
4078 (point))))
4079 (push (buffer-substring-no-properties beg end)
4080 bibtex-entry-kill-ring)
4081 (if (> (length bibtex-entry-kill-ring) bibtex-entry-kill-ring-max)
4082 (setcdr (nthcdr (1- bibtex-entry-kill-ring-max)
4083 bibtex-entry-kill-ring)
4084 nil))
4085 (setq bibtex-entry-kill-ring-yank-pointer bibtex-entry-kill-ring)
4086 (unless copy-only
4087 (delete-region beg end))))
4088 (setq bibtex-last-kill-command 'entry))
4090 (defun bibtex-copy-entry-as-kill ()
4091 "Copy the entire enclosing BibTeX entry to `bibtex-entry-kill-ring'."
4092 (interactive)
4093 (bibtex-kill-entry t))
4095 (defun bibtex-yank (&optional n)
4096 "Reinsert the last BibTeX item.
4097 More precisely, reinsert the field or entry killed or yanked most recently.
4098 With argument N, reinsert the Nth most recently killed BibTeX item.
4099 See also the command \\[bibtex-yank-pop]."
4100 (interactive "*p")
4101 (bibtex-insert-kill (1- n) t)
4102 (setq this-command 'bibtex-yank))
4104 (defun bibtex-yank-pop (n)
4105 "Replace just-yanked killed BibTeX item with a different item.
4106 This command is allowed only immediately after a `bibtex-yank' or a
4107 `bibtex-yank-pop'. In this case, the region contains a reinserted
4108 previously killed BibTeX item. `bibtex-yank-pop' deletes that item
4109 and inserts in its place a different killed BibTeX item.
4111 With no argument, the previous kill is inserted.
4112 With argument N, insert the Nth previous kill.
4113 If N is negative, this is a more recent kill.
4115 The sequence of kills wraps around, so that after the oldest one
4116 comes the newest one."
4117 (interactive "*p")
4118 (unless (eq last-command 'bibtex-yank)
4119 (error "Previous command was not a BibTeX yank"))
4120 (setq this-command 'bibtex-yank)
4121 (let ((inhibit-read-only t))
4122 (delete-region (point) (mark t))
4123 (bibtex-insert-kill n t)))
4125 (defun bibtex-empty-field (&optional comma)
4126 "Delete the text part of the current field, replace with empty text.
4127 Optional arg COMMA is as in `bibtex-enclosing-field'. It is t for
4128 interactive calls."
4129 (interactive (list t))
4130 (let ((bounds (bibtex-enclosing-field comma)))
4131 (goto-char (bibtex-start-of-text-in-field bounds))
4132 (delete-region (point) (bibtex-end-of-text-in-field bounds))
4133 (insert (bibtex-field-left-delimiter)
4134 (bibtex-field-right-delimiter))
4135 (bibtex-find-text t nil bibtex-help-message)))
4137 (defun bibtex-pop-previous (arg)
4138 "Replace text of current field with the similar field in previous entry.
4139 With arg, goes up ARG entries. Repeated, goes up so many times. May be
4140 intermixed with \\[bibtex-pop-next] (bibtex-pop-next)."
4141 (interactive "p")
4142 (bibtex-pop arg 'previous))
4144 (defun bibtex-pop-next (arg)
4145 "Replace text of current field with the text of similar field in next entry.
4146 With arg, goes down ARG entries. Repeated, goes down so many times. May be
4147 intermixed with \\[bibtex-pop-previous] (bibtex-pop-previous)."
4148 (interactive "p")
4149 (bibtex-pop arg 'next))
4151 (defun bibtex-clean-entry (&optional new-key called-by-reformat)
4152 "Finish editing the current BibTeX entry and clean it up.
4153 Check that no required fields are empty and formats entry dependent
4154 on the value of `bibtex-entry-format'.
4155 If the reference key of the entry is empty or a prefix argument is given,
4156 calculate a new reference key. (Note: this works only if fields in entry
4157 begin on separate lines prior to calling `bibtex-clean-entry' or if
4158 'realign is contained in `bibtex-entry-format'.)
4159 Don't call `bibtex-clean-entry' on @Preamble entries.
4160 At end of the cleaning process, the functions in
4161 `bibtex-clean-entry-hook' are called with region narrowed to entry."
4162 ;; Opt. arg CALLED-BY-REFORMAT is t if `bibtex-clean-entry'
4163 ;; is called by `bibtex-reformat'
4164 (interactive "P")
4165 (let ((case-fold-search t)
4166 (start (bibtex-beginning-of-entry))
4167 (_ (or (looking-at bibtex-any-entry-maybe-empty-head)
4168 (error "Not inside a BibTeX entry")))
4169 (entry-type (bibtex-type-in-head))
4170 (key (bibtex-key-in-head)))
4171 (cond ((bibtex-string= entry-type "preamble")
4172 ;; (bibtex-format-preamble)
4173 (error "No clean up of @Preamble entries"))
4174 ((bibtex-string= entry-type "string")
4175 (setq entry-type 'string))
4176 ;; (bibtex-format-string)
4177 (t (bibtex-format-entry)))
4178 ;; set key
4179 (when (or new-key (not key))
4180 (setq key (bibtex-generate-autokey))
4181 ;; Sometimes `bibtex-generate-autokey' returns an empty string
4182 (if (or bibtex-autokey-edit-before-use (string= "" key))
4183 (setq key (if (eq entry-type 'string)
4184 (bibtex-read-string-key key)
4185 (bibtex-read-key "Key to use: " key))))
4186 (save-excursion
4187 (re-search-forward (if (eq entry-type 'string)
4188 bibtex-string-maybe-empty-head
4189 bibtex-entry-maybe-empty-head))
4190 (if (match-beginning bibtex-key-in-head)
4191 (delete-region (match-beginning bibtex-key-in-head)
4192 (match-end bibtex-key-in-head)))
4193 (insert key)))
4195 (unless called-by-reformat
4196 (let* ((end (save-excursion
4197 (bibtex-end-of-entry)
4198 (if (re-search-forward
4199 bibtex-entry-maybe-empty-head nil 'move)
4200 (goto-char (match-beginning 0)))
4201 (point)))
4202 (entry (buffer-substring start end))
4203 ;; include the crossref key in index
4204 (index (let ((bibtex-maintain-sorted-entries 'crossref))
4205 (bibtex-entry-index))) ; moves point to end of head
4206 error)
4207 ;; sorting
4208 (if (and bibtex-maintain-sorted-entries
4209 (not (and bibtex-sort-ignore-string-entries
4210 (eq entry-type 'string))))
4211 (progn
4212 (delete-region start end)
4213 (setq error (not (bibtex-prepare-new-entry index))
4214 start (point)) ; update start
4215 (save-excursion (insert entry)))
4216 (bibtex-search-entry key)
4217 (setq error (or (/= (point) start)
4218 (bibtex-search-entry key nil end))))
4219 (if error
4220 (error "New inserted entry yields duplicate key"))
4221 (dolist (buffer (bibtex-initialize))
4222 (with-current-buffer buffer
4223 (if (cdr (assoc-string key bibtex-reference-keys))
4224 (error "Duplicate key in %s" (buffer-file-name)))))
4226 ;; Only update the list of keys if it has been built already.
4227 (cond ((eq entry-type 'string)
4228 (if (and (listp bibtex-strings)
4229 (not (assoc key bibtex-strings)))
4230 (push (cons key (bibtex-text-in-string
4231 (bibtex-parse-string) t))
4232 bibtex-strings)))
4233 ;; We have a normal entry.
4234 ((listp bibtex-reference-keys)
4235 (cond ((not (assoc key bibtex-reference-keys))
4236 (push (cons key t) bibtex-reference-keys))
4237 ((not (cdr (assoc key bibtex-reference-keys)))
4238 ;; Turn a crossref key into a header key
4239 (setq bibtex-reference-keys
4240 (cons (cons key t)
4241 (delete (list key) bibtex-reference-keys)))))
4242 ;; Handle crossref key.
4243 (if (and (nth 1 index)
4244 (not (assoc (nth 1 index) bibtex-reference-keys)))
4245 (push (list (nth 1 index)) bibtex-reference-keys)))))
4247 ;; final clean up
4248 (if bibtex-clean-entry-hook
4249 (save-excursion
4250 (save-restriction
4251 (bibtex-narrow-to-entry)
4252 (run-hooks 'bibtex-clean-entry-hook)))))))
4254 (defun bibtex-fill-field-bounds (bounds justify &optional move)
4255 "Fill BibTeX field delimited by BOUNDS.
4256 If JUSTIFY is non-nil justify as well.
4257 If optional arg MOVE is non-nil move point to end of field."
4258 (let ((end-field (copy-marker (bibtex-end-of-field bounds))))
4259 (if (not justify)
4260 (goto-char (bibtex-start-of-text-in-field bounds))
4261 (goto-char (bibtex-start-of-field bounds))
4262 (forward-char) ; leading comma
4263 (bibtex-delete-whitespace)
4264 (open-line 1)
4265 (forward-char)
4266 (indent-to-column (+ bibtex-entry-offset
4267 bibtex-field-indentation))
4268 (re-search-forward "[ \t\n]*=" end-field)
4269 (replace-match "=")
4270 (forward-char -1)
4271 (if bibtex-align-at-equal-sign
4272 (indent-to-column
4273 (+ bibtex-entry-offset (- bibtex-text-indentation 2)))
4274 (insert " "))
4275 (forward-char)
4276 (bibtex-delete-whitespace)
4277 (if bibtex-align-at-equal-sign
4278 (insert " ")
4279 (indent-to-column bibtex-text-indentation)))
4280 ;; Paragraphs within fields are not preserved. Bother?
4281 (fill-region-as-paragraph (line-beginning-position) end-field
4282 default-justification nil (point))
4283 (if move (goto-char end-field))))
4285 (defun bibtex-fill-field (&optional justify)
4286 "Like \\[fill-paragraph], but fill current BibTeX field.
4287 If optional prefix JUSTIFY is non-nil justify as well.
4288 In BibTeX mode this function is bound to `fill-paragraph-function'."
4289 (interactive "*P")
4290 (let ((pnt (copy-marker (point)))
4291 (bounds (bibtex-enclosing-field t)))
4292 (bibtex-fill-field-bounds bounds justify)
4293 (goto-char pnt)))
4295 (defun bibtex-fill-entry ()
4296 "Fill current BibTeX entry.
4297 Realign entry, so that every field starts on a separate line. Field
4298 names appear in column `bibtex-field-indentation', field text starts in
4299 column `bibtex-text-indentation' and continuation lines start here, too.
4300 If `bibtex-align-at-equal-sign' is non-nil, align equal signs, too."
4301 (interactive "*")
4302 (let ((pnt (copy-marker (point)))
4303 (end (copy-marker (bibtex-end-of-entry)))
4304 (beg (bibtex-beginning-of-entry)) ; move point
4305 bounds)
4306 (bibtex-delete-whitespace)
4307 (indent-to-column bibtex-entry-offset)
4308 (bibtex-beginning-first-field beg)
4309 (while (setq bounds (bibtex-parse-field))
4310 (bibtex-fill-field-bounds bounds t t))
4311 (if (looking-at ",")
4312 (forward-char))
4313 (skip-chars-backward " \t\n")
4314 (bibtex-delete-whitespace)
4315 (open-line 1)
4316 (forward-char)
4317 (indent-to-column bibtex-entry-offset)
4318 (goto-char pnt)))
4320 (defun bibtex-realign ()
4321 "Realign BibTeX entries such that they are separated by one blank line."
4322 (goto-char (point-min))
4323 (let ((case-fold-search t)
4324 (entry-type (concat "[ \t\n]*\\(" bibtex-entry-type "\\)")))
4325 ;; No blank lines prior to the first entry if there no
4326 ;; non-white characters in front of it.
4327 (when (looking-at entry-type)
4328 (replace-match "\\1"))
4329 ;; Entries are separated by one blank line.
4330 (while (re-search-forward entry-type nil t)
4331 (replace-match "\n\n\\1"))
4332 ;; One blank line past the last entry if it is followed by
4333 ;; non-white characters, no blank line otherwise.
4334 (beginning-of-line)
4335 (when (re-search-forward bibtex-entry-type nil t)
4336 (bibtex-end-of-entry)
4337 (bibtex-delete-whitespace)
4338 (open-line (if (eobp) 1 2)))))
4340 (defun bibtex-reformat (&optional read-options)
4341 "Reformat all BibTeX entries in buffer or region.
4342 Without prefix argument, reformatting is based on `bibtex-entry-format'.
4343 With prefix argument, read options for reformatting from minibuffer.
4344 With \\[universal-argument] \\[universal-argument] prefix argument, reuse previous answers (if any) again.
4345 If mark is active reformat entries in region, if not in whole buffer."
4346 (interactive "*P")
4347 (let* ((pnt (point))
4348 (use-previous-options
4349 (and (equal (prefix-numeric-value read-options) 16)
4350 (or bibtex-reformat-previous-options
4351 bibtex-reformat-previous-reference-keys)))
4352 (bibtex-entry-format
4353 (cond (read-options
4354 (if use-previous-options
4355 bibtex-reformat-previous-options
4356 (setq bibtex-reformat-previous-options
4357 (mapcar (lambda (option)
4358 (if (y-or-n-p (car option)) (cdr option)))
4359 `(("Realign entries (recommended)? " . 'realign)
4360 ("Remove empty optional and alternative fields? " . 'opts-or-alts)
4361 ("Remove delimiters around pure numerical fields? " . 'numerical-fields)
4362 (,(concat (if bibtex-comma-after-last-field "Insert" "Remove")
4363 " comma at end of entry? ") . 'last-comma)
4364 ("Replace double page dashes by single ones? " . 'page-dashes)
4365 ("Delete whitespace at the beginning and end of fields? " . 'whitespace)
4366 ("Inherit booktitle? " . 'inherit-booktitle)
4367 ("Force delimiters? " . 'delimiters)
4368 ("Unify case of entry types and field names? " . 'unify-case)
4369 ("Enclose parts of field entries by braces? " . 'braces)
4370 ("Replace parts of field entries by string constants? " . 'strings))))))
4371 ;; Do not include required-fields because `bibtex-reformat'
4372 ;; cannot handle the error messages of `bibtex-format-entry'.
4373 ;; Use `bibtex-validate' to check for required fields.
4374 ((eq t bibtex-entry-format)
4375 '(realign opts-or-alts numerical-fields delimiters
4376 last-comma page-dashes unify-case inherit-booktitle
4377 whitespace braces strings))
4379 (remove 'required-fields (push 'realign bibtex-entry-format)))))
4380 (reformat-reference-keys
4381 (if read-options
4382 (if use-previous-options
4383 bibtex-reformat-previous-reference-keys
4384 (setq bibtex-reformat-previous-reference-keys
4385 (y-or-n-p "Generate new reference keys automatically? ")))))
4386 (bibtex-sort-ignore-string-entries t)
4387 bibtex-autokey-edit-before-use)
4389 (save-restriction
4390 (if mark-active (narrow-to-region (region-beginning) (region-end)))
4391 (if (memq 'realign bibtex-entry-format)
4392 (bibtex-realign))
4393 (bibtex-progress-message "Formatting" 1)
4394 (bibtex-map-entries (lambda (key beg end)
4395 (bibtex-progress-message)
4396 (bibtex-clean-entry reformat-reference-keys t)))
4397 (bibtex-progress-message 'done))
4398 (when reformat-reference-keys
4399 (kill-local-variable 'bibtex-reference-keys)
4400 (when bibtex-maintain-sorted-entries
4401 (bibtex-progress-message "Sorting" 1)
4402 (bibtex-sort-buffer)
4403 (bibtex-progress-message 'done)))
4404 (goto-char pnt)))
4406 (defun bibtex-convert-alien (&optional read-options)
4407 "Make an alien BibTeX buffer fully usable by BibTeX mode.
4408 If a file does not conform with all standards used by BibTeX mode,
4409 some of the high-level features of BibTeX mode are not available.
4410 This function tries to convert current buffer to conform with these standards.
4411 With prefix argument READ-OPTIONS non-nil, read options for reformatting
4412 entries from minibuffer."
4413 (interactive "*P")
4414 (message "Starting to validate buffer...")
4415 (sit-for 1)
4416 (bibtex-realign)
4417 (deactivate-mark) ; So `bibtex-validate' works on the whole buffer.
4418 (if (not (let (bibtex-maintain-sorted-entries)
4419 (bibtex-validate)))
4420 (message "Correct errors and call `bibtex-convert-alien' again")
4421 (message "Starting to reformat entries...")
4422 (sit-for 2)
4423 (bibtex-reformat read-options)
4424 (goto-char (point-max))
4425 (message "Buffer is now parsable. Please save it.")))
4427 (defun bibtex-complete ()
4428 "Complete word fragment before point according to context.
4429 If point is inside key or crossref field perform key completion based on
4430 `bibtex-reference-keys'. Inside a month field perform key completion
4431 based on `bibtex-predefined-month-strings'. Inside any other field
4432 \(including a String or Preamble definition) perform string completion
4433 based on `bibtex-strings'.
4434 An error is signaled if point is outside key or BibTeX field."
4435 (interactive)
4436 (let ((pnt (point))
4437 (case-fold-search t)
4438 bounds name compl)
4439 (save-excursion
4440 (if (and (setq bounds (bibtex-enclosing-field nil t))
4441 (>= pnt (bibtex-start-of-text-in-field bounds))
4442 (<= pnt (bibtex-end-of-text-in-field bounds)))
4443 (setq name (bibtex-name-in-field bounds t)
4444 compl (cond ((bibtex-string= name "crossref")
4445 ;; point is in crossref field
4446 'crossref-key)
4447 ((bibtex-string= name "month")
4448 ;; point is in month field
4449 bibtex-predefined-month-strings)
4450 ;; point is in other field
4451 (t (bibtex-strings))))
4452 (bibtex-beginning-of-entry)
4453 (cond ((setq bounds (bibtex-parse-string t))
4454 ;; point is inside a @String key
4455 (cond ((and (>= pnt (nth 1 (car bounds)))
4456 (<= pnt (nth 2 (car bounds))))
4457 (setq compl 'string))
4458 ;; point is inside a @String field
4459 ((and (>= pnt (bibtex-start-of-text-in-string bounds))
4460 (<= pnt (bibtex-end-of-text-in-string bounds)))
4461 (setq compl (bibtex-strings)))))
4462 ;; point is inside a @Preamble field
4463 ((setq bounds (bibtex-parse-preamble))
4464 (if (and (>= pnt (bibtex-start-of-text-in-string bounds))
4465 (<= pnt (bibtex-end-of-text-in-string bounds)))
4466 (setq compl (bibtex-strings))))
4467 ((and (looking-at bibtex-entry-maybe-empty-head)
4468 ;; point is inside a key
4469 (or (and (match-beginning bibtex-key-in-head)
4470 (>= pnt (match-beginning bibtex-key-in-head))
4471 (<= pnt (match-end bibtex-key-in-head)))
4472 ;; or point is on empty key
4473 (and (not (match-beginning bibtex-key-in-head))
4474 (= pnt (match-end 0)))))
4475 (setq compl 'key)))))
4477 (cond ((eq compl 'key)
4478 ;; key completion: no cleanup needed
4479 (setq choose-completion-string-functions nil)
4480 (let (completion-ignore-case)
4481 (bibtex-complete-internal (bibtex-global-key-alist))))
4483 ((eq compl 'crossref-key)
4484 ;; crossref key completion
4486 ;; If we quit the *Completions* buffer without requesting
4487 ;; a completion, `choose-completion-string-functions' is still
4488 ;; non-nil. Therefore, `choose-completion-string-functions' is
4489 ;; always set (either to non-nil or nil) when a new completion
4490 ;; is requested.
4491 (let (completion-ignore-case)
4492 (setq choose-completion-string-functions
4493 (lambda (choice buffer mini-p base-size)
4494 (setq choose-completion-string-functions nil)
4495 (choose-completion-string choice buffer base-size)
4496 (bibtex-complete-crossref-cleanup choice)
4497 t)) ; needed by choose-completion-string-functions
4498 (bibtex-complete-crossref-cleanup
4499 (bibtex-complete-internal (bibtex-global-key-alist)))))
4501 ((eq compl 'string)
4502 ;; string key completion: no cleanup needed
4503 (setq choose-completion-string-functions nil)
4504 (let ((completion-ignore-case t))
4505 (bibtex-complete-internal bibtex-strings)))
4507 (compl
4508 ;; string completion
4509 (let ((completion-ignore-case t))
4510 (setq choose-completion-string-functions
4511 `(lambda (choice buffer mini-p base-size)
4512 (setq choose-completion-string-functions nil)
4513 (choose-completion-string choice buffer base-size)
4514 (bibtex-complete-string-cleanup choice ',compl)
4515 t)) ; needed by `choose-completion-string-functions'
4516 (bibtex-complete-string-cleanup (bibtex-complete-internal compl)
4517 compl)))
4519 (t (setq choose-completion-string-functions nil)
4520 (error "Point outside key or BibTeX field")))))
4522 (defun bibtex-Article ()
4523 "Insert a new BibTeX @Article entry; see also `bibtex-entry'."
4524 (interactive "*")
4525 (bibtex-entry "Article"))
4527 (defun bibtex-Book ()
4528 "Insert a new BibTeX @Book entry; see also `bibtex-entry'."
4529 (interactive "*")
4530 (bibtex-entry "Book"))
4532 (defun bibtex-Booklet ()
4533 "Insert a new BibTeX @Booklet entry; see also `bibtex-entry'."
4534 (interactive "*")
4535 (bibtex-entry "Booklet"))
4537 (defun bibtex-InBook ()
4538 "Insert a new BibTeX @InBook entry; see also `bibtex-entry'."
4539 (interactive "*")
4540 (bibtex-entry "InBook"))
4542 (defun bibtex-InCollection ()
4543 "Insert a new BibTeX @InCollection entry; see also `bibtex-entry'."
4544 (interactive "*")
4545 (bibtex-entry "InCollection"))
4547 (defun bibtex-InProceedings ()
4548 "Insert a new BibTeX @InProceedings entry; see also `bibtex-entry'."
4549 (interactive "*")
4550 (bibtex-entry "InProceedings"))
4552 (defun bibtex-Manual ()
4553 "Insert a new BibTeX @Manual entry; see also `bibtex-entry'."
4554 (interactive "*")
4555 (bibtex-entry "Manual"))
4557 (defun bibtex-MastersThesis ()
4558 "Insert a new BibTeX @MastersThesis entry; see also `bibtex-entry'."
4559 (interactive "*")
4560 (bibtex-entry "MastersThesis"))
4562 (defun bibtex-Misc ()
4563 "Insert a new BibTeX @Misc entry; see also `bibtex-entry'."
4564 (interactive "*")
4565 (bibtex-entry "Misc"))
4567 (defun bibtex-PhdThesis ()
4568 "Insert a new BibTeX @PhdThesis entry; see also `bibtex-entry'."
4569 (interactive "*")
4570 (bibtex-entry "PhdThesis"))
4572 (defun bibtex-Proceedings ()
4573 "Insert a new BibTeX @Proceedings entry; see also `bibtex-entry'."
4574 (interactive "*")
4575 (bibtex-entry "Proceedings"))
4577 (defun bibtex-TechReport ()
4578 "Insert a new BibTeX @TechReport entry; see also `bibtex-entry'."
4579 (interactive "*")
4580 (bibtex-entry "TechReport"))
4582 (defun bibtex-Unpublished ()
4583 "Insert a new BibTeX @Unpublished entry; see also `bibtex-entry'."
4584 (interactive "*")
4585 (bibtex-entry "Unpublished"))
4587 (defun bibtex-String (&optional key)
4588 "Insert a new BibTeX @String entry with key KEY."
4589 (interactive (list (bibtex-read-string-key)))
4590 (let ((bibtex-maintain-sorted-entries
4591 (unless bibtex-sort-ignore-string-entries
4592 bibtex-maintain-sorted-entries))
4593 endpos)
4594 (unless (bibtex-prepare-new-entry (list key nil "String"))
4595 (error "Entry with key `%s' already exists" key))
4596 (if (zerop (length key)) (setq key nil))
4597 (indent-to-column bibtex-entry-offset)
4598 (insert "@String"
4599 (bibtex-entry-left-delimiter))
4600 (if key
4601 (insert key)
4602 (setq endpos (point)))
4603 (insert " = "
4604 (bibtex-field-left-delimiter))
4605 (if key
4606 (setq endpos (point)))
4607 (insert (bibtex-field-right-delimiter)
4608 (bibtex-entry-right-delimiter)
4609 "\n")
4610 (goto-char endpos)))
4612 (defun bibtex-Preamble ()
4613 "Insert a new BibTeX @Preamble entry."
4614 (interactive "*")
4615 (bibtex-move-outside-of-entry)
4616 (indent-to-column bibtex-entry-offset)
4617 (insert "@Preamble"
4618 (bibtex-entry-left-delimiter)
4619 (bibtex-field-left-delimiter))
4620 (let ((endpos (point)))
4621 (insert (bibtex-field-right-delimiter)
4622 (bibtex-entry-right-delimiter)
4623 "\n")
4624 (goto-char endpos)))
4626 (defun bibtex-url (&optional pos no-browse)
4627 "Browse a URL for the BibTeX entry at point.
4628 Optional POS is the location of the BibTeX entry.
4629 The URL is generated using the schemes defined in `bibtex-generate-url-list'
4630 \(see there\). If multiple schemes match for this entry, or the same scheme
4631 matches more than once, use the one for which the first step's match is the
4632 closest to POS. The URL is passed to `browse-url' unless NO-BROWSE is t.
4633 Return the URL or nil if none can be generated."
4634 (interactive)
4635 (unless pos (setq pos (point)))
4636 (save-excursion
4637 (goto-char pos)
4638 (bibtex-beginning-of-entry)
4639 (let ((end (save-excursion (bibtex-end-of-entry)))
4640 (fields-alist (save-excursion (bibtex-parse-entry t)))
4641 ;; Always ignore case,
4642 (case-fold-search t)
4643 text url scheme obj fmt fl-match step)
4644 ;; The return value of `bibtex-parse-entry' (i.e., FIELDS-ALIST)
4645 ;; is always used to generate the URL. However, if the BibTeX
4646 ;; entry contains more than one URL, we have multiple matches
4647 ;; for the first step defining the generation of the URL.
4648 ;; Therefore, we try to initiate the generation of the URL
4649 ;; based on the match of `bibtex-font-lock-url' that is the
4650 ;; closest to POS. If that fails (no match found) we try to
4651 ;; initiate the generation of the URL based on the properly
4652 ;; concatenated CONTENT of the field as returned by
4653 ;; `bibtex-text-in-field-bounds'. The latter approach can
4654 ;; differ from the former because `bibtex-font-lock-url' uses
4655 ;; the buffer itself.
4656 (while (bibtex-font-lock-url end t)
4657 (push (list (bibtex-dist pos (match-beginning 0) (match-end 0))
4658 (match-beginning 0)
4659 (buffer-substring-no-properties
4660 (match-beginning 0) (match-end 0)))
4661 fl-match)
4662 ;; `bibtex-font-lock-url' moves point to end of match.
4663 (forward-char))
4664 (when fl-match
4665 (setq fl-match (car (sort fl-match (lambda (x y) (< (car x) (car y))))))
4666 (goto-char (nth 1 fl-match))
4667 (bibtex-beginning-of-field) (re-search-backward ",")
4668 (let* ((bounds (bibtex-parse-field))
4669 (name (bibtex-name-in-field bounds))
4670 (content (bibtex-text-in-field-bounds bounds t))
4671 (lst bibtex-generate-url-list))
4672 ;; This match can fail when CONTENT differs from text in buffer.
4673 (when (string-match (regexp-quote (nth 2 fl-match)) content)
4674 ;; TEXT is the part of CONTENT that starts with the match
4675 ;; of `bibtex-font-lock-url' we are looking for.
4676 (setq text (substring content (match-beginning 0)))
4677 (while (and (not url) (setq scheme (pop lst)))
4678 ;; Verify the match of `bibtex-font-lock-url' by
4679 ;; comparing with TEXT.
4680 (when (and (bibtex-string= (caar scheme) name)
4681 (string-match (cdar scheme) text))
4682 (setq url t scheme (cdr scheme)))))))
4684 ;; If the match of `bibtex-font-lock-url' was not approved
4685 ;; parse FIELDS-ALIST, i.e., the output of `bibtex-parse-entry'.
4686 (unless url
4687 (let ((lst bibtex-generate-url-list))
4688 (while (and (not url) (setq scheme (pop lst)))
4689 (when (and (setq text (cdr (assoc-string (caar scheme)
4690 fields-alist t)))
4691 (string-match (cdar scheme) text))
4692 (setq url t scheme (cdr scheme))))))
4694 (when url
4695 (setq url (if (null scheme) (match-string 0 text)
4696 (if (stringp (car scheme))
4697 (setq fmt (pop scheme)))
4698 (dotimes (i (length scheme))
4699 (setq step (nth i scheme))
4700 ;; The first step shall use TEXT as obtained earlier.
4701 (unless (= i 0)
4702 (setq text (cdr (assoc-string (car step) fields-alist t))))
4703 (if (string-match (nth 1 step) text)
4704 (push (cond ((functionp (nth 2 step))
4705 (funcall (nth 2 step) text))
4706 ((numberp (nth 2 step))
4707 (match-string (nth 2 step) text))
4709 (replace-match (nth 2 step) t nil text)))
4710 obj)
4711 ;; If SCHEME is set up correctly,
4712 ;; we should never reach this point
4713 (error "Match failed: %s" text)))
4714 (if fmt (apply 'format fmt (nreverse obj))
4715 (apply 'concat (nreverse obj)))))
4716 (if (interactive-p) (message "%s" url))
4717 (unless no-browse (browse-url url)))
4718 (if (and (not url) (interactive-p)) (message "No URL known."))
4719 url)))
4722 ;; Make BibTeX a Feature
4724 (provide 'bibtex)
4726 ;; arch-tag: ee2be3af-caad-427f-b42a-d20fad630d04
4727 ;;; bibtex.el ends here