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