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