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