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