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