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