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