* etc/publicsuffix.txt: Update from source.
[bpt/emacs.git] / lisp / org / org-bibtex.el
CommitLineData
20908596
CD
1;;; org-bibtex.el --- Org links to BibTeX entries
2;;
ba318903 3;; Copyright (C) 2007-2014 Free Software Foundation, Inc.
20908596 4;;
271672fa 5;; Authors: Bastien Guerry <bzg@gnu.org>
dfd98937
BG
6;; Carsten Dominik <carsten dot dominik at gmail dot com>
7;; Eric Schulte <schulte dot eric at gmail dot com>
271672fa 8;; Keywords: org, wp, capture
20908596
CD
9;;
10;; This file is part of GNU Emacs.
11;;
b1fc2b50 12;; GNU Emacs is free software: you can redistribute it and/or modify
20908596 13;; it under the terms of the GNU General Public License as published by
b1fc2b50
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
20908596
CD
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
b1fc2b50 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
20908596
CD
24;;
25;;; Commentary:
26;;
27;; This file implements links to database entries in BibTeX files.
28;; Instead of defining a special link prefix, it uses the normal file
29;; links combined with a custom search mechanism to find entries
33306645 30;; by reference key. And it constructs a nice description tag for
20908596
CD
31;; the link that contains the author name, the year and a short title.
32;;
33;; It also stores detailed information about the entry so that
271672fa 34;; capture templates can access and enter this information easily.
20908596
CD
35;;
36;; The available properties for each entry are listed here:
37;;
38;; :author :publisher :volume :pages
39;; :editor :url :number :journal
40;; :title :year :series :address
41;; :booktitle :month :annote :abstract
42;; :key :btype
43;;
271672fa 44;; Here is an example of a capture template that use some of this
20908596
CD
45;; information (:author :year :title :journal :pages):
46;;
d1389828 47;; (setq org-capture-templates
20908596
CD
48;; '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n \
49;; In %:journal, %:pages.")))
50;;
271672fa 51;; Let's say you want to capture this BibTeX entry:
20908596
CD
52;;
53;; @Article{dolev83,
54;; author = {Danny Dolev and Andrew C. Yao},
55;; title = {On the security of public-key protocols},
56;; journal = {IEEE Transaction on Information Theory},
57;; year = 1983,
58;; volume = 2,
59;; number = 29,
60;; pages = {198--208},
61;; month = {Mars}
62;; }
63;;
271672fa 64;; M-x `org-capture' on this entry will produce this buffer:
20908596
CD
65;;
66;; =====================================================================
67;; * READ <== [point here]
68;;
3ab2c837 69;; [[file:file.bib::dolev83][Dolev & Yao 1983: security of public key protocols]]
20908596
CD
70;;
71;; Danny Dolev and Andrew C. Yao (1983): On the security of public-key protocols
72;; In IEEE Transaction on Information Theory, 198--208.
73;; =====================================================================
74;;
3ab2c837
BG
75;; Additionally, the following functions are now available for storing
76;; bibtex entries within Org-mode documents.
77;;
78;; - Run `org-bibtex' to export the current file to a .bib.
79;;
80;; - Run `org-bibtex-check' or `org-bibtex-check-all' to check and
81;; fill in missing field of either the current, or all headlines
82;;
83;; - Run `org-bibtex-create' to add a bibtex entry
84;;
85;; - Use `org-bibtex-read' to read a bibtex entry after `point' or in
86;; the active region, then call `org-bibtex-write' in a .org file to
87;; insert a heading for the read bibtex entry
88;;
89;; - All Bibtex information is taken from the document compiled by
90;; Andrew Roberts from the Bibtex manual, available at
63aa0982 91;; http://www.andy-roberts.net/res/writing/latex/bibentries.pdf
3ab2c837 92;;
20908596
CD
93;;; History:
94;;
95;; The link creation part has been part of Org-mode for a long time.
96;;
271672fa 97;; Creating better capture template information was inspired by a request
20908596 98;; of Austin Frank: http://article.gmane.org/gmane.emacs.orgmode/4112
8bfe682a 99;; and then implemented by Bastien Guerry.
20908596 100;;
3ab2c837
BG
101;; Eric Schulte eventually added the functions for translating between
102;; Org-mode headlines and Bibtex entries, and for fleshing out the Bibtex
103;; fields of existing Org-mode headlines.
104;;
20908596
CD
105;; Org-mode loads this module by default - if this is not what you want,
106;; configure the variable `org-modules'.
107
108;;; Code:
109
110(require 'org)
3ab2c837
BG
111(require 'bibtex)
112(eval-when-compile
113 (require 'cl))
8223b1d2 114(require 'org-compat)
20908596 115
153ae947 116(defvar org-bibtex-description nil) ; dynamically scoped from org.el
3ab2c837 117(defvar org-id-locations)
20908596
CD
118
119(declare-function bibtex-beginning-of-entry "bibtex" ())
120(declare-function bibtex-generate-autokey "bibtex" ())
121(declare-function bibtex-parse-entry "bibtex" (&optional content))
122(declare-function bibtex-url "bibtex" (&optional pos no-browse))
3ab2c837
BG
123(declare-function org-babel-trim "ob" (string &optional regexp))
124
125\f
126;;; Bibtex data
127(defvar org-bibtex-types
128 '((:article
129 (:description . "An article from a journal or magazine")
130 (:required :author :title :journal :year)
131 (:optional :volume :number :pages :month :note))
132 (:book
133 (:description . "A book with an explicit publisher")
134 (:required (:editor :author) :title :publisher :year)
135 (:optional (:volume :number) :series :address :edition :month :note))
136 (:booklet
137 (:description . "A work that is printed and bound, but without a named publisher or sponsoring institution.")
138 (:required :title)
139 (:optional :author :howpublished :address :month :year :note))
140 (:conference
141 (:description . "")
142 (:required :author :title :booktitle :year)
143 (:optional :editor :pages :organization :publisher :address :month :note))
144 (:inbook
145 (:description . "A part of a book, which may be a chapter (or section or whatever) and/or a range of pages.")
146 (:required (:author :editor) :title (:chapter :pages) :publisher :year)
147 (:optional :crossref (:volume :number) :series :type :address :edition :month :note))
148 (:incollection
149 (:description . "A part of a book having its own title.")
150 (:required :author :title :booktitle :publisher :year)
151 (:optional :crossref :editor (:volume :number) :series :type :chapter :pages :address :edition :month :note))
152 (:inproceedings
153 (:description . "An article in a conference proceedings")
154 (:required :author :title :booktitle :year)
155 (:optional :crossref :editor (:volume :number) :series :pages :address :month :organization :publisher :note))
156 (:manual
157 (:description . "Technical documentation.")
158 (:required :title)
159 (:optional :author :organization :address :edition :month :year :note))
160 (:mastersthesis
161 (:description . "A Master’s thesis.")
162 (:required :author :title :school :year)
163 (:optional :type :address :month :note))
164 (:misc
165 (:description . "Use this type when nothing else fits.")
166 (:required)
167 (:optional :author :title :howpublished :month :year :note))
168 (:phdthesis
169 (:description . "A PhD thesis.")
170 (:required :author :title :school :year)
171 (:optional :type :address :month :note))
172 (:proceedings
173 (:description . "The proceedings of a conference.")
174 (:required :title :year)
175 (:optional :editor (:volume :number) :series :address :month :organization :publisher :note))
176 (:techreport
177 (:description . "A report published by a school or other institution.")
178 (:required :author :title :institution :year)
179 (:optional :type :address :month :note))
180 (:unpublished
181 (:description . "A document having an author and title, but not formally published.")
182 (:required :author :title :note)
183 (:optional :month :year)))
184 "Bibtex entry types with required and optional parameters.")
185
186(defvar org-bibtex-fields
8223b1d2
BG
187 '((:address . "Usually the address of the publisher or other type of institution. For major publishing houses, van Leunen recommends omitting the information entirely. For small publishers, on the other hand, you can help the reader by giving the complete address.")
188 (:annote . "An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.")
3ab2c837 189 (:author . "The name(s) of the author(s), in the format described in the LaTeX book. Remember, all names are separated with the and keyword, and not commas.")
8223b1d2 190 (:booktitle . "Title of a book, part of which is being cited. See the LaTeX book for how to type titles. For book entries, use the title field instead.")
3ab2c837
BG
191 (:chapter . "A chapter (or section or whatever) number.")
192 (:crossref . "The database key of the entry being cross referenced.")
8223b1d2
BG
193 (:edition . "The edition of a book for example, 'Second'. This should be an ordinal, and should have the first letter capitalized, as shown here; the standard styles convert to lower case when necessary.")
194 (:editor . "Name(s) of editor(s), typed as indicated in the LaTeX book. If there is also an author field, then the editor field gives the editor of the book or collection in which the reference appears.")
195 (:howpublished . "How something strange has been published. The first word should be capitalized.")
3ab2c837
BG
196 (:institution . "The sponsoring institution of a technical report.")
197 (:journal . "A journal name.")
8223b1d2
BG
198 (:key . "Used for alphabetizing, cross-referencing, and creating a label when the author information is missing. This field should not be confused with the key that appears in the \cite command and at the beginning of the database entry.")
199 (:month . "The month in which the work was published or, for an unpublished work, in which it was written. You should use the standard three-letter abbreviation,")
200 (:note . "Any additional information that can help the reader. The first word should be capitalized.")
201 (:number . "Any additional information that can help the reader. The first word should be capitalized.")
3ab2c837
BG
202 (:organization . "The organization that sponsors a conference or that publishes a manual.")
203 (:pages . "One or more page numbers or range of numbers, such as 42-111 or 7,41,73-97 or 43+ (the ‘+’ in this last example indicates pages following that don’t form simple range). BibTEX requires double dashes for page ranges (--).")
204 (:publisher . "The publisher’s name.")
205 (:school . "The name of the school where a thesis was written.")
8223b1d2 206 (:series . "The name of a series or set of books. When citing an entire book, the the title field gives its title and an optional series field gives the name of a series or multi-volume set in which the book is published.")
3ab2c837
BG
207 (:title . "The work’s title, typed as explained in the LaTeX book.")
208 (:type . "The type of a technical report for example, 'Research Note'.")
209 (:volume . "The volume of a journal or multi-volume book.")
210 (:year . "The year of publication or, for an unpublished work, the year it was written. Generally it should consist of four numerals, such as 1984, although the standard styles can handle any year whose last four nonpunctuation characters are numerals, such as '(about 1984)'"))
211 "Bibtex fields with descriptions.")
212
8223b1d2 213(defvar org-bibtex-entries nil
3ab2c837
BG
214 "List to hold parsed bibtex entries.")
215
216(defcustom org-bibtex-autogen-keys nil
ee7683eb 217 "Set to a truth value to use `bibtex-generate-autokey' to generate keys."
3ab2c837 218 :group 'org-bibtex
372d7b21 219 :version "24.1"
3ab2c837
BG
220 :type 'boolean)
221
222(defcustom org-bibtex-prefix nil
223 "Optional prefix for all bibtex property names.
e66ba1df 224For example setting to 'BIB_' would allow interoperability with fireforg."
3ab2c837 225 :group 'org-bibtex
372d7b21 226 :version "24.1"
271672fa
BG
227 :type '(choice
228 (const nil)
229 (string)))
3ab2c837
BG
230
231(defcustom org-bibtex-treat-headline-as-title t
232 "Treat headline text as title if title property is absent.
233If an entry is missing a title property, use the headline text as
8223b1d2 234the property. If this value is t, `org-bibtex-check' will ignore
3ab2c837
BG
235a missing title field."
236 :group 'org-bibtex
372d7b21 237 :version "24.1"
3ab2c837
BG
238 :type 'boolean)
239
240(defcustom org-bibtex-export-arbitrary-fields nil
241 "When converting to bibtex allow fields not defined in `org-bibtex-fields'.
242This only has effect if `org-bibtex-prefix' is defined, so as to
243ensure that other org-properties, such as CATEGORY or LOGGING are
244not placed in the exported bibtex entry."
245 :group 'org-bibtex
372d7b21 246 :version "24.1"
3ab2c837
BG
247 :type 'boolean)
248
249(defcustom org-bibtex-key-property "CUSTOM_ID"
250 "Property that holds the bibtex key.
251By default, this is CUSTOM_ID, which enables easy linking to
8223b1d2 252bibtex headlines from within an org file. This can be set to ID
3ab2c837
BG
253to enable global links, but only with great caution, as global
254IDs must be unique."
255 :group 'org-bibtex
372d7b21 256 :version "24.1"
3ab2c837
BG
257 :type 'string)
258
259(defcustom org-bibtex-tags nil
260 "List of tag(s) that should be added to new bib entries."
261 :group 'org-bibtex
372d7b21 262 :version "24.1"
3ab2c837
BG
263 :type '(repeat :tag "Tag" (string)))
264
265(defcustom org-bibtex-tags-are-keywords nil
266 "Convert the value of the keywords field to tags and vice versa.
267If set to t, comma-separated entries in a bibtex entry's keywords
8223b1d2 268field will be converted to org tags. Note: spaces will be escaped
3ab2c837
BG
269with underscores, and characters that are not permitted in org
270tags will be removed.
271
272If t, local tags in an org entry will be exported as a
8223b1d2 273comma-separated string of keywords when exported to bibtex. Tags
3ab2c837
BG
274defined in `org-bibtex-tags' or `org-bibtex-no-export-tags' will
275not be exported."
276 :group 'org-bibtex
372d7b21 277 :version "24.1"
3ab2c837 278 :type 'boolean)
20908596 279
3ab2c837
BG
280(defcustom org-bibtex-no-export-tags nil
281 "List of tag(s) that should not be converted to keywords.
30cb51f1 282This variable is relevant only if `org-bibtex-tags-are-keywords' is t."
3ab2c837 283 :group 'org-bibtex
372d7b21 284 :version "24.1"
3ab2c837
BG
285 :type '(repeat :tag "Tag" (string)))
286
e66ba1df
BG
287(defcustom org-bibtex-type-property-name "btype"
288 "Property in which to store bibtex entry type (e.g., article)."
289 :group 'org-bibtex
372d7b21 290 :version "24.1"
e66ba1df
BG
291 :type 'string)
292
3ab2c837
BG
293\f
294;;; Utility functions
295(defun org-bibtex-get (property)
666ffc7e
SM
296 (let ((it (let ((org-special-properties
297 (delete "FILE" (copy-sequence org-special-properties))))
298 (or
299 (org-entry-get (point) (upcase property))
300 (org-entry-get (point) (concat org-bibtex-prefix
301 (upcase property)))))))
302 (when it (org-babel-trim it))))
3ab2c837
BG
303
304(defun org-bibtex-put (property value)
305 (let ((prop (upcase (if (keywordp property)
306 (substring (symbol-name property) 1)
307 property))))
308 (org-set-property
309 (concat (unless (string= org-bibtex-key-property prop) org-bibtex-prefix)
310 prop)
311 value)))
312
313(defun org-bibtex-headline ()
314 "Return a bibtex entry of the given headline as a string."
8223b1d2
BG
315 (let* ((val (lambda (key lst) (cdr (assoc key lst))))
316 (to (lambda (string) (intern (concat ":" string))))
317 (from (lambda (key) (substring (symbol-name key) 1)))
318 flatten ; silent compiler warning
319 (flatten (lambda (&rest lsts)
320 (apply #'append (mapcar
321 (lambda (e)
322 (if (listp e) (apply flatten e) (list e)))
323 lsts))))
324 (notes (buffer-string))
325 (id (org-bibtex-get org-bibtex-key-property))
326 (type (org-bibtex-get org-bibtex-type-property-name))
327 (tags (when org-bibtex-tags-are-keywords
328 (delq nil
329 (mapcar
330 (lambda (tag)
331 (unless (member tag
332 (append org-bibtex-tags
333 org-bibtex-no-export-tags))
334 tag))
335 (org-get-local-tags-at))))))
336 (when type
337 (let ((entry (format
338 "@%s{%s,\n%s\n}\n" type id
339 (mapconcat
340 (lambda (pair)
341 (format " %s={%s}" (car pair) (cdr pair)))
342 (remove nil
343 (if (and org-bibtex-export-arbitrary-fields
344 org-bibtex-prefix)
345 (mapcar
346 (lambda (kv)
347 (let ((key (car kv)) (val0 (cdr kv)))
348 (when (and
349 (string-match org-bibtex-prefix key)
350 (not (string=
351 (downcase (concat org-bibtex-prefix
352 org-bibtex-type-property-name))
353 (downcase key))))
354 (cons (downcase (replace-regexp-in-string
355 org-bibtex-prefix "" key))
356 val0))))
357 (org-entry-properties nil 'standard))
358 (mapcar
359 (lambda (field)
360 (let ((value (or (org-bibtex-get (funcall from field))
361 (and (equal :title field)
362 (nth 4 (org-heading-components))))))
363 (when value (cons (funcall from field) value))))
364 (funcall flatten
365 (funcall val :required (funcall val (funcall to type) org-bibtex-types))
366 (funcall val :optional (funcall val (funcall to type) org-bibtex-types))))))
367 ",\n"))))
368 (with-temp-buffer
369 (insert entry)
370 (when tags
371 (bibtex-beginning-of-entry)
372 (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
373 (progn (goto-char (match-end 1)) (insert ", "))
30cb51f1
BG
374 (search-forward ",\n" nil t)
375 (insert " keywords={},\n")
376 (search-backward "}," nil t))
8223b1d2
BG
377 (insert (mapconcat #'identity tags ", ")))
378 (buffer-string))))))
3ab2c837
BG
379
380(defun org-bibtex-ask (field)
381 (unless (assoc field org-bibtex-fields)
8223b1d2 382 (error "Field:%s is not known" field))
3ab2c837
BG
383 (save-window-excursion
384 (let* ((name (substring (symbol-name field) 1))
385 (buf-name (format "*Bibtex Help %s*" name)))
386 (with-output-to-temp-buffer buf-name
387 (princ (cdr (assoc field org-bibtex-fields))))
770de7cf 388 (with-current-buffer buf-name (visual-line-mode 1))
3ab2c837 389 (org-fit-window-to-buffer (get-buffer-window buf-name))
666ffc7e
SM
390 (let ((result (read-from-minibuffer (format "%s: " name))))
391 (when (> (length result) 0) result)))))
3ab2c837
BG
392
393(defun org-bibtex-autokey ()
8223b1d2 394 "Generate an autokey for the current headline."
3ab2c837
BG
395 (org-bibtex-put org-bibtex-key-property
396 (if org-bibtex-autogen-keys
397 (let* ((entry (org-bibtex-headline))
398 (key
399 (with-temp-buffer
400 (insert entry)
401 (bibtex-generate-autokey))))
402 ;; test for duplicate IDs if using global ID
403 (when (and
404 (equal org-bibtex-key-property "ID")
405 (featurep 'org-id)
406 (hash-table-p org-id-locations)
407 (gethash key org-id-locations))
408 (warn "Another entry has the same ID"))
409 key)
410 (read-from-minibuffer "id: "))))
411
412(defun org-bibtex-fleshout (type &optional optional)
8223b1d2 413 "Fleshout current heading, ensuring all required fields are present.
3ab2c837 414With optional argument OPTIONAL, also prompt for optional fields."
8223b1d2
BG
415 (let ((val (lambda (key lst) (cdr (assoc key lst))))
416 (keyword (lambda (name) (intern (concat ":" (downcase name)))))
417 (name (lambda (keyword) (substring (symbol-name keyword) 1))))
3ab2c837
BG
418 (dolist (field (append
419 (if org-bibtex-treat-headline-as-title
8223b1d2
BG
420 (remove :title (funcall val :required (funcall val type org-bibtex-types)))
421 (funcall val :required (funcall val type org-bibtex-types)))
422 (when optional (funcall val :optional (funcall val type org-bibtex-types)))))
3ab2c837 423 (when (consp field) ; or'd pair of fields e.g., (:editor :author)
8223b1d2
BG
424 (let ((present (first (remove
425 nil
426 (mapcar
427 (lambda (f) (when (org-bibtex-get (funcall name f)) f))
428 field)))))
429 (setf field (or present (funcall keyword
430 (org-icompleting-read
431 "Field: " (mapcar name field)))))))
432 (let ((name (funcall name field)))
3ab2c837
BG
433 (unless (org-bibtex-get name)
434 (let ((prop (org-bibtex-ask field)))
435 (when prop (org-bibtex-put name prop)))))))
436 (when (and type (assoc type org-bibtex-types)
437 (not (org-bibtex-get org-bibtex-key-property)))
438 (org-bibtex-autokey)))
439
440\f
441;;; Bibtex link functions
20908596
CD
442(org-add-link-type "bibtex" 'org-bibtex-open)
443(add-hook 'org-store-link-functions 'org-bibtex-store-link)
444
20908596
CD
445(defun org-bibtex-open (path)
446 "Visit the bibliography entry on PATH."
447 (let* ((search (when (string-match "::\\(.+\\)\\'" path)
448 (match-string 1 path)))
449 (path (substring path 0 (match-beginning 0))))
450 (org-open-file path t nil search)))
451
452(defun org-bibtex-store-link ()
453 "Store a link to a BibTeX entry."
454 (when (eq major-mode 'bibtex-mode)
455 (let* ((search (org-create-file-search-in-bibtex))
456 (link (concat "file:" (abbreviate-file-name buffer-file-name)
457 "::" search))
458 (entry (mapcar ; repair strings enclosed in "..." or {...}
459 (lambda(c)
460 (if (string-match
461 "^\\(?:{\\|\"\\)\\(.*\\)\\(?:}\\|\"\\)$" (cdr c))
462 (cons (car c) (match-string 1 (cdr c))) c))
463 (save-excursion
464 (bibtex-beginning-of-entry)
465 (bibtex-parse-entry)))))
466 (org-store-link-props
467 :key (cdr (assoc "=key=" entry))
468 :author (or (cdr (assoc "author" entry)) "[no author]")
469 :editor (or (cdr (assoc "editor" entry)) "[no editor]")
470 :title (or (cdr (assoc "title" entry)) "[no title]")
471 :booktitle (or (cdr (assoc "booktitle" entry)) "[no booktitle]")
472 :journal (or (cdr (assoc "journal" entry)) "[no journal]")
473 :publisher (or (cdr (assoc "publisher" entry)) "[no publisher]")
474 :pages (or (cdr (assoc "pages" entry)) "[no pages]")
475 :url (or (cdr (assoc "url" entry)) "[no url]")
476 :year (or (cdr (assoc "year" entry)) "[no year]")
477 :month (or (cdr (assoc "month" entry)) "[no month]")
478 :address (or (cdr (assoc "address" entry)) "[no address]")
479 :volume (or (cdr (assoc "volume" entry)) "[no volume]")
480 :number (or (cdr (assoc "number" entry)) "[no number]")
481 :annote (or (cdr (assoc "annote" entry)) "[no annotation]")
482 :series (or (cdr (assoc "series" entry)) "[no series]")
483 :abstract (or (cdr (assoc "abstract" entry)) "[no abstract]")
484 :btype (or (cdr (assoc "=type=" entry)) "[no type]")
485 :type "bibtex"
486 :link link
153ae947 487 :description org-bibtex-description))))
20908596
CD
488
489(defun org-create-file-search-in-bibtex ()
490 "Create the search string and description for a BibTeX database entry."
491 ;; Make a good description for this entry, using names, year and the title
492 ;; Put it into the `description' variable which is dynamically scoped.
493 (let ((bibtex-autokey-names 1)
494 (bibtex-autokey-names-stretch 1)
495 (bibtex-autokey-name-case-convert-function 'identity)
496 (bibtex-autokey-name-separator " & ")
497 (bibtex-autokey-additional-names " et al.")
498 (bibtex-autokey-year-length 4)
499 (bibtex-autokey-name-year-separator " ")
500 (bibtex-autokey-titlewords 3)
501 (bibtex-autokey-titleword-separator " ")
502 (bibtex-autokey-titleword-case-convert-function 'identity)
503 (bibtex-autokey-titleword-length 'infty)
504 (bibtex-autokey-year-title-separator ": "))
153ae947 505 (setq org-bibtex-description (bibtex-generate-autokey)))
20908596
CD
506 ;; Now parse the entry, get the key and return it.
507 (save-excursion
508 (bibtex-beginning-of-entry)
509 (cdr (assoc "=key=" (bibtex-parse-entry)))))
510
511(defun org-execute-file-search-in-bibtex (s)
512 "Find the link search string S as a key for a database entry."
513 (when (eq major-mode 'bibtex-mode)
514 ;; Yes, we want to do the search in this file.
515 ;; We construct a regexp that searches for "@entrytype{" followed by the key
516 (goto-char (point-min))
517 (and (re-search-forward (concat "@[a-zA-Z]+[ \t\n]*{[ \t\n]*"
518 (regexp-quote s) "[ \t\n]*,") nil t)
519 (goto-char (match-beginning 0)))
520 (if (and (match-beginning 0) (equal current-prefix-arg '(16)))
521 ;; Use double prefix to indicate that any web link should be browsed
522 (let ((b (current-buffer)) (p (point)))
523 ;; Restore the window configuration because we just use the web link
524 (set-window-configuration org-window-config-before-follow-link)
81ad75af 525 (with-current-buffer b
8bfe682a
CD
526 (goto-char p)
527 (bibtex-url)))
20908596 528 (recenter 0)) ; Move entry start to beginning of window
3ab2c837 529 ;; return t to indicate that the search is done.
20908596
CD
530 t))
531
532;; Finally add the link search function to the right hook.
533(add-hook 'org-execute-file-search-functions 'org-execute-file-search-in-bibtex)
534
3ab2c837
BG
535\f
536;;; Bibtex <-> Org-mode headline translation functions
537(defun org-bibtex (&optional filename)
538 "Export each headline in the current file to a bibtex entry.
30cb51f1 539Headlines are exported using `org-bibtex-headline'."
3ab2c837
BG
540 (interactive
541 (list (read-file-name
542 "Bibtex file: " nil nil nil
543 (file-name-nondirectory
544 (concat (file-name-sans-extension (buffer-file-name)) ".bib")))))
666ffc7e
SM
545 (let ((error-point
546 (catch 'bib
547 (let ((bibtex-entries
548 (remove nil (org-map-entries
549 (lambda ()
550 (condition-case foo
551 (org-bibtex-headline)
552 (error (throw 'bib (point)))))))))
553 (with-temp-file filename
554 (insert (mapconcat #'identity bibtex-entries "\n")))
555 (message "Successfully exported %d BibTeX entries to %s"
556 (length bibtex-entries) filename) nil))))
557 (when error-point
558 (goto-char error-point)
559 (message "Bibtex error at %S" (nth 4 (org-heading-components))))))
3ab2c837
BG
560
561(defun org-bibtex-check (&optional optional)
562 "Check the current headline for required fields.
563With prefix argument OPTIONAL also prompt for optional fields."
564 (interactive "P")
565 (save-restriction
566 (org-narrow-to-subtree)
666ffc7e
SM
567 (let ((type (let ((name (org-bibtex-get org-bibtex-type-property-name)))
568 (when name (intern (concat ":" name))))))
3ab2c837
BG
569 (when type (org-bibtex-fleshout type optional)))))
570
571(defun org-bibtex-check-all (&optional optional)
572 "Check all headlines in the current file.
573With prefix argument OPTIONAL also prompt for optional fields."
574 (interactive) (org-map-entries (lambda () (org-bibtex-check optional))))
575
576(defun org-bibtex-create (&optional arg nonew)
577 "Create a new entry at the given level.
578With a prefix arg, query for optional fields as well.
579If nonew is t, add data to the headline of the entry at point."
580 (interactive "P")
581 (let* ((type (org-icompleting-read
582 "Type: " (mapcar (lambda (type)
583 (substring (symbol-name (car type)) 1))
584 org-bibtex-types)
e66ba1df
BG
585 nil nil (when nonew
586 (org-bibtex-get org-bibtex-type-property-name))))
3ab2c837
BG
587 (type (if (keywordp type) type (intern (concat ":" type))))
588 (org-bibtex-treat-headline-as-title (if nonew nil t)))
589 (unless (assoc type org-bibtex-types)
8223b1d2 590 (error "Type:%s is not known" type))
3ab2c837
BG
591 (if nonew
592 (org-back-to-heading)
593 (org-insert-heading)
594 (let ((title (org-bibtex-ask :title)))
595 (insert title)
596 (org-bibtex-put "TITLE" title)))
e66ba1df
BG
597 (org-bibtex-put org-bibtex-type-property-name
598 (substring (symbol-name type) 1))
3ab2c837
BG
599 (org-bibtex-fleshout type arg)
600 (mapc (lambda (tag) (org-toggle-tag tag 'on)) org-bibtex-tags)))
601
602(defun org-bibtex-create-in-current-entry (&optional arg)
603 "Add bibliographical data to the current entry.
604With a prefix arg, query for optional fields."
605 (interactive "P")
606 (org-bibtex-create arg t))
607
608(defun org-bibtex-read ()
8223b1d2 609 "Read a bibtex entry and save to `org-bibtex-entries'.
3ab2c837
BG
610This uses `bibtex-parse-entry'."
611 (interactive)
8223b1d2
BG
612 (let ((keyword (lambda (str) (intern (concat ":" (downcase str)))))
613 (clean-space (lambda (str) (replace-regexp-in-string
614 "[[:space:]\n\r]+" " " str)))
615 (strip-delim
616 (lambda (str) ; strip enclosing "..." and {...}
617 (dolist (pair '((34 . 34) (123 . 125) (123 . 125)))
30cb51f1
BG
618 (when (and (> (length str) 1)
619 (= (aref str 0) (car pair))
8223b1d2
BG
620 (= (aref str (1- (length str))) (cdr pair)))
621 (setf str (substring str 1 (1- (length str)))))) str)))
3ab2c837
BG
622 (push (mapcar
623 (lambda (pair)
8223b1d2 624 (cons (let ((field (funcall keyword (car pair))))
3ab2c837
BG
625 (case field
626 (:=type= :type)
627 (:=key= :key)
628 (otherwise field)))
8223b1d2 629 (funcall clean-space (funcall strip-delim (cdr pair)))))
3ab2c837 630 (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
8223b1d2 631 org-bibtex-entries)))
3ab2c837 632
271672fa
BG
633(defun org-bibtex-read-buffer (buffer)
634 "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'.
635Return the number of saved entries."
636 (interactive "bbuffer: ")
637 (let ((start-length (length org-bibtex-entries)))
638 (with-current-buffer buffer
639 (save-excursion
640 (goto-char (point-max))
641 (while (not (= (point) (point-min)))
642 (backward-char 1)
643 (org-bibtex-read)
644 (bibtex-beginning-of-entry))))
645 (let ((added (- (length org-bibtex-entries) start-length)))
646 (message "parsed %d entries" added)
647 added)))
648
649(defun org-bibtex-read-file (file)
650 "Read FILE with `org-bibtex-read-buffer'."
651 (interactive "ffile: ")
652 (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile)))
653
3ab2c837 654(defun org-bibtex-write ()
8223b1d2 655 "Insert a heading built from the first element of `org-bibtex-entries'."
3ab2c837 656 (interactive)
8223b1d2
BG
657 (when (= (length org-bibtex-entries) 0)
658 (error "No entries in `org-bibtex-entries'"))
659 (let* ((entry (pop org-bibtex-entries))
660 (org-special-properties nil) ; avoids errors with `org-entry-put'
661 (val (lambda (field) (cdr (assoc field entry))))
662 (togtag (lambda (tag) (org-toggle-tag tag 'on))))
663 (org-insert-heading)
664 (insert (funcall val :title))
665 (org-bibtex-put "TITLE" (funcall val :title))
666 (org-bibtex-put org-bibtex-type-property-name
667 (downcase (funcall val :type)))
668 (dolist (pair entry)
669 (case (car pair)
670 (:title nil)
671 (:type nil)
672 (:key (org-bibtex-put org-bibtex-key-property (cdr pair)))
673 (:keywords (if org-bibtex-tags-are-keywords
674 (mapc
675 (lambda (kw)
676 (funcall
677 togtag
678 (replace-regexp-in-string
679 "[^[:alnum:]_@#%]" ""
680 (replace-regexp-in-string "[ \t]+" "_" kw))))
681 (split-string (cdr pair) ", *"))
682 (org-bibtex-put (car pair) (cdr pair))))
683 (otherwise (org-bibtex-put (car pair) (cdr pair)))))
684 (mapc togtag org-bibtex-tags)))
3ab2c837
BG
685
686(defun org-bibtex-yank ()
687 "If kill ring holds a bibtex entry yank it as an Org-mode headline."
688 (interactive)
689 (let (entry)
690 (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
691 (if entry
692 (org-bibtex-write)
8223b1d2 693 (error "Yanked text does not appear to contain a BibTeX entry"))))
3ab2c837 694
271672fa
BG
695(defun org-bibtex-import-from-file (file)
696 "Read bibtex entries from FILE and insert as Org-mode headlines after point."
697 (interactive "ffile: ")
698 (dotimes (_ (org-bibtex-read-file file))
699 (save-excursion (org-bibtex-write))
700 (re-search-forward org-property-end-re)
701 (open-line 1) (forward-char 1)))
702
3ab2c837
BG
703(defun org-bibtex-export-to-kill-ring ()
704 "Export current headline to kill ring as bibtex entry."
705 (interactive)
8c8b834f
BG
706 (let ((result (org-bibtex-headline)))
707 (kill-new result) result))
3ab2c837
BG
708
709(defun org-bibtex-search (string)
710 "Search for bibliographical entries in agenda files.
711This function relies `org-search-view' to locate results."
712 (interactive "sSearch string: ")
713 (let ((org-agenda-overriding-header "Bib search results:")
714 (org-agenda-search-view-always-boolean t))
715 (org-search-view nil
e66ba1df 716 (format "%s +{:%s%s:}"
d3517077 717 string (or org-bibtex-prefix "")
e66ba1df 718 org-bibtex-type-property-name))))
3ab2c837 719
20908596
CD
720(provide 'org-bibtex)
721
722;;; org-bibtex.el ends here