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