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