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