Fix copyright years by hand.
[bpt/emacs.git] / lisp / org / org-bibtex.el
index 17cdbc2..b4e6977 100644 (file)
@@ -1,11 +1,11 @@
 ;;; org-bibtex.el --- Org links to BibTeX entries
 ;;
-;; Copyright (C) 2007-2012 Free Software Foundation, Inc.
+;; Copyright (C) 2007-2014 Free Software Foundation, Inc.
 ;;
-;; Author: Bastien Guerry <bzg at altern dot org>
-;;         Carsten Dominik <carsten dot dominik at gmail dot com>
-;;         Eric Schulte <schulte dot eric at gmail dot com>
-;; Keywords: org, wp, remember
+;; Authors: Bastien Guerry <bzg@gnu.org>
+;;       Carsten Dominik <carsten dot dominik at gmail dot com>
+;;       Eric Schulte <schulte dot eric at gmail dot com>
+;; Keywords: org, wp, capture
 ;;
 ;; This file is part of GNU Emacs.
 ;;
@@ -31,7 +31,7 @@
 ;; the link that contains the author name, the year and a short title.
 ;;
 ;; It also stores detailed information about the entry so that
-;; remember templates can access and enter this information easily.
+;; capture templates can access and enter this information easily.
 ;;
 ;; The available properties for each entry are listed here:
 ;;
 ;; :booktitle     :month          :annote      :abstract
 ;; :key           :btype
 ;;
-;; Here is an example of a remember template that use some of this
+;; Here is an example of a capture template that use some of this
 ;; information (:author :year :title :journal :pages):
 ;;
-;; (setq org-remember-templates
+;; (setq org-capture-templates
 ;;   '((?b "* READ %?\n\n%a\n\n%:author (%:year): %:title\n   \
 ;;          In %:journal, %:pages.")))
 ;;
-;; Let's say you want to remember this BibTeX entry:
+;; Let's say you want to capture this BibTeX entry:
 ;;
 ;; @Article{dolev83,
 ;;   author =   {Danny Dolev and Andrew C. Yao},
@@ -61,7 +61,7 @@
 ;;   month =    {Mars}
 ;; }
 ;;
-;; M-x `org-remember' on this entry will produce this buffer:
+;; M-x `org-capture' on this entry will produce this buffer:
 ;;
 ;; =====================================================================
 ;; * READ <== [point here]
 ;;
 ;; - All Bibtex information is taken from the document compiled by
 ;;   Andrew Roberts from the Bibtex manual, available at
-;;   http://www.andy-roberts.net/misc/latex/sessions/bibtex/bibentries.pdf
+;;   http://www.andy-roberts.net/res/writing/latex/bibentries.pdf
 ;;
 ;;; History:
 ;;
 ;; The link creation part has been part of Org-mode for a long time.
 ;;
-;; Creating better remember template information was inspired by a request
+;; Creating better capture template information was inspired by a request
 ;; of Austin Frank: http://article.gmane.org/gmane.emacs.orgmode/4112
 ;; and then implemented by Bastien Guerry.
 ;;
 (require 'bibtex)
 (eval-when-compile
   (require 'cl))
+(require 'org-compat)
 
-(defvar description nil) ; dynamically scoped from org.el
+(defvar org-bibtex-description nil) ; dynamically scoped from org.el
 (defvar org-id-locations)
 
 (declare-function bibtex-beginning-of-entry "bibtex" ())
 (declare-function bibtex-generate-autokey "bibtex" ())
 (declare-function bibtex-parse-entry "bibtex" (&optional content))
 (declare-function bibtex-url "bibtex" (&optional pos no-browse))
-(declare-function longlines-mode "longlines" (&optional arg))
 (declare-function org-babel-trim "ob" (string &optional regexp))
 
 \f
   "Bibtex entry types with required and optional parameters.")
 
 (defvar org-bibtex-fields
-  '((: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.")
-    (:annote       . "An annotation. It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.")
+  '((: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.")
+    (:annote       . "An annotation.  It is not used by the standard bibliography styles, but may be used by others that produce an annotated bibliography.")
     (: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.")
-    (: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.")
+    (: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.")
     (:chapter      . "A chapter (or section or whatever) number.")
     (:crossref     . "The database key of the entry being cross referenced.")
-    (: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.")
-    (: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.")
-    (:howpublished . "How something strange has been published. The first word should be capitalized.")
+    (: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.")
+    (: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.")
+    (:howpublished . "How something strange has been published.  The first word should be capitalized.")
     (:institution  . "The sponsoring institution of a technical report.")
     (:journal      . "A journal name.")
-    (: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.")
-    (: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,")
-    (:note         . "Any additional information that can help the reader. The first word should be capitalized.")
-    (:number       . "Any additional information that can help the reader. The first word should be capitalized.")
+    (: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.")
+    (: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,")
+    (:note         . "Any additional information that can help the reader.  The first word should be capitalized.")
+    (:number       . "Any additional information that can help the reader.  The first word should be capitalized.")
     (:organization . "The organization that sponsors a conference or that publishes a manual.")
     (: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 (--).")
     (:publisher    . "The publisher’s name.")
     (:school       . "The name of the school where a thesis was written.")
-    (: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.")
+    (: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.")
     (:title        . "The work’s title, typed as explained in the LaTeX book.")
     (:type         . "The type of a technical report for example, 'Research Note'.")
     (:volume       . "The volume of a journal or multi-volume book.")
     (: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)'"))
   "Bibtex fields with descriptions.")
 
-(defvar *org-bibtex-entries* nil
+(defvar org-bibtex-entries nil
   "List to hold parsed bibtex entries.")
 
 (defcustom org-bibtex-autogen-keys nil
   "Set to a truth value to use `bibtex-generate-autokey' to generate keys."
   :group 'org-bibtex
+  :version "24.1"
   :type  'boolean)
 
 (defcustom org-bibtex-prefix nil
   "Optional prefix for all bibtex property names.
 For example setting to 'BIB_' would allow interoperability with fireforg."
   :group 'org-bibtex
-  :type  'string)
+  :version "24.1"
+  :type  '(choice
+          (const nil)
+          (string)))
 
 (defcustom org-bibtex-treat-headline-as-title t
   "Treat headline text as title if title property is absent.
 If an entry is missing a title property, use the headline text as
-the property. If this value is t, `org-bibtex-check' will ignore
+the property.  If this value is t, `org-bibtex-check' will ignore
 a missing title field."
   :group 'org-bibtex
+  :version "24.1"
   :type 'boolean)
 
 (defcustom org-bibtex-export-arbitrary-fields nil
@@ -238,56 +243,63 @@ This only has effect if `org-bibtex-prefix' is defined, so as to
 ensure that other org-properties, such as CATEGORY or LOGGING are
 not placed in the exported bibtex entry."
   :group 'org-bibtex
+  :version "24.1"
   :type 'boolean)
 
 (defcustom org-bibtex-key-property "CUSTOM_ID"
   "Property that holds the bibtex key.
 By default, this is CUSTOM_ID, which enables easy linking to
-bibtex headlines from within an org file. This can be set to ID
+bibtex headlines from within an org file.  This can be set to ID
 to enable global links, but only with great caution, as global
 IDs must be unique."
   :group 'org-bibtex
+  :version "24.1"
   :type 'string)
 
 (defcustom org-bibtex-tags nil
   "List of tag(s) that should be added to new bib entries."
   :group 'org-bibtex
+  :version "24.1"
   :type '(repeat  :tag "Tag" (string)))
 
 (defcustom org-bibtex-tags-are-keywords nil
   "Convert the value of the keywords field to tags and vice versa.
 If set to t, comma-separated entries in a bibtex entry's keywords
-field will be converted to org tags. Note: spaces will be escaped
+field will be converted to org tags.  Note: spaces will be escaped
 with underscores, and characters that are not permitted in org
 tags will be removed.
 
 If t, local tags in an org entry will be exported as a
-comma-separated string of keywords when exported to bibtex. Tags
+comma-separated string of keywords when exported to bibtex.  Tags
 defined in `org-bibtex-tags' or `org-bibtex-no-export-tags' will
 not be exported."
   :group 'org-bibtex
+  :version "24.1"
   :type 'boolean)
 
 (defcustom org-bibtex-no-export-tags nil
   "List of tag(s) that should not be converted to keywords.
-This variable is relevant only if `org-bibtex-export-tags-as-keywords` is t."
+This variable is relevant only if `org-bibtex-export-tags-as-keywords' is t."
   :group 'org-bibtex
+  :version "24.1"
   :type '(repeat :tag "Tag" (string)))
 
 (defcustom org-bibtex-type-property-name "btype"
   "Property in which to store bibtex entry type (e.g., article)."
   :group 'org-bibtex
+  :version "24.1"
   :type 'string)
 
 \f
 ;;; Utility functions
 (defun org-bibtex-get (property)
-  ((lambda (it) (when it (org-babel-trim it)))
-   (let ((org-special-properties
-         (delete "FILE" (copy-sequence org-special-properties))))
-     (or
-      (org-entry-get (point) (upcase property))
-      (org-entry-get (point) (concat org-bibtex-prefix (upcase property)))))))
+  (let ((it (let ((org-special-properties
+                   (delete "FILE" (copy-sequence org-special-properties))))
+              (or
+               (org-entry-get (point) (upcase property))
+               (org-entry-get (point) (concat org-bibtex-prefix
+                                              (upcase property)))))))
+    (when it (org-babel-trim it))))
 
 (defun org-bibtex-put (property value)
   (let ((prop (upcase (if (keywordp property)
@@ -300,83 +312,84 @@ This variable is relevant only if `org-bibtex-export-tags-as-keywords` is t."
 
 (defun org-bibtex-headline ()
   "Return a bibtex entry of the given headline as a string."
-  (flet ((val (key lst) (cdr (assoc key lst)))
-         (to (string) (intern (concat ":" string)))
-         (from (key) (substring (symbol-name key) 1))
-         (flatten (&rest lsts)
-                  (apply #'append (mapcar
-                                   (lambda (e)
-                                     (if (listp e) (apply #'flatten e) (list e)))
-                                   lsts))))
-    (let ((notes (buffer-string))
-          (id (org-bibtex-get org-bibtex-key-property))
-          (type (org-bibtex-get org-bibtex-type-property-name))
-         (tags (when org-bibtex-tags-are-keywords
-                 (delq nil
-                       (mapcar
-                        (lambda (tag)
-                          (unless (member tag
-                                          (append org-bibtex-tags
-                                                  org-bibtex-no-export-tags))
-                            tag))
-                        (org-get-local-tags-at))))))
-      (when type
-        (let ((entry (format
-                      "@%s{%s,\n%s\n}\n" type id
-                      (mapconcat
-                       (lambda (pair)
-                        (format "  %s={%s}" (car pair) (cdr pair)))
-                       (remove nil
-                        (if (and org-bibtex-export-arbitrary-fields
-                                 org-bibtex-prefix)
-                            (mapcar
-                             (lambda (kv)
-                               (let ((key (car kv)) (val (cdr kv)))
-                                 (when (and
-                                        (string-match org-bibtex-prefix key)
-                                        (not (string=
-                                              (downcase (concat org-bibtex-prefix
-                                                                org-bibtex-type-property-name))
-                                              (downcase key))))
-                                   (cons (downcase (replace-regexp-in-string
-                                                    org-bibtex-prefix "" key))
-                                         val))))
-                             (org-entry-properties nil 'standard))
-                          (mapcar
-                           (lambda (field)
-                             (let ((value (or (org-bibtex-get (from field))
-                                              (and (equal :title field)
-                                                   (nth 4 (org-heading-components))))))
-                               (when value (cons (from field) value))))
-                           (flatten
-                            (val :required (val (to type) org-bibtex-types))
-                            (val :optional (val (to type) org-bibtex-types))))))
-                       ",\n"))))
-          (with-temp-buffer
-            (insert entry)
-           (when tags
-             (bibtex-beginning-of-entry)
-             (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
-                 (progn (goto-char (match-end 1)) (insert ", "))
-               (bibtex-make-field "keywords" t t))
-             (insert (mapconcat #'identity tags ", ")))
-            (bibtex-reformat) (buffer-string)))))))
+  (let* ((val (lambda (key lst) (cdr (assoc key lst))))
+        (to (lambda (string) (intern (concat ":" string))))
+        (from (lambda (key) (substring (symbol-name key) 1)))
+        flatten ; silent compiler warning
+        (flatten (lambda (&rest lsts)
+                   (apply #'append (mapcar
+                                    (lambda (e)
+                                      (if (listp e) (apply flatten e) (list e)))
+                                    lsts))))
+        (notes (buffer-string))
+        (id (org-bibtex-get org-bibtex-key-property))
+        (type (org-bibtex-get org-bibtex-type-property-name))
+        (tags (when org-bibtex-tags-are-keywords
+                (delq nil
+                      (mapcar
+                       (lambda (tag)
+                         (unless (member tag
+                                         (append org-bibtex-tags
+                                                 org-bibtex-no-export-tags))
+                           tag))
+                       (org-get-local-tags-at))))))
+    (when type
+      (let ((entry (format
+                   "@%s{%s,\n%s\n}\n" type id
+                   (mapconcat
+                    (lambda (pair)
+                      (format "  %s={%s}" (car pair) (cdr pair)))
+                    (remove nil
+                            (if (and org-bibtex-export-arbitrary-fields
+                                     org-bibtex-prefix)
+                                (mapcar
+                                 (lambda (kv)
+                                   (let ((key (car kv)) (val0 (cdr kv)))
+                                     (when (and
+                                            (string-match org-bibtex-prefix key)
+                                            (not (string=
+                                                  (downcase (concat org-bibtex-prefix
+                                                                    org-bibtex-type-property-name))
+                                                  (downcase key))))
+                                       (cons (downcase (replace-regexp-in-string
+                                                        org-bibtex-prefix "" key))
+                                             val0))))
+                                 (org-entry-properties nil 'standard))
+                              (mapcar
+                               (lambda (field)
+                                 (let ((value (or (org-bibtex-get (funcall from field))
+                                                  (and (equal :title field)
+                                                       (nth 4 (org-heading-components))))))
+                                   (when value (cons (funcall from field) value))))
+                               (funcall flatten
+                                        (funcall val :required (funcall val (funcall to type) org-bibtex-types))
+                                        (funcall val :optional (funcall val (funcall to type) org-bibtex-types))))))
+                    ",\n"))))
+       (with-temp-buffer
+         (insert entry)
+         (when tags
+           (bibtex-beginning-of-entry)
+           (if (re-search-forward "keywords.*=.*{\\(.*\\)}" nil t)
+               (progn (goto-char (match-end 1)) (insert ", "))
+             (bibtex-make-field "keywords" t t))
+           (insert (mapconcat #'identity tags ", ")))
+         (buffer-string))))))
 
 (defun org-bibtex-ask (field)
   (unless (assoc field org-bibtex-fields)
-    (error "field:%s is not known" field))
+    (error "Field:%s is not known" field))
   (save-window-excursion
     (let* ((name (substring (symbol-name field) 1))
           (buf-name (format "*Bibtex Help %s*" name)))
       (with-output-to-temp-buffer buf-name
        (princ (cdr (assoc field org-bibtex-fields))))
-      (with-current-buffer buf-name (longlines-mode t))
+      (with-current-buffer buf-name (visual-line-mode 1))
       (org-fit-window-to-buffer (get-buffer-window buf-name))
-      ((lambda (result) (when (> (length result) 0) result))
-       (read-from-minibuffer (format "%s: " name))))))
+      (let ((result (read-from-minibuffer (format "%s: " name))))
+        (when (> (length result) 0) result)))))
 
 (defun org-bibtex-autokey ()
-  "Generate an autokey for the current headline"
+  "Generate an autokey for the current headline."
   (org-bibtex-put org-bibtex-key-property
                   (if org-bibtex-autogen-keys
                       (let* ((entry (org-bibtex-headline))
@@ -395,24 +408,26 @@ This variable is relevant only if `org-bibtex-export-tags-as-keywords` is t."
                     (read-from-minibuffer "id: "))))
 
 (defun org-bibtex-fleshout (type &optional optional)
-  "Fleshout the current heading, ensuring that all required fields are present.
+  "Fleshout current heading, ensuring all required fields are present.
 With optional argument OPTIONAL, also prompt for optional fields."
-  (flet ((val (key lst) (cdr (assoc key lst)))
-        (keyword (name) (intern (concat ":" (downcase name))))
-         (name (keyword) (substring (symbol-name keyword) 1)))
+  (let ((val (lambda (key lst) (cdr (assoc key lst))))
+       (keyword (lambda (name) (intern (concat ":" (downcase name)))))
+       (name (lambda (keyword) (substring (symbol-name keyword) 1))))
     (dolist (field (append
                    (if org-bibtex-treat-headline-as-title
-                       (remove :title (val :required (val type org-bibtex-types)))
-                     (val :required (val type org-bibtex-types)))
-                   (when optional (val :optional (val type org-bibtex-types)))))
+                       (remove :title (funcall val :required (funcall val type org-bibtex-types)))
+                     (funcall val :required (funcall val type org-bibtex-types)))
+                   (when optional (funcall val :optional (funcall val type org-bibtex-types)))))
       (when (consp field) ; or'd pair of fields e.g., (:editor :author)
-        (let ((present (first (remove nil
-                                (mapcar
-                                 (lambda (f) (when (org-bibtex-get (name f)) f))
-                                 field)))))
-          (setf field (or present (keyword (org-icompleting-read
-                                           "Field: " (mapcar #'name field)))))))
-      (let ((name (name field)))
+        (let ((present (first (remove
+                              nil
+                              (mapcar
+                               (lambda (f) (when (org-bibtex-get (funcall name f)) f))
+                               field)))))
+          (setf field (or present (funcall keyword
+                                          (org-icompleting-read
+                                           "Field: " (mapcar name field)))))))
+      (let ((name (funcall name field)))
         (unless (org-bibtex-get name)
           (let ((prop (org-bibtex-ask field)))
             (when prop (org-bibtex-put name prop)))))))
@@ -467,7 +482,7 @@ With optional argument OPTIONAL, also prompt for optional fields."
        :btype (or (cdr (assoc "=type=" entry)) "[no type]")
        :type "bibtex"
        :link link
-       :description description))))
+       :description org-bibtex-description))))
 
 (defun org-create-file-search-in-bibtex ()
   "Create the search string and description for a BibTeX database entry."
@@ -485,7 +500,7 @@ With optional argument OPTIONAL, also prompt for optional fields."
        (bibtex-autokey-titleword-case-convert-function 'identity)
        (bibtex-autokey-titleword-length 'infty)
        (bibtex-autokey-year-title-separator ": "))
-    (setq description (bibtex-generate-autokey)))
+    (setq org-bibtex-description (bibtex-generate-autokey)))
   ;; Now parse the entry, get the key and return it.
   (save-excursion
     (bibtex-beginning-of-entry)
@@ -525,20 +540,21 @@ Headlines are exported using `org-bibtex-export-headline'."
          "Bibtex file: " nil nil nil
          (file-name-nondirectory
           (concat (file-name-sans-extension (buffer-file-name)) ".bib")))))
-  ((lambda (error-point)
-     (when error-point
-       (goto-char error-point)
-       (message "Bibtex error at %S" (nth 4 (org-heading-components)))))
-   (catch 'bib
-     (let ((bibtex-entries (remove nil (org-map-entries
-                                       (lambda ()
-                                         (condition-case foo
-                                             (org-bibtex-headline)
-                                           (error (throw 'bib (point)))))))))
-       (with-temp-file filename
-        (insert (mapconcat #'identity bibtex-entries "\n")))
-       (message "Successfully exported %d bibtex entries to %s"
-               (length bibtex-entries) filename) nil))))
+  (let ((error-point
+         (catch 'bib
+           (let ((bibtex-entries
+                  (remove nil (org-map-entries
+                               (lambda ()
+                                 (condition-case foo
+                                     (org-bibtex-headline)
+                                   (error (throw 'bib (point)))))))))
+             (with-temp-file filename
+               (insert (mapconcat #'identity bibtex-entries "\n")))
+             (message "Successfully exported %d BibTeX entries to %s"
+                      (length bibtex-entries) filename) nil))))
+    (when error-point
+      (goto-char error-point)
+      (message "Bibtex error at %S" (nth 4 (org-heading-components))))))
 
 (defun org-bibtex-check (&optional optional)
   "Check the current headline for required fields.
@@ -546,8 +562,8 @@ With prefix argument OPTIONAL also prompt for optional fields."
   (interactive "P")
   (save-restriction
     (org-narrow-to-subtree)
-    (let ((type ((lambda (name) (when name (intern (concat ":" name))))
-                 (org-bibtex-get org-bibtex-type-property-name))))
+    (let ((type (let ((name (org-bibtex-get org-bibtex-type-property-name)))
+                  (when name (intern (concat ":" name))))))
       (when type (org-bibtex-fleshout type optional)))))
 
 (defun org-bibtex-check-all (&optional optional)
@@ -569,7 +585,7 @@ If nonew is t, add data to the headline of the entry at point."
         (type (if (keywordp type) type (intern (concat ":" type))))
         (org-bibtex-treat-headline-as-title (if nonew nil t)))
     (unless (assoc type org-bibtex-types)
-      (error "type:%s is not known" type))
+      (error "Type:%s is not known" type))
     (if nonew
        (org-back-to-heading)
       (org-insert-heading)
@@ -588,57 +604,81 @@ With a prefix arg, query for optional fields."
   (org-bibtex-create arg t))
 
 (defun org-bibtex-read ()
-  "Read a bibtex entry and save to `*org-bibtex-entries*'.
+  "Read a bibtex entry and save to `org-bibtex-entries'.
 This uses `bibtex-parse-entry'."
   (interactive)
-  (flet ((keyword (str) (intern (concat ":" (downcase str))))
-         (clean-space (str) (replace-regexp-in-string
-                             "[[:space:]\n\r]+" " " str))
-         (strip-delim (str)         ; strip enclosing "..." and {...}
-                     (dolist (pair '((34 . 34) (123 . 125) (123 . 125)))
-                       (when (and (= (aref str 0) (car pair))
-                                  (= (aref str (1- (length str))) (cdr pair)))
-                         (setf str (substring str 1 (1- (length str)))))) str))
+  (let ((keyword (lambda (str) (intern (concat ":" (downcase str)))))
+       (clean-space (lambda (str) (replace-regexp-in-string
+                                   "[[:space:]\n\r]+" " " str)))
+       (strip-delim
+        (lambda (str)       ; strip enclosing "..." and {...}
+          (dolist (pair '((34 . 34) (123 . 125) (123 . 125)))
+            (when (and (= (aref str 0) (car pair))
+                       (= (aref str (1- (length str))) (cdr pair)))
+              (setf str (substring str 1 (1- (length str)))))) str)))
     (push (mapcar
            (lambda (pair)
-             (cons (let ((field (keyword (car pair))))
+             (cons (let ((field (funcall keyword (car pair))))
                      (case field
                        (:=type= :type)
                        (:=key= :key)
                        (otherwise field)))
-                   (clean-space (strip-delim (cdr pair)))))
+                   (funcall clean-space (funcall strip-delim (cdr pair)))))
            (save-excursion (bibtex-beginning-of-entry) (bibtex-parse-entry)))
-          *org-bibtex-entries*)))
+          org-bibtex-entries)))
+
+(defun org-bibtex-read-buffer (buffer)
+  "Read all bibtex entries in BUFFER and save to `org-bibtex-entries'.
+Return the number of saved entries."
+  (interactive "bbuffer: ")
+  (let ((start-length (length org-bibtex-entries)))
+    (with-current-buffer buffer
+      (save-excursion
+       (goto-char (point-max))
+       (while (not (= (point) (point-min)))
+         (backward-char 1)
+         (org-bibtex-read)
+         (bibtex-beginning-of-entry))))
+    (let ((added (- (length org-bibtex-entries) start-length)))
+      (message "parsed %d entries" added)
+      added)))
+
+(defun org-bibtex-read-file (file)
+  "Read FILE with `org-bibtex-read-buffer'."
+  (interactive "ffile: ")
+  (org-bibtex-read-buffer (find-file-noselect file 'nowarn 'rawfile)))
 
 (defun org-bibtex-write ()
-  "Insert a heading built from the first element of `*org-bibtex-entries*'."
+  "Insert a heading built from the first element of `org-bibtex-entries'."
   (interactive)
-  (when (= (length *org-bibtex-entries*) 0)
-    (error "No entries in `*org-bibtex-entries*'."))
-  (let ((entry (pop *org-bibtex-entries*))
-       (org-special-properties nil)) ; avoids errors with `org-entry-put'
-    (flet ((val (field) (cdr (assoc field entry)))
-          (togtag (tag) (org-toggle-tag tag 'on)))
-      (org-insert-heading)
-      (insert (val :title))
-      (org-bibtex-put "TITLE" (val :title))
-      (org-bibtex-put org-bibtex-type-property-name (downcase (val :type)))
-      (dolist (pair entry)
-        (case (car pair)
-          (:title    nil)
-          (:type     nil)
-          (:key      (org-bibtex-put org-bibtex-key-property (cdr pair)))
-         (:keywords (if org-bibtex-tags-are-keywords
-                         (mapc
-                          (lambda (kw)
-                            (togtag
-                             (replace-regexp-in-string
-                              "[^[:alnum:]_@#%]" ""
-                              (replace-regexp-in-string "[ \t]+" "_" kw))))
-                          (split-string (cdr pair) ", *"))
-                      (org-bibtex-put (car pair) (cdr pair))))
-          (otherwise (org-bibtex-put (car pair)  (cdr pair)))))
-      (mapc #'togtag org-bibtex-tags))))
+  (when (= (length org-bibtex-entries) 0)
+    (error "No entries in `org-bibtex-entries'"))
+  (let* ((entry (pop org-bibtex-entries))
+        (org-special-properties nil) ; avoids errors with `org-entry-put'
+        (val (lambda (field) (cdr (assoc field entry))))
+        (togtag (lambda (tag) (org-toggle-tag tag 'on))))
+    (org-insert-heading)
+    (insert (funcall val :title))
+    (org-bibtex-put "TITLE" (funcall val :title))
+    (org-bibtex-put org-bibtex-type-property-name
+                   (downcase (funcall val :type)))
+    (dolist (pair entry)
+      (case (car pair)
+       (:title    nil)
+       (:type     nil)
+       (:key      (org-bibtex-put org-bibtex-key-property (cdr pair)))
+       (:keywords (if org-bibtex-tags-are-keywords
+                      (mapc
+                       (lambda (kw)
+                         (funcall
+                          togtag
+                          (replace-regexp-in-string
+                           "[^[:alnum:]_@#%]" ""
+                           (replace-regexp-in-string "[ \t]+" "_" kw))))
+                       (split-string (cdr pair) ", *"))
+                    (org-bibtex-put (car pair) (cdr pair))))
+       (otherwise (org-bibtex-put (car pair)  (cdr pair)))))
+    (mapc togtag org-bibtex-tags)))
 
 (defun org-bibtex-yank ()
   "If kill ring holds a bibtex entry yank it as an Org-mode headline."
@@ -647,12 +687,21 @@ This uses `bibtex-parse-entry'."
     (with-temp-buffer (yank 1) (setf entry (org-bibtex-read)))
     (if entry
        (org-bibtex-write)
-      (error "yanked text does not appear to contain a bibtex entry"))))
+      (error "Yanked text does not appear to contain a BibTeX entry"))))
+
+(defun org-bibtex-import-from-file (file)
+  "Read bibtex entries from FILE and insert as Org-mode headlines after point."
+  (interactive "ffile: ")
+  (dotimes (_ (org-bibtex-read-file file))
+    (save-excursion (org-bibtex-write))
+    (re-search-forward org-property-end-re)
+    (open-line 1) (forward-char 1)))
 
 (defun org-bibtex-export-to-kill-ring ()
   "Export current headline to kill ring as bibtex entry."
   (interactive)
-  (kill-new (org-bibtex-headline)))
+  (let ((result (org-bibtex-headline)))
+    (kill-new result) result))
 
 (defun org-bibtex-search (string)
   "Search for bibliographical entries in agenda files.
@@ -662,7 +711,7 @@ This function relies `org-search-view' to locate results."
         (org-agenda-search-view-always-boolean t))
     (org-search-view nil
                     (format "%s +{:%s%s:}"
-                            string org-bibtex-prefix
+                            string (or org-bibtex-prefix "")
                             org-bibtex-type-property-name))))
 
 (provide 'org-bibtex)