]> git.donarmstrong.com Git - org-ref.git/commitdiff
add org directory
authorJohn Kitchin <jkitchin@andrew.cmu.edu>
Sun, 3 Aug 2014 17:47:08 +0000 (13:47 -0400)
committerJohn Kitchin <jkitchin@andrew.cmu.edu>
Sun, 3 Aug 2014 17:47:08 +0000 (13:47 -0400)
doi-utils.el [new file with mode: 0644]
doi-utils.org [new file with mode: 0644]
org-ref.org [new file with mode: 0644]
org-show.el [new file with mode: 0644]
org-show.org [new file with mode: 0644]

diff --git a/doi-utils.el b/doi-utils.el
new file mode 100644 (file)
index 0000000..afba18a
--- /dev/null
@@ -0,0 +1,431 @@
+
+;;; doi-utils.el --- get bibtex entries and pdfs from a DOI
+
+;; Copyright(C) 2014 John Kitchin
+
+;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
+;; This file is not currently part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2, or (at
+;; your option) any later version.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program ; see the file COPYING.  If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+;;
+;; Lisp code to generate and update bibtex entries from a DOI, and to
+;; download pdfs from publisher websites from a DOI.
+;;
+;; Package-Requires: ((org-ref))
+
+(require 'json)
+
+(defvar *doi-utils-waiting* t
+  "stores waiting state for url retrieval.")
+
+(defvar *doi-utils-redirect* nil
+  "stores redirect url from a callback function")
+
+(defun doi-utils-redirect-callback (&optional status)
+  "callback for url-retrieve to set the redirect"
+  (when (plist-get status :error)
+    (signal (car (plist-get status :error)) (cdr(plist-get status :error))))
+  (when (plist-get status :redirect) ;  is nil if there none
+    (message "redirects = %s" (plist-get status :redirect))
+    (message "*doi-utils-redirect* set to %s"
+            (setq *doi-utils-redirect* (plist-get status :redirect))))
+  ;; we have done our job, so we are not waiting any more.
+  (setq *doi-utils-waiting* nil))
+
+(defun doi-utils-get-redirect (doi)
+  "get redirect url from dx.doi.org/doi"
+  ;; we are going to wait until the url-retrieve is done
+  (setq *doi-utils-waiting* t)
+  ;; start with no redirect. it will be set in the callback.
+  (setq *doi-utils-redirect* nil) 
+  (url-retrieve 
+   (format "http://dx.doi.org/%s" doi)
+   'doi-utils-redirect-callback)
+  ; I suspect we need to wait here for the asynchronous process to
+  ; finish. we loop and sleep until the callback says it is done via
+  ; `*doi-utils-waiting*'. this works as far as i can tell. Before I
+  ; had to run this a few times to get it to work, which i suspect
+  ; just gave the first one enough time to finish.
+  (while *doi-utils-waiting* (sleep-for 0.1)))
+
+(defvar doi-utils-pdf-url-functions nil
+  "list of functions that return a url to a pdf from a redirect url. Each function takes one argument, the redirect url. The function must return a pdf-url, or nil.")
+
+(defun aps-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://journals.aps.org" *doi-utils-redirect*)
+    (replace-regexp-in-string "/abstract/" "/pdf/" *doi-utils-redirect*)))
+
+(defun science-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.sciencemag.org" *doi-utils-redirect*)
+    (concat *doi-utils-redirect* ".full.pdf")))
+
+(defun nature-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.nature.com" *doi-utils-redirect*)
+    (let ((result *doi-utils-redirect*))
+      (setq result (replace-regexp-in-string "/full/" "/pdf/" result))
+      (replace-regexp-in-string "\.html$" "\.pdf" result))))
+
+(defun doi-utils-get-wiley-pdf-url (redirect-url)
+  "wileyscience direct hides the pdf url in html. we get it out here"
+  (setq *doi-utils-waiting* t)
+  (url-retrieve redirect-url
+               (lambda (status)
+                 (beginning-of-buffer)
+                 (re-search-forward "<iframe id=\"pdfDocument\" src=\"\\([^\"]*\\)\"" nil)
+                 (setq *doi-utils-pdf-url* (match-string 1)
+                       *doi-utils-waiting* nil)))
+  (while *doi-utils-waiting* (sleep-for 0.1))
+  *doi-utils-pdf-url*)
+
+(defun wiley-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://onlinelibrary.wiley.com" *doi-utils-redirect*)
+   (doi-utils-get-wiley-pdf-url (replace-regexp-in-string "/abstract" "/pdf" *doi-utils-redirect*))
+   *doi-utils-pdf-url*))
+
+(defun springer-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://link.springer.com" *doi-utils-redirect*)
+    (replace-regexp-in-string "/article/" "/content/pdf/" (concat *doi-utils-redirect* ".pdf"))))
+
+(defun acs-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://pubs.acs.org" *doi-utils-redirect*)
+    (replace-regexp-in-string "/abs/" "/pdf/" *doi-utils-redirect*)))
+
+(defun iop-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://iopscience.iop.org" *doi-utils-redirect*)
+    (let ((tail (replace-regexp-in-string "^http://iopscience.iop.org" "" *doi-utils-redirect*)))
+      (concat "http://iopscience.iop.org" tail "/pdf" (replace-regexp-in-string "/" "_" tail) ".pdf"))))
+
+(defun jstor-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.jstor.org" *doi-utils-redirect*)
+    (concat (replace-regexp-in-string "/stable/" "/stable/pdfplus/" *doi-utils-redirect*) ".pdf")))
+
+(defun aip-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://scitation.aip.org" *doi-utils-redirect*)
+    ;; get stuff after content
+    (let (p1 p2 s p3)
+      (setq p2 (replace-regexp-in-string "^http://scitation.aip.org/" "" *doi-utils-redirect*))
+      (setq s (split-string p2 "/"))
+      (setq p1 (mapconcat 'identity (-remove-at-indices '(0 6) s) "/"))
+      (setq p3 (concat "/" (nth 0 s) (nth 1 s) "/" (nth 2 s) "/" (nth 3 s)))
+      (format "http://scitation.aip.org/deliver/fulltext/%s.pdf?itemId=/%s&mimeType=pdf&containerItemId=%s"
+             p1 p2 p3))))
+
+(defun tandfonline-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.tandfonline.com" *doi-utils-redirect*)
+    (replace-regexp-in-string "/abs/\\|/full/" "/pdf/" *doi-utils-redirect*)))
+
+(defun ecs-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://jes.ecsdl.org" *doi-utils-redirect*)
+    (replace-regexp-in-string "\.abstract$" ".full.pdf" *doi-utils-redirect*)))
+
+(defun ecst-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://ecst.ecsdl.org" *doi-utils-redirect*)
+    (concat *doi-utils-redirect* ".full.pdf")))
+
+(defun rsc-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://pubs.rsc.org" *doi-utils-redirect*)
+    (let ((url (downcase *doi-utils-redirect*)))
+      (setq url (replace-regexp-in-string "articlelanding" "articlepdf" url))
+      url)))
+
+(defvar *doi-utils-pdf-url* nil
+  "stores url to pdf download from a callback function")
+
+(defun doi-utils-get-science-direct-pdf-url (redirect-url)
+  "science direct hides the pdf url in html. we get it out here"
+  (setq *doi-utils-waiting* t)
+  (url-retrieve redirect-url
+               (lambda (status)
+                 (beginning-of-buffer)
+                 (re-search-forward "pdfurl=\"\\([^\"]*\\)\"" nil t)
+                 (setq *doi-utils-pdf-url* (match-string 1)
+                       *doi-utils-waiting* nil)))
+  (while *doi-utils-waiting* (sleep-for 0.1))
+  *doi-utils-pdf-url*)
+
+
+(defun science-direct-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.sciencedirect.com" *doi-utils-redirect*)
+    (doi-utils-get-science-direct-pdf-url *doi-utils-redirect*)
+    *doi-utils-pdf-url*))
+
+;; sometimes I get
+;; http://linkinghub.elsevier.com/retrieve/pii/S0927025609004558
+;; which actually redirect to
+;; http://www.sciencedirect.com/science/article/pii/S0927025609004558
+(defun linkinghub-elsevier-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://linkinghub.elsevier.com/retrieve" *doi-utils-redirect*)
+    (let ((second-redirect (replace-regexp-in-string
+                           "http://linkinghub.elsevier.com/retrieve"
+                           "http://www.sciencedirect.com/science/article"
+                           *doi-utils-redirect*)))
+      (message "getting pdf url from %s" second-redirect)
+      ;(doi-utils-get-science-direct-pdf-url second-redirect)
+      *doi-utils-pdf-url*)))
+
+(defun pnas-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.pnas.org" *doi-utils-redirect*)
+    (concat *doi-utils-redirect* ".full.pdf?with-ds=yes")))
+
+(setq doi-utils-pdf-url-functions
+      (list
+       'aps-pdf-url
+       'science-pdf-url
+       'nature-pdf-url
+       'wiley-pdf-url       
+       'springer-pdf-url
+       'acs-pdf-url
+       'iop-pdf-url
+       'jstor-pdf-url
+       'aip-pdf-url
+       'science-direct-pdf-url
+       'linkinghub-elsevier-pdf-url
+       'tandfonline-pdf-url
+       'ecs-pdf-url
+       'ecst-pdf-url
+       'rsc-pdf-url
+       'pnas-pdf-url))
+
+(defun doi-utils-get-pdf-url (doi)
+  "returns a url to a pdf for the doi if one can be
+calculated. Loops through the functions in `doi-utils-pdf-url-functions'
+until one is found"
+  (doi-utils-get-redirect doi)
+  
+  (unless *doi-utils-redirect*
+    (error "No redirect found for %s" doi))
+  (message "applying functions")
+  (catch 'pdf-url
+    (dolist (func doi-utils-pdf-url-functions)
+     (message "calling %s" func)
+      (let ((this-pdf-url (funcall func *doi-utils-redirect*)))
+(message "t: %s" this-pdf-url)
+       (when this-pdf-url
+          (message "found pdf url: %s" this-pdf-url)
+         (throw 'pdf-url this-pdf-url))))))
+
+(defun doi-utils-get-bibtex-entry-pdf ()
+  "download pdf for entry at point if the pdf does not already
+exist locally. The entry must have a doi. The pdf will be saved
+to `org-ref-pdf-directory', by the name %s.pdf where %s is the
+bibtex label. Files will not be overwritten. The pdf will be
+checked to make sure it is a pdf, and not some html failure
+page. you must have permission to access the pdf. We open the pdf
+at the end."
+  (interactive)
+  (save-excursion
+    (bibtex-beginning-of-entry) 
+    (let (;; get doi, removing http://dx.doi.org/ if it is there.
+         (doi (replace-regexp-in-string
+               "http://dx.doi.org/" ""
+               (bibtex-autokey-get-field "doi")))             
+         (key)
+         (pdf-url)
+         (pdf-file)
+         (content))
+      ;; get the key and build pdf filename.
+      (re-search-forward bibtex-entry-maybe-empty-head)
+      (setq key (match-string bibtex-key-in-head))
+      (setq pdf-file (concat org-ref-pdf-directory key ".pdf"))
+
+      ;; now get file if needed.
+      (when (and doi (not (file-exists-p pdf-file)))
+       (setq pdf-url (doi-utils-get-pdf-url doi))
+       (if pdf-url
+           (progn
+             (url-copy-file pdf-url pdf-file)
+             ;; now check if we got a pdf
+             (with-temp-buffer
+               (insert-file-contents pdf-file)
+               ;; PDFS start with %PDF-1.x as the first few characters.
+               (if (not (string= (buffer-substring 1 6) "%PDF-"))
+                   (progn
+                     (message "%s" (buffer-string))
+                     (delete-file pdf-file))
+                 (message "%s saved" pdf-file)))
+       
+             (when (file-exists-p pdf-file)
+               (org-open-file pdf-file)))
+         (message "No pdf-url found for %s at %s" doi *doi-utils-redirect* ))
+         pdf-file))))
+
+(defun doi-utils-get-json-metadata (doi)
+  (let ((url-request-method "GET") 
+       (url-mime-accept-string "application/citeproc+json")
+       (json-object-type 'plist))
+    (with-current-buffer
+       (url-retrieve-synchronously
+        (concat "http://dx.doi.org/" doi))
+      (json-read-from-string (buffer-substring url-http-end-of-headers (point-max))))))       
+
+(defun doi-utils-expand-template (s)
+  "expand a template containing %{} with the eval of its contents"
+  (replace-regexp-in-string "%{\\([^}]+\\)}"
+                            (lambda (arg)
+                              (let ((sexp (substring arg 2 -1)))
+                                (format "%s" (eval (read sexp))))) s))
+
+(defun doi-utils-doi-to-bibtex-string (doi)
+  "return a bibtex entry as a string for the doi. Only articles are currently supported"
+  (let (type
+       results
+       author
+       title
+       journal
+       year
+       volume
+       number
+       pages
+       month
+       url
+       json-data)
+    (setq results (doi-utils-get-json-metadata doi)
+         json-data (format "%s" results)
+         type (plist-get results :type)
+         author (mapconcat (lambda (x) (concat (plist-get x :given) " " (plist-get x :family)))
+                           (plist-get results :author) " and ")
+         title (plist-get results :title)
+         journal (plist-get results :container-title)
+         volume (plist-get results :volume)
+         issue (plist-get results :issue)
+         year (elt (elt (plist-get (plist-get results :issued) :date-parts) 0) 0)
+         pages (plist-get results :page)
+         doi (plist-get results :DOI)
+         url (plist-get results :URL))
+    (cond
+     ((string= type "journal-article")
+      (doi-utils-expand-template "@article{,
+  author =      {%{author}},
+  title =       {%{title}},
+  journal =     {%{journal}},
+  year =        {%{year}},
+  volume =      {%{volume}},
+  number =      {%{issue}},
+  pages =       {%{pages}},
+  doi =          {%{doi}},
+  url =          {%{url}},
+}"))
+    (t (message-box "%s not supported yet." type)))))
+
+(defun doi-utils-insert-bibtex-entry-from-doi (doi)
+  "insert bibtex entry from a doi. Also cleans entry using
+org-ref, and tries to download the corresponding pdf."
+  (interactive "sDOI: ")
+  (insert (doi-utils-doi-to-bibtex-string doi))
+  (backward-char)
+  (if (bibtex-key-in-head nil)
+       (org-ref-clean-bibtex-entry t)
+     (org-ref-clean-bibtex-entry))
+   ;; try to get pdf
+   (doi-utils-get-bibtex-entry-pdf)
+   (save-selected-window
+     (org-ref-open-bibtex-notes)))
+
+(defun doi-utils-add-bibtex-entry-from-doi (doi)
+  "add entry to end of first entry in `org-ref-default-bibliography'."
+  (interactive "sDOI: ")
+  (find-file (car org-ref-default-bibliography))
+  (end-of-buffer)
+  (insert "\n\n")
+  (doi-utils-insert-bibtex-entry-from-doi doi))
+
+(defun doi-utils-add-bibtex-entry-from-region (start end)
+  "add entry assuming region is a doi to end of first entry in `org-ref-default-bibliography'."
+  (interactive "r")
+  (let ((doi (buffer-substring start end)))
+    (find-file (car org-ref-default-bibliography))
+    (end-of-buffer)
+    (insert "\n")
+    (doi-utils-insert-bibtex-entry-from-doi doi)))
+
+(defun bibtex-set-field (field value)
+  "set field to value in bibtex file. create field if it does not exist"
+  (interactive "sfield: \nsvalue: ")
+  (bibtex-beginning-of-entry)
+  (let ((found))
+    (if (setq found (bibtex-search-forward-field field t))
+       ;; we found a field
+       (progn
+         (goto-char (car (cdr found)))
+         (when value
+           (bibtex-kill-field)
+           (bibtex-make-field field)
+           (backward-char)
+           (insert value)))
+      ;; make a new field
+      (message "new field being made")
+      (bibtex-beginning-of-entry)
+      (forward-line) (beginning-of-line)
+      (bibtex-next-field nil)
+      (forward-char)
+      (bibtex-make-field field)
+      (backward-char)
+      (insert value))))
+
+(defun plist-get-keys (plist)
+   "return keys in a plist"
+  (loop
+   for key in results by #'cddr collect key))
+
+(defun doi-utils-update-bibtex-entry-from-doi (doi)
+  "update fields in a bibtex entry from the doi. Every field will be updated, so previous changes will be lost."
+  (interactive (list
+               (or (replace-regexp-in-string "http://dx.doi.org/" "" (bibtex-autokey-get-field "doi"))
+                   (read-string "DOI: "))))
+  (let* ((results (doi-utils-get-json-metadata doi))
+        (type (plist-get results :type))
+        (author (mapconcat
+                 (lambda (x) (concat (plist-get x :given)
+                                   " " (plist-get x :family)))
+                 (plist-get results :author) " and "))
+        (title (plist-get results :title))
+        (journal (plist-get results :container-title))
+        (year (format "%s"
+                      (elt
+                       (elt
+                        (plist-get
+                         (plist-get results :issued) :date-parts) 0) 0)))      
+       (volume (plist-get results :volume))
+       (number (or (plist-get results :issue) ""))
+       (pages (or (plist-get results :page) ""))
+       (url (or (plist-get results :URL) ""))
+       (doi (plist-get results :DOI)))
+    
+    ;; map the json fields to bibtex fields. The code each field is mapped to is evaluated.
+    (setq mapping '((:author . (bibtex-set-field "author" author))
+                   (:title . (bibtex-set-field "title" title))
+                   (:container-title . (bibtex-set-field "journal" journal))
+                   (:issued . (bibtex-set-field "year" year))
+                   (:volume . (bibtex-set-field "volume" volume))
+                   (:issue . (bibtex-set-field "number" number))
+                   (:page . (bibtex-set-field "pages" pages))
+                   (:DOI . (bibtex-set-field "doi" doi))
+                   (:URL . (bibtex-set-field "url" url))))
+
+    ;; now we have code to run for each entry. we map over them and evaluate the code
+    (mapcar
+     (lambda (key)
+       (eval (cdr (assoc key mapping))))
+     (plist-get-keys results)))
+  
+  ; reclean entry, but keep key if it exists.
+  (if (bibtex-key-in-head)
+      (org-ref-clean-bibtex-entry t)
+    (org-ref-clean-bibtex-entry)))
+
+(provide 'doi-utils)
diff --git a/doi-utils.org b/doi-utils.org
new file mode 100644 (file)
index 0000000..fa49976
--- /dev/null
@@ -0,0 +1,656 @@
+#+TITLE: DOI utilities for making bibtex entries and downloading pdfs
+
+This package provides functionality to download PDFs and bibtex entries from a DOI, as well as to update a bibtex entry from a DOI. It depends slightly on org-ref, to determine where to save pdf files too, and where to insert bibtex entries in the default bibliography.
+
+The principle commands you will use from here are:
+
+- doi-utils-get-bibtex-entry-pdf with the cursor in a bibtex entry.
+- doi-utils-insert-bibtex-entry-from-doi to insert a bibtex entry at your cursor, clean it and try to get a pdf.
+- doi-utils-add-bibtex-entry-from-doi to add an entry to your default bibliography (cleaned with pdf if possible).
+- doi-utils-add-bibtex-entry-from-region to add an entry from a highlighed doi to your default bibliography.
+- doi-utils-update-bibtex-entry-from-doi with cursor in an entry to update its fields.
+
+* Header
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+;;; doi-utils.el --- get bibtex entries and pdfs from a DOI
+
+;; Copyright(C) 2014 John Kitchin
+
+;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
+;; This file is not currently part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2, or (at
+;; your option) any later version.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program ; see the file COPYING.  If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+;;
+;; Lisp code to generate and update bibtex entries from a DOI, and to
+;; download pdfs from publisher websites from a DOI.
+;;
+;; Package-Requires: ((org-ref))
+
+(require 'json)
+#+END_SRC
+
+* Getting pdf files from a DOI
+The idea here is simple. When you visit http://dx.doi.org/doi, you get redirected to the journal site. Once you have the url for the article, you can usually compute the url to the pdf, or find it in the page. Then you simply download it. 
+
+There are some subtleties in doing this that are described here. To get the redirect, we have to use url-retrieve, and a callback function. The callback does not return anything, so we communicate through global variables. url-retrieve is asynchronous, so we have to make sure to wait for it to finish. 
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defvar *doi-utils-waiting* t
+  "stores waiting state for url retrieval.")
+
+(defvar *doi-utils-redirect* nil
+  "stores redirect url from a callback function")
+
+(defun doi-utils-redirect-callback (&optional status)
+  "callback for url-retrieve to set the redirect"
+  (when (plist-get status :error)
+    (signal (car (plist-get status :error)) (cdr(plist-get status :error))))
+  (when (plist-get status :redirect) ;  is nil if there none
+    (message "redirects = %s" (plist-get status :redirect))
+    (message "*doi-utils-redirect* set to %s"
+            (setq *doi-utils-redirect* (plist-get status :redirect))))
+  ;; we have done our job, so we are not waiting any more.
+  (setq *doi-utils-waiting* nil))
+#+END_SRC
+
+To actually get the redirect we use url-retrieve like this.
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun doi-utils-get-redirect (doi)
+  "get redirect url from dx.doi.org/doi"
+  ;; we are going to wait until the url-retrieve is done
+  (setq *doi-utils-waiting* t)
+  ;; start with no redirect. it will be set in the callback.
+  (setq *doi-utils-redirect* nil) 
+  (url-retrieve 
+   (format "http://dx.doi.org/%s" doi)
+   'doi-utils-redirect-callback)
+  ; I suspect we need to wait here for the asynchronous process to
+  ; finish. we loop and sleep until the callback says it is done via
+  ; `*doi-utils-waiting*'. this works as far as i can tell. Before I
+  ; had to run this a few times to get it to work, which i suspect
+  ; just gave the first one enough time to finish.
+  (while *doi-utils-waiting* (sleep-for 0.1)))
+#+END_SRC
+
+Once we have a redirect for a particular doi, we need to compute the url to the pdf. We do this with a series of functions. Each function takes a single argument, the redirect url. If it knows how to compute the pdf url it does, and returns it. We store the functions in a variable:
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defvar doi-utils-pdf-url-functions nil
+  "list of functions that return a url to a pdf from a redirect url. Each function takes one argument, the redirect url. The function must return a pdf-url, or nil.")
+#+END_SRC
+
+** APS journals
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun aps-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://journals.aps.org" *doi-utils-redirect*)
+    (replace-regexp-in-string "/abstract/" "/pdf/" *doi-utils-redirect*)))
+#+END_SRC
+
+** Science
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun science-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.sciencemag.org" *doi-utils-redirect*)
+    (concat *doi-utils-redirect* ".full.pdf")))
+#+END_SRC
+
+** Nature
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun nature-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.nature.com" *doi-utils-redirect*)
+    (let ((result *doi-utils-redirect*))
+      (setq result (replace-regexp-in-string "/full/" "/pdf/" result))
+      (replace-regexp-in-string "\.html$" "\.pdf" result))))
+#+END_SRC
+
+** Wiley
+http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/abstract
+http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/pdf
+
+It appears that it is not enough to use the pdf url above. That takes you to an html page. The actual link to teh pdf is embedded in that page. This is how ScienceDirect does things too.
+
+This is where the link is hidden:
+
+<iframe id="pdfDocument" src="http://onlinelibrary.wiley.com/store/10.1002/anie.201402680/asset/6397_ftp.pdf?v=1&amp;t=hwut2142&amp;s=d4bb3cd4ad20eb733836717f42346ffb34017831" width="100%" height="675px"></iframe>
+
+
+
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun doi-utils-get-wiley-pdf-url (redirect-url)
+  "wileyscience direct hides the pdf url in html. we get it out here"
+  (setq *doi-utils-waiting* t)
+  (url-retrieve redirect-url
+               (lambda (status)
+                 (beginning-of-buffer)
+                 (re-search-forward "<iframe id=\"pdfDocument\" src=\"\\([^\"]*\\)\"" nil)
+                 (setq *doi-utils-pdf-url* (match-string 1)
+                       ,*doi-utils-waiting* nil)))
+  (while *doi-utils-waiting* (sleep-for 0.1))
+  ,*doi-utils-pdf-url*)
+
+(defun wiley-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://onlinelibrary.wiley.com" *doi-utils-redirect*)
+   (doi-utils-get-wiley-pdf-url (replace-regexp-in-string "/abstract" "/pdf" *doi-utils-redirect*))
+   ,*doi-utils-pdf-url*))
+#+END_SRC
+
+** Springer
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun springer-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://link.springer.com" *doi-utils-redirect*)
+    (replace-regexp-in-string "/article/" "/content/pdf/" (concat *doi-utils-redirect* ".pdf"))))
+#+END_SRC
+
+** ACS
+here is a typical url http://pubs.acs.org/doi/abs/10.1021/nl500037x
+the pdf is found at http://pubs.acs.org/doi/pdf/10.1021/nl500037x
+
+we just change /abs/ to /pdf/.
+
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun acs-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://pubs.acs.org" *doi-utils-redirect*)
+    (replace-regexp-in-string "/abs/" "/pdf/" *doi-utils-redirect*)))
+#+END_SRC
+
+#+BEGIN_SRC emacs-lisp
+(acs-pdf-url  "http://pubs.acs.org/doi/abs/10.1021/nl500037x")
+#+END_SRC
+
+#+RESULTS:
+: http://pubs.acs.org/doi/pdf/10.1021/nl500037x
+
+** IOP
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun iop-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://iopscience.iop.org" *doi-utils-redirect*)
+    (let ((tail (replace-regexp-in-string "^http://iopscience.iop.org" "" *doi-utils-redirect*)))
+      (concat "http://iopscience.iop.org" tail "/pdf" (replace-regexp-in-string "/" "_" tail) ".pdf"))))
+#+END_SRC
+
+** JSTOR
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun jstor-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.jstor.org" *doi-utils-redirect*)
+    (concat (replace-regexp-in-string "/stable/" "/stable/pdfplus/" *doi-utils-redirect*) ".pdf")))
+#+END_SRC
+
+** AIP 
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun aip-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://scitation.aip.org" *doi-utils-redirect*)
+    ;; get stuff after content
+    (let (p1 p2 s p3)
+      (setq p2 (replace-regexp-in-string "^http://scitation.aip.org/" "" *doi-utils-redirect*))
+      (setq s (split-string p2 "/"))
+      (setq p1 (mapconcat 'identity (-remove-at-indices '(0 6) s) "/"))
+      (setq p3 (concat "/" (nth 0 s) (nth 1 s) "/" (nth 2 s) "/" (nth 3 s)))
+      (format "http://scitation.aip.org/deliver/fulltext/%s.pdf?itemId=/%s&mimeType=pdf&containerItemId=%s"
+             p1 p2 p3))))
+#+END_SRC
+
+** Taylor and Francis
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun tandfonline-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.tandfonline.com" *doi-utils-redirect*)
+    (replace-regexp-in-string "/abs/\\|/full/" "/pdf/" *doi-utils-redirect*)))
+#+END_SRC
+** ECS
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun ecs-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://jes.ecsdl.org" *doi-utils-redirect*)
+    (replace-regexp-in-string "\.abstract$" ".full.pdf" *doi-utils-redirect*)))
+#+END_SRC
+
+http://ecst.ecsdl.org/content/25/2/2769
+http://ecst.ecsdl.org/content/25/2/2769.full.pdf
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun ecst-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://ecst.ecsdl.org" *doi-utils-redirect*)
+    (concat *doi-utils-redirect* ".full.pdf")))
+#+END_SRC
+
+
+** RSC
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun rsc-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://pubs.rsc.org" *doi-utils-redirect*)
+    (let ((url (downcase *doi-utils-redirect*)))
+      (setq url (replace-regexp-in-string "articlelanding" "articlepdf" url))
+      url)))
+#+END_SRC
+
+** Elsevier/ScienceDirect
+You cannot compute these pdf links; they are embedded in the redirected pages.
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defvar *doi-utils-pdf-url* nil
+  "stores url to pdf download from a callback function")
+
+(defun doi-utils-get-science-direct-pdf-url (redirect-url)
+  "science direct hides the pdf url in html. we get it out here"
+  (setq *doi-utils-waiting* t)
+  (url-retrieve redirect-url
+               (lambda (status)
+                 (beginning-of-buffer)
+                 (re-search-forward "pdfurl=\"\\([^\"]*\\)\"" nil t)
+                 (setq *doi-utils-pdf-url* (match-string 1)
+                       ,*doi-utils-waiting* nil)))
+  (while *doi-utils-waiting* (sleep-for 0.1))
+  ,*doi-utils-pdf-url*)
+
+
+(defun science-direct-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.sciencedirect.com" *doi-utils-redirect*)
+    (doi-utils-get-science-direct-pdf-url *doi-utils-redirect*)
+    ,*doi-utils-pdf-url*))
+
+;; sometimes I get
+;; http://linkinghub.elsevier.com/retrieve/pii/S0927025609004558
+;; which actually redirect to
+;; http://www.sciencedirect.com/science/article/pii/S0927025609004558
+(defun linkinghub-elsevier-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://linkinghub.elsevier.com/retrieve" *doi-utils-redirect*)
+    (let ((second-redirect (replace-regexp-in-string
+                           "http://linkinghub.elsevier.com/retrieve"
+                           "http://www.sciencedirect.com/science/article"
+                           ,*doi-utils-redirect*)))
+      (message "getting pdf url from %s" second-redirect)
+      ;(doi-utils-get-science-direct-pdf-url second-redirect)
+      ,*doi-utils-pdf-url*)))
+#+END_SRC
+
+** PNAS
+http://www.pnas.org/content/early/2014/05/08/1319030111
+http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf
+
+with supporting info
+http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf+html?with-ds=yes
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun pnas-pdf-url (*doi-utils-redirect*)
+  (when (string-match "^http://www.pnas.org" *doi-utils-redirect*)
+    (concat *doi-utils-redirect* ".full.pdf?with-ds=yes")))
+#+END_SRC
+
+** Add all functions
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(setq doi-utils-pdf-url-functions
+      (list
+       'aps-pdf-url
+       'science-pdf-url
+       'nature-pdf-url
+       'wiley-pdf-url       
+       'springer-pdf-url
+       'acs-pdf-url
+       'iop-pdf-url
+       'jstor-pdf-url
+       'aip-pdf-url
+       'science-direct-pdf-url
+       'linkinghub-elsevier-pdf-url
+       'tandfonline-pdf-url
+       'ecs-pdf-url
+       'ecst-pdf-url
+       'rsc-pdf-url
+       'pnas-pdf-url))
+#+END_SRC
+
+** Get the pdf url for a doi
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun doi-utils-get-pdf-url (doi)
+  "returns a url to a pdf for the doi if one can be
+calculated. Loops through the functions in `doi-utils-pdf-url-functions'
+until one is found"
+  (doi-utils-get-redirect doi)
+  
+  (unless *doi-utils-redirect*
+    (error "No redirect found for %s" doi))
+  (message "applying functions")
+  (catch 'pdf-url
+    (dolist (func doi-utils-pdf-url-functions)
+     (message "calling %s" func)
+      (let ((this-pdf-url (funcall func *doi-utils-redirect*)))
+(message "t: %s" this-pdf-url)
+       (when this-pdf-url
+          (message "found pdf url: %s" this-pdf-url)
+         (throw 'pdf-url this-pdf-url))))))
+#+END_SRC
+
+#+RESULTS:
+: doi-utils-get-pdf-url
+
+
+#+BEGIN_SRC emacs-lisp
+(doi-utils-get-pdf-url "10.1126/science.1158722")
+#+END_SRC
+
+#+RESULTS:
+: http://www.sciencemag.org/content/321/5890/792.full.pdf
+
+#+BEGIN_SRC emacs-lisp
+(doi-utils-get-pdf-url  "10.1021/nl500037x")
+#+END_SRC
+
+#+RESULTS:
+: http://pubs.acs.org/doi/pdf/10.1021/nl500037x
+
+
+#+BEGIN_SRC emacs-lisp
+(doi-utils-get-pdf-url  "10.1002/anie.201402680")
+#+END_SRC
+
+#+RESULTS:
+: http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/pdf
+
+** Finally, download the pdf
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun doi-utils-get-bibtex-entry-pdf ()
+  "download pdf for entry at point if the pdf does not already
+exist locally. The entry must have a doi. The pdf will be saved
+to `org-ref-pdf-directory', by the name %s.pdf where %s is the
+bibtex label. Files will not be overwritten. The pdf will be
+checked to make sure it is a pdf, and not some html failure
+page. you must have permission to access the pdf. We open the pdf
+at the end."
+  (interactive)
+  (save-excursion
+    (bibtex-beginning-of-entry) 
+    (let (;; get doi, removing http://dx.doi.org/ if it is there.
+         (doi (replace-regexp-in-string
+               "http://dx.doi.org/" ""
+               (bibtex-autokey-get-field "doi")))             
+         (key)
+         (pdf-url)
+         (pdf-file)
+         (content))
+      ;; get the key and build pdf filename.
+      (re-search-forward bibtex-entry-maybe-empty-head)
+      (setq key (match-string bibtex-key-in-head))
+      (setq pdf-file (concat org-ref-pdf-directory key ".pdf"))
+
+      ;; now get file if needed.
+      (when (and doi (not (file-exists-p pdf-file)))
+       (setq pdf-url (doi-utils-get-pdf-url doi))
+       (if pdf-url
+           (progn
+             (url-copy-file pdf-url pdf-file)
+             ;; now check if we got a pdf
+             (with-temp-buffer
+               (insert-file-contents pdf-file)
+               ;; PDFS start with %PDF-1.x as the first few characters.
+               (if (not (string= (buffer-substring 1 6) "%PDF-"))
+                   (progn
+                     (message "%s" (buffer-string))
+                     (delete-file pdf-file))
+                 (message "%s saved" pdf-file)))
+       
+             (when (file-exists-p pdf-file)
+               (org-open-file pdf-file)))
+         (message "No pdf-url found for %s at %s" doi *doi-utils-redirect* ))
+         pdf-file))))
+#+END_SRC
+
+* Getting bibtex entries from a DOI
+
+I [[http://homepages.see.leeds.ac.uk/~eeaol/notes/2013/02/doi-metadata/][found]] you can download metadata about a DOI from http://dx.doi.org. You just have to construct the right http request to get it. Here is a function that gets the metadata as a plist in emacs.
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun doi-utils-get-json-metadata (doi)
+  (let ((url-request-method "GET") 
+       (url-mime-accept-string "application/citeproc+json")
+       (json-object-type 'plist))
+    (with-current-buffer
+       (url-retrieve-synchronously
+        (concat "http://dx.doi.org/" doi))
+      (json-read-from-string (buffer-substring url-http-end-of-headers (point-max))))))       
+#+END_SRC
+
+#+RESULTS:
+: doi-utils-get-json-metadata
+
+For example:
+#+BEGIN_SRC emacs-lisp
+(doi-utils-get-json-metadata "10.1103/PhysRevLett.99.016105")
+#+END_SRC
+
+#+RESULTS:
+| :volume | 99 | :indexed | (:timestamp 1399964115538.0 :date-parts [[2014 5 13]]) | :publisher | American Physical Society (APS) | :source | CrossRef | :URL | http://dx.doi.org/10.1103/PhysRevLett.99.016105 | :ISSN | [0031-9007 1079-7114] | :DOI | 10.1103/physrevlett.99.016105 | :type | journal-article | :title | Scaling Properties of Adsorption Energies for Hydrogen-Containing Molecules on Transition-Metal Surfaces | :issue | 1 | :deposited | (:timestamp 1313712000000.0 :date-parts [[2011 8 19]]) | :reference-count | 26 | :container-title | Phys. Rev. Lett. | :author | [(:given F. :family Abild-Pedersen) (:given J. :family Greeley) (:given F. :family Studt) (:given J. :family Rossmeisl) (:given T. :family Munter) (:given P. :family Moses) (:given E. :family Skúlason) (:given T. :family Bligaard) (:given J. :family Nørskov)] | :prefix | http://id.crossref.org/prefix/10.1103 | :score | 1.0 | :issued | (:date-parts [[2007 7]]) | :subject | [Physics and Astronomy(all)] | :subtitle | [] |
+
+We can use that data to construct a bibtex entry. We do that by defining a template, and filling it in. I wrote this template expansion code which makes it easy to substitute values like %{} in emacs lisp.
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun doi-utils-expand-template (s)
+  "expand a template containing %{} with the eval of its contents"
+  (replace-regexp-in-string "%{\\([^}]+\\)}"
+                            (lambda (arg)
+                              (let ((sexp (substring arg 2 -1)))
+                                (format "%s" (eval (read sexp))))) s))
+#+END_SRC
+
+Now we define a function that fills in that template from the metadata.
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun doi-utils-doi-to-bibtex-string (doi)
+  "return a bibtex entry as a string for the doi. Only articles are currently supported"
+  (let (type
+       results
+       author
+       title
+       journal
+       year
+       volume
+       number
+       pages
+       month
+       url
+       json-data)
+    (setq results (doi-utils-get-json-metadata doi)
+         json-data (format "%s" results)
+         type (plist-get results :type)
+         author (mapconcat (lambda (x) (concat (plist-get x :given) " " (plist-get x :family)))
+                           (plist-get results :author) " and ")
+         title (plist-get results :title)
+         journal (plist-get results :container-title)
+         volume (plist-get results :volume)
+         issue (plist-get results :issue)
+         year (elt (elt (plist-get (plist-get results :issued) :date-parts) 0) 0)
+         pages (plist-get results :page)
+         doi (plist-get results :DOI)
+         url (plist-get results :URL))
+    (cond
+     ((string= type "journal-article")
+      (doi-utils-expand-template "@article{,
+  author =      {%{author}},
+  title =       {%{title}},
+  journal =     {%{journal}},
+  year =        {%{year}},
+  volume =      {%{volume}},
+  number =      {%{issue}},
+  pages =       {%{pages}},
+  doi =          {%{doi}},
+  url =          {%{url}},
+}"))
+    (t (message-box "%s not supported yet." type)))))
+#+END_SRC
+
+#+RESULTS:
+: doi-utils-doi-to-bibtex-string
+
+To see that in action:
+#+BEGIN_SRC emacs-lisp
+(doi-utils-doi-to-bibtex-string "10.1103/PhysRevLett.99.016105")
+#+END_SRC
+
+#+RESULTS:
+#+begin_example
+@article{,
+  author =      {F. Abild-Pedersen and J. Greeley and F. Studt and J. Rossmeisl and T. Munter and P. Moses and E. Skúlason and T. Bligaard and J. Nørskov},
+  title =       {Scaling Properties of Adsorption Energies for Hydrogen-Containing Molecules on Transition-Metal Surfaces},
+  journal =     {Phys. Rev. Lett.},
+  year =        {2007},
+  volume =      {99},
+  number =      {1},
+  pages =       {nil},
+  doi =          {10.1103/physrevlett.99.016105},
+  url =          {http://dx.doi.org/10.1103/PhysRevLett.99.016105},
+}
+#+end_example
+
+That is just the string for the entry. To be useful, we need a function that inserts the string into a buffer. This function will insert the string at the cursor, clean the entry, try to get the pdf, and create a notes entry for you.
+
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun doi-utils-insert-bibtex-entry-from-doi (doi)
+  "insert bibtex entry from a doi. Also cleans entry using
+org-ref, and tries to download the corresponding pdf."
+  (interactive "sDOI: ")
+  (insert (doi-utils-doi-to-bibtex-string doi))
+  (backward-char)
+  (if (bibtex-key-in-head nil)
+       (org-ref-clean-bibtex-entry t)
+     (org-ref-clean-bibtex-entry))
+   ;; try to get pdf
+   (doi-utils-get-bibtex-entry-pdf)
+   (save-selected-window
+     (org-ref-open-bibtex-notes)))
+#+END_SRC
+
+It may be you are in some other place when you want to add a bibtex entry. This next function will open the first entry in org-ref-default-bibliography go to the end, and add the entry. You can sort it later.
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun doi-utils-add-bibtex-entry-from-doi (doi)
+  "add entry to end of first entry in `org-ref-default-bibliography'."
+  (interactive "sDOI: ")
+  (find-file (car org-ref-default-bibliography))
+  (end-of-buffer)
+  (insert "\n\n")
+  (doi-utils-insert-bibtex-entry-from-doi doi))
+#+END_SRC
+
+It may be you want to just highlight a doi, and then add it. Here is that function.
+
+#+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
+(defun doi-utils-add-bibtex-entry-from-region (start end)
+  "add entry assuming region is a doi to end of first entry in `org-ref-default-bibliography'."
+  (interactive "r")
+  (let ((doi (buffer-substring start end)))
+    (find-file (car org-ref-default-bibliography))
+    (end-of-buffer)
+    (insert "\n")
+    (doi-utils-insert-bibtex-entry-from-doi doi)))
+#+END_SRC
+
+#+RESULTS:
+: doi-utils-add-bibtex-entry-from-region
+
+* Updating bibtex entries
+I wrote this code because it is pretty common for me to copy bibtex entries from ASAP articles that are incomplete, e.g. no page numbers because it is not in print yet. I wanted a convenient way to update an entry from its DOI. Basically, we get the metadata, and update the fields in the entry.
+
+There is not bibtex set field function, so I wrote this one.
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun bibtex-set-field (field value)
+  "set field to value in bibtex file. create field if it does not exist"
+  (interactive "sfield: \nsvalue: ")
+  (bibtex-beginning-of-entry)
+  (let ((found))
+    (if (setq found (bibtex-search-forward-field field t))
+       ;; we found a field
+       (progn
+         (goto-char (car (cdr found)))
+         (when value
+           (bibtex-kill-field)
+           (bibtex-make-field field)
+           (backward-char)
+           (insert value)))
+      ;; make a new field
+      (message "new field being made")
+      (bibtex-beginning-of-entry)
+      (forward-line) (beginning-of-line)
+      (bibtex-next-field nil)
+      (forward-char)
+      (bibtex-make-field field)
+      (backward-char)
+      (insert value))))
+#+END_SRC
+
+The updating function looks like this. We get all the keys from the json plist metadata, and update the fields if they exist.
+
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(defun plist-get-keys (plist)
+   "return keys in a plist"
+  (loop
+   for key in results by #'cddr collect key))
+
+(defun doi-utils-update-bibtex-entry-from-doi (doi)
+  "update fields in a bibtex entry from the doi. Every field will be updated, so previous changes will be lost."
+  (interactive (list
+               (or (replace-regexp-in-string "http://dx.doi.org/" "" (bibtex-autokey-get-field "doi"))
+                   (read-string "DOI: "))))
+  (let* ((results (doi-utils-get-json-metadata doi))
+        (type (plist-get results :type))
+        (author (mapconcat
+                 (lambda (x) (concat (plist-get x :given)
+                                   " " (plist-get x :family)))
+                 (plist-get results :author) " and "))
+        (title (plist-get results :title))
+        (journal (plist-get results :container-title))
+        (year (format "%s"
+                      (elt
+                       (elt
+                        (plist-get
+                         (plist-get results :issued) :date-parts) 0) 0)))      
+       (volume (plist-get results :volume))
+       (number (or (plist-get results :issue) ""))
+       (pages (or (plist-get results :page) ""))
+       (url (or (plist-get results :URL) ""))
+       (doi (plist-get results :DOI)))
+    
+    ;; map the json fields to bibtex fields. The code each field is mapped to is evaluated.
+    (setq mapping '((:author . (bibtex-set-field "author" author))
+                   (:title . (bibtex-set-field "title" title))
+                   (:container-title . (bibtex-set-field "journal" journal))
+                   (:issued . (bibtex-set-field "year" year))
+                   (:volume . (bibtex-set-field "volume" volume))
+                   (:issue . (bibtex-set-field "number" number))
+                   (:page . (bibtex-set-field "pages" pages))
+                   (:DOI . (bibtex-set-field "doi" doi))
+                   (:URL . (bibtex-set-field "url" url))))
+
+    ;; now we have code to run for each entry. we map over them and evaluate the code
+    (mapcar
+     (lambda (key)
+       (eval (cdr (assoc key mapping))))
+     (plist-get-keys results)))
+  
+  ; reclean entry, but keep key if it exists.
+  (if (bibtex-key-in-head)
+      (org-ref-clean-bibtex-entry t)
+    (org-ref-clean-bibtex-entry)))
+#+END_SRC
+* end of file
+#+BEGIN_SRC emacs-lisp :tangle doi-utils.el
+(provide 'doi-utils)
+#+END_SRC
+* load
+#+BEGIN_SRC emacs-lisp
+(org-babel-load-file "doi-utils.org")
+#+END_SRC
+
+#+RESULTS:
+: Loaded doi-utils.el
+
diff --git a/org-ref.org b/org-ref.org
new file mode 100644 (file)
index 0000000..62e9804
--- /dev/null
@@ -0,0 +1,2180 @@
+#+TITLE: Org-ref - The best reference handling for org-mode
+#+AUTHOR: John Kitchin
+#+DATE: April 29, 2014
+
+* Introduction
+
+This document is an experiment at creating a literate program to provide similar features as reftex for org-mode referencing. These features include:
+
+1. using completion to create links
+2. storing links to places, 
+3. Clickable links that do useful things
+4. Exportable links to LaTeX
+5. Utility functions for dealing with bibtex files and org-files
+
+** Header
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+;;; org-ref.el --- setup bibliography, cite, ref and label org-mode links.
+
+;; Copyright(C) 2014 John Kitchin
+
+;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
+;; This file is not currently part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2, or (at
+;; your option) any later version.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program ; see the file COPYING.  If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+;;
+;; Lisp code to setup bibliography cite, ref and label org-mode links.
+;; also sets up reftex for org-mode. The links are clickable and do
+;; things that are useful. You should really read org-ref.org for details.
+;;
+;; Package-Requires: ((dash))
+#+END_SRC
+
+** requires
+The only external require is reftex-cite
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(require 'reftex-cite)
+(require 'dash)
+#+END_SRC
+
+** Custom variables
+There are some variables needed later to tell this library where you store your pdf files, where your notes file is, and your default bibliography. This variable is similar to the reftex-default-bibliography. I do not remember why I made it separate.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defgroup org-ref nil
+  "customization group for org-ref")
+
+(defcustom org-ref-bibliography-notes
+  nil
+  "filename to where you will put all your notes about an entry in
+  the default bibliography."
+  :type 'file
+  :group 'org-ref)
+
+(defcustom org-ref-default-bibliography
+  nil
+  "list of bibtex files to search for. You should use full-paths for each file."
+  :type '(repeat :tag "List of bibtex files" file)
+  :group 'org-ref)
+
+(defcustom org-ref-pdf-directory
+  nil
+  "directory where pdfs are stored by key. put a trailing / in"
+  :type 'directory
+  :group 'org-ref)
+
+(defcustom org-ref-default-citation-link
+  "cite"
+  "The default type of citation link to use"
+  :type 'string
+  :group 'org-ref)
+
+(defcustom org-ref-insert-cite-key
+  "C-c ]"
+  "Keyboard shortcut to insert a citation."
+  :type 'string
+  :group 'org-ref)
+
+(defcustom org-ref-bibliography-entry-format
+  "%a, %t, <i>%j</i>, <b>%v(%n)</b>, %p (%y). <a href=\"%U\">link</a>. <a href=\"http://dx.doi.org/%D\">doi</a>."
+  "string to format an entry. Just the reference, no numbering at the beginning, etc..."
+  :type 'string
+  :group 'org-ref)
+#+END_SRC
+
+This next variable determines the citation types that are available in org-ref. Links for each one are automatically generated, and completion functions are automatically generated. Users may add to this list in their own init files.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defcustom org-ref-cite-types
+  '("cite" "nocite" ;; the default latex cite commands
+    ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
+    "citet" "citet*" "citep" "citep*"
+    "citealt" "citealt*" "citealp" "citealp*"
+    "citenum" "citetext"
+    "citeauthor" "citeauthor*"
+    "citeyear" "citeyear*"
+    "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
+    ;; biblatex commands
+    ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
+    "Cite"
+    "parencite" "Parencite"
+    "footcite" "footcitetext"
+    "textcite" "Textcite"
+    "smartcite" "Smartcite"
+    "cite*" "parencite*" "supercite"
+    "autocite" "Autocite" "autocite*" "Autocite*"
+    "Citeauthor*"
+    "citetitle" "citetitle*"
+    "citedate" "citedate*"
+    "citeurl"
+    "fullcite" "footfullcite"
+    ;; "volcite" "Volcite" cannot support the syntax
+    "notecite" "Notecite"
+    "pnotecite" "Pnotecite"
+    "fnotecite"
+    ;; multicites. Very limited support for these.
+    "cites" "Cites" "parencites" "Parencites"
+    "footcites" "footcitetexts"
+    "smartcites" "Smartcites" "textcites" "Textcites"
+    "supercites" "autocites" "Autocites"
+    )
+  "List of citation types known in org-ref"
+  :type '(repeat :tag "List of citation types" string)
+  :group 'org-ref)
+#+END_SRC
+
+We need a hook variable to store user-defined bibtex entry cleaning functions
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defcustom org-ref-clean-bibtex-entry-hook nil
+  "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
+  :group 'org-ref
+  :type 'hook)
+#+END_SRC
+
+** Program variables
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defvar org-ref-bibliography-files
+  nil
+  "variable to hold bibliography files to be searched")
+#+END_SRC
+
+** org-mode / reftex setup
+
+We setup reftex here. We use a custom insert cite link function defined here: [[*org-ref-insert-cite-link][org-ref-insert-cite-link]]. We setup reftex to use our org citation format.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-mode-reftex-setup ()
+    (load-library "reftex")
+    (and (buffer-file-name)
+         (file-exists-p (buffer-file-name))
+        (global-auto-revert-mode t)
+         (reftex-parse-all))
+    (make-local-variable 'reftex-cite-format)
+    (setq reftex-cite-format 'org)
+    (define-key org-mode-map (kbd org-ref-insert-cite-key) 'org-ref-insert-cite-link))
+
+(add-hook 'org-mode-hook 'org-mode-reftex-setup)
+
+(eval-after-load 'reftex-vars
+  '(progn
+      (add-to-list 'reftex-cite-format-builtin
+                   '(org "Org-mode citation"
+                         ((?\C-m . "cite:%l")     ; default
+                         (?d . ",%l")            ; for appending
+                         (?a . "autocite:%l")
+                         (?t . "citet:%l")
+                         (?T . "citet*:%l")
+                         (?p . "citep:%l")
+                         (?P . "citep*:%l")
+                         (?h . "citeauthor:%l")
+                         (?H . "citeauthor*:%l")
+                         (?y . "citeyear:%l")
+                         (?x . "citetext:%l")
+                         (?n . "nocite:%l")
+                         )))))
+#+END_SRC
+
+You may want to add new formats to the reftex-cite-format-builtin variable. Here is an example of adding two new formats. Note that this does not create the links. 
+
+#+BEGIN_SRC emacs-lisp :tangle no
+;; add new format
+(setf (nth 2 (assoc 'org reftex-cite-format-builtin))
+      (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W  . "textcite:%l")
+            (?z  . "newcite:%l"))))
+#+END_SRC
+
+You can define a new citation link like this:
+#+BEGIN_SRC emacs-lisp :tangle no
+(org-ref-define-citation-link "citez" ?z)
+#+END_SRC
+
+* Links
+Most of this library is the creation of functional links to help with references and citations.
+** General utilities
+We need several general utilities for this module. They are organized here. We frequently need to remove white space from the front and back of a string. Here we do that for a string.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-strip-string (string)
+  "strip leading and trailing whitespace from the string"
+  (replace-regexp-in-string
+   (concat search-whitespace-regexp "$" ) ""
+   (replace-regexp-in-string
+    (concat "^" search-whitespace-regexp ) "" string)))
+#+END_SRC
+
+It is helpful to make the previous function operate on a list of strings here.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-split-and-strip-string (string)
+  "split key-string and strip keys. Assumes the key-string is comma delimited"
+  (mapcar 'org-ref-strip-string (split-string string ",")))
+#+END_SRC
+
+** bibliography and bibliographystyle
+*** An html bibliography
+
+Reftex is no longer being developed. I want a url and doi option for formatting, so I am modifying this [[file:emacs-24.3/lisp/textmodes/reftex-cite.el::(defun%20reftex-format-citation%20(entry%20format)][function]] from reftex-cite to provide that. We need to modify the reftex-get-bib-field code a bit to remove enclosing braces and quotes so we can make nice looking links.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-reftex-get-bib-field (field entry &optional format)
+  "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
+  (let ((result))
+    (setq result (reftex-get-bib-field field entry format))
+    (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
+      (setq result (substring result 1 -1)))
+    (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
+      (setq result (substring result 1 -1)))    
+      result))
+
+(defun org-ref-reftex-format-citation (entry format)
+  "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
+to the format argument. The format is a string with these percent escapes.
+
+In the format, the following percent escapes will be expanded.
+
+%l   The BibTeX label of the citation.
+%a   List of author names, see also `reftex-cite-punctuation'.
+%2a  Like %a, but abbreviate more than 2 authors like Jones et al.
+%A   First author name only.
+%e   Works like %a, but on list of editor names. (%2e and %E work a well)
+
+It is also possible to access all other BibTeX database fields:
+%b booktitle     %c chapter        %d edition    %h howpublished
+%i institution   %j journal        %k key        %m month
+%n number        %o organization   %p pages      %P first page
+%r address       %s school         %u publisher  %t title
+%v volume        %y year
+%B booktitle, abbreviated          %T title, abbreviated
+%U url
+%D doi
+
+Usually, only %l is needed.  The other stuff is mainly for the echo area
+display, and for (setq reftex-comment-citations t).
+
+%< as a special operator kills punctuation and space around it after the
+string has been formatted.
+
+A pair of square brackets indicates an optional argument, and RefTeX
+will prompt for the values of these arguments.
+
+Beware that all this only works with BibTeX database files.  When
+citations are made from the \bibitems in an explicit thebibliography
+environment, only %l is available."
+  ;; Format a citation from the info in the BibTeX ENTRY
+
+  (unless (stringp format) (setq format "\\cite{%l}"))
+
+  (if (and reftex-comment-citations
+           (string-match "%l" reftex-cite-comment-format))
+      (error "reftex-cite-comment-format contains invalid %%l"))
+
+  (while (string-match
+          "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
+          format)
+    (let ((n (string-to-number (match-string 4 format)))
+          (l (string-to-char (match-string 5 format)))
+          rpl b e)
+      (save-match-data
+        (setq rpl
+              (cond
+               ((= l ?l) (concat
+                          (org-ref-reftex-get-bib-field "&key" entry)
+                          (if reftex-comment-citations
+                              reftex-cite-comment-format
+                            "")))
+               ((= l ?a) (reftex-format-names
+                          (reftex-get-bib-names "author" entry)
+                          (or n 2)))
+               ((= l ?A) (car (reftex-get-bib-names "author" entry)))
+               ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
+               ((= l ?B) (reftex-abbreviate-title
+                          (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
+               ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
+               ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
+               ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
+               ((= l ?e) (reftex-format-names
+                          (reftex-get-bib-names "editor" entry)
+                          (or n 2)))
+               ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
+               ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
+               ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
+               ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
+               ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
+               ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
+               ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
+               ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
+               ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
+               ((= l ?P) (car (split-string
+                               (org-ref-reftex-get-bib-field "pages" entry)
+                               "[- .]+")))
+               ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
+               ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
+               ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
+               ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
+              ;; strip enclosing brackets from title if they are there
+               ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
+               ((= l ?T) (reftex-abbreviate-title
+                          (org-ref-reftex-get-bib-field "title" entry)))
+               ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
+               ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
+
+      (if (string= rpl "")
+          (setq b (match-beginning 2) e (match-end 2))
+        (setq b (match-beginning 3) e (match-end 3)))
+      (setq format (concat (substring format 0 b) rpl (substring format e)))))
+  (while (string-match "%%" format)
+    (setq format (replace-match "%" t t format)))
+  (while (string-match "[ ,.;:]*%<" format)
+    (setq format (replace-match "" t t format)))
+  ;; also replace carriage returns, tabs, and multiple whitespaces
+  (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
+  format)
+
+(defun org-ref-get-bibtex-entry-citation (key)
+  "returns a string for the bibliography entry corresponding to key, and formatted according to `org-ref-bibliography-entry-format'"
+
+  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
+       (file) (entry))
+
+    (setq file (catch 'result
+                (loop for file in org-ref-bibliography-files do
+                      (if (org-ref-key-in-file-p key (file-truename file)) 
+                          (throw 'result file)
+                        (message "%s not found in %s" key (file-truename file))))))
+
+    (with-temp-buffer
+      (insert-file-contents file)
+      (bibtex-search-entry key nil 0)
+      (setq entry  (org-ref-reftex-format-citation (bibtex-parse-entry) org-ref-bibliography-entry-format)))
+    entry))
+#+END_SRC
+
+#+RESULTS:
+: org-ref-reftex-format-citation
+
+Here is how to use the function. You call it with point in an entry in a bibtex file.
+
+#+BEGIN_SRC emacs-lisp :tangle no
+(let((org-ref-bibliography-entry-format   "%a, %t, <i>%j</i>, <b>%v(%n)</b>, %p (%y). <a href=\"%U\">link</a>. <a href=\"http://dx.doi.org/%D\">doi</a>."))
+  (org-ref-get-bibtex-entry-citation  "armiento-2014-high"))
+#+END_SRC
+#+RESULTS:
+: Armiento, Kozinsky, Hautier, , Fornari \& Ceder, High-throughput screening of perovskite alloys for  piezoelectric performance and thermodynamic  stability, <i>Phys. Rev. B</i>, <b>89()</b>, 134103 (2014). <a href="http://link.aps.org/doi/10.1103/PhysRevB.89.134103">link</a>. <a href="http://dx.doi.org/10.1103/PhysRevB.89.134103">doi</a>.
+
+I am not sure why full author names are not used.
+
+This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the bufer.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-bibtex-keys ()
+  "return a list of unique keys in the buffer."
+  (let ((keys '()))
+    (org-element-map (org-element-parse-buffer) 'link
+      (lambda (link)       
+       (let ((plist (nth 1 link)))                          
+         (when (-contains? org-ref-cite-types (plist-get plist ':type))
+           (dolist 
+               (key 
+                (org-ref-split-and-strip-string (plist-get plist ':path)))
+             (when (not (-contains? keys key))
+               (setq keys (append keys (list key)))))))))
+    ;; Sort keys alphabetically
+    (setq keys (cl-sort keys 'string-lessp :key 'downcase))
+    keys))
+#+END_SRC
+
+This function gets the html for one entry.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-bibtex-entry-html (key)
+  "returns an html string for the bibliography entry corresponding to key"
+
+  (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
+#+END_SRC
+
+Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el 
+(defun org-ref-get-html-bibliography ()
+  "Create an html bibliography when there are keys"
+  (let ((keys (org-ref-get-bibtex-keys)))
+    (when keys
+      (concat "<h1>Bibliography</h1>
+<ul>"
+             (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
+             "\n</ul>"))))
+#+END_SRC
+
+I do not have plans to make a numbered bibliography with numbered citations anytime soon. This will require changing the way the citation links are exported, and keeping track of the numbers.
+
+*** the links
+We use a link for the bibliography so that we can click on it to open the bibliography file. The link may have more than one bibliography file in it, separated by commas. Clicking opens the file under the cursor. The bibliographies should be full filenames with the bib extension. Clicking on this link makes reftex-default-bibliography local and sets it to the list of files in the link. We need this to use reftex's searching capability.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(org-add-link-type "bibliography"
+                  ;; this code is run on clicking. The bibliography
+                  ;; may contain multiple files. this code finds the
+                  ;; one you clicked on and opens it.
+                  (lambda (link-string)        
+                      ;; get link-string boundaries
+                      ;; we have to go to the beginning of the line, and then search forward
+                      
+                    (let* ((bibfile)
+                           ;; object is the link you clicked on
+                           (object (org-element-context))
+                           (link-string-beginning) 
+                           (link-string-end))
+
+                    (save-excursion
+                      (goto-char (org-element-property :begin object))
+                      (search-forward link-string nil nil 1)
+                      (setq link-string-beginning (match-beginning 0))
+                      (setq link-string-end (match-end 0)))
+
+                      ;; We set the reftex-default-bibliography
+                      ;; here. it should be a local variable only in
+                      ;; the current buffer. We need this for using
+                      ;; reftex to do citations.
+                      (set (make-local-variable 'reftex-default-bibliography) 
+                           (split-string (org-element-property :path object) ","))
+
+                      ;; now if we have comma separated bibliographies
+                      ;; we find the one clicked on. we want to
+                      ;; search forward to next comma from point
+                      (save-excursion
+                        (if (search-forward "," link-string-end 1 1)
+                            (setq key-end (- (match-end 0) 1)) ; we found a match
+                          (setq key-end (point)))) ; no comma found so take the point
+                      ;; and backward to previous comma from point
+                      (save-excursion
+                        (if (search-backward "," link-string-beginning 1 1)
+                            (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
+                          (setq key-beginning (point)))) ; no match found
+                      ;; save the key we clicked on.
+                      (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
+                      (find-file bibfile))) ; open file on click
+
+                    ;; formatting code
+                  (lambda (keyword desc format)
+                    (cond
+                     ((eq format 'html) (org-ref-get-html-bibliography))
+                     ((eq format 'latex)
+                        ;; write out the latex bibliography command
+                      (format "\\bibliography{%s}" (replace-regexp-in-string  "\\.bib" "" keyword))))))
+#+END_SRC
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(org-add-link-type "printbibliography"
+                  (lambda (arg) (message "Nothing implemented for clicking here."))
+                  (lambda (keyword desc format)
+                    (cond
+                      ((eq format 'html) (org-ref-get-html-bibliography))
+                     ((eq format 'latex)
+                      ;; write out the latex bibliography command
+                      (format "\\printbibliography" keyword)))))
+#+END_SRC
+
+We also create a bibliographystyle link. There is nothing to do on clicking here, and we create it for consistency. This sets the style for latex export, so use something appropriate there, e.g. unsrt, plain, plainnat, ...
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(org-add-link-type "bibliographystyle"
+                  (lambda (arg) (message "Nothing implemented for clicking here."))
+                  (lambda (keyword desc format)
+                    (cond
+                     ((eq format 'latex)
+                      ;; write out the latex bibliography command
+                      (format "\\bibliographystyle{%s}" keyword)))))
+#+END_SRC
+
+*** Completion for bibliography link
+It would be nice 
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-bibliography-complete-link (&optional arg)
+ (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
+
+(defun org-ref-insert-bibliography-link ()
+  "insert a bibliography with completion"
+  (interactive)
+  (insert (org-bibliography-complete-link)))
+#+END_SRC
+
+** addbibresource
+This is apparently used for biblatex.
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(org-add-link-type "addbibresource"
+                  ;; this code is run on clicking. The addbibresource
+                  ;; may contain multiple files. this code finds the
+                  ;; one you clicked on and opens it.
+                  (lambda (link-string)        
+                      ;; get link-string boundaries
+                      ;; we have to go to the beginning of the line, and then search forward
+                      
+                    (let* ((bibfile)
+                           ;; object is the link you clicked on
+                           (object (org-element-context))
+                           (link-string-beginning) 
+                           (link-string-end))
+
+                    (save-excursion
+                      (goto-char (org-element-property :begin object))
+                      (search-forward link-string nil nil 1)
+                      (setq link-string-beginning (match-beginning 0))
+                      (setq link-string-end (match-end 0)))
+
+                      ;; We set the reftex-default-addbibresource
+                      ;; here. it should be a local variable only in
+                      ;; the current buffer. We need this for using
+                      ;; reftex to do citations.
+                      (set (make-local-variable 'reftex-default-addbibresource) 
+                           (split-string (org-element-property :path object) ","))
+
+                      ;; now if we have comma separated bibliographies
+                      ;; we find the one clicked on. we want to
+                      ;; search forward to next comma from point
+                      (save-excursion
+                        (if (search-forward "," link-string-end 1 1)
+                            (setq key-end (- (match-end 0) 1)) ; we found a match
+                          (setq key-end (point)))) ; no comma found so take the point
+                      ;; and backward to previous comma from point
+                      (save-excursion
+                        (if (search-backward "," link-string-beginning 1 1)
+                            (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
+                          (setq key-beginning (point)))) ; no match found
+                      ;; save the key we clicked on.
+                      (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
+                      (find-file bibfile))) ; open file on click
+
+                    ;; formatting code
+                  (lambda (keyword desc format)
+                    (cond
+                     ((eq format 'html) (format "")); no output for html
+                     ((eq format 'latex)
+                        ;; write out the latex addbibresource command
+                      (format "\\addbibresource{%s}" keyword)))))
+#+END_SRC
+
+** List of Figures
+
+In long documents, a list of figures is not uncommon. Here we create a clickable link that generates a temporary buffer containing a list of figures in the document, and their captions. We make a function that can be called interactively, and define a link type that is rendered in LaTeX to create the list of figures.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-list-of-figures (&optional arg)
+  "Generate buffer with list of figures in them"
+  (interactive)
+  (save-excursion (widen)
+  (let* ((c-b (buffer-name))
+        (counter 0)
+        (list-of-figures 
+         (org-element-map (org-element-parse-buffer) 'link
+           (lambda (link) 
+             "create a link for to the figure"
+             (when 
+                 (and (string= (org-element-property :type link) "file")
+                      (string-match-p  
+                       "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
+                       (org-element-property :path link)))                   
+               (incf counter)
+               
+               (let* ((start (org-element-property :begin link))
+                      (parent (car (cdr (org-element-property :parent link))))
+                      (caption (caaar (plist-get parent :caption)))
+                      (name (plist-get parent :name)))
+                 (if caption 
+                     (format 
+                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n" 
+                      c-b start counter (or name "") caption)
+                   (format 
+                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n" 
+                    c-b start counter (or name "")))))))))
+    (switch-to-buffer "*List of Figures*")
+    (setq buffer-read-only nil)
+    (org-mode)
+    (erase-buffer)
+    (insert (mapconcat 'identity list-of-figures ""))
+    (setq buffer-read-only t)
+    (use-local-map (copy-keymap org-mode-map))
+    (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
+
+(org-add-link-type 
+ "list-of-figures"
+ 'org-ref-list-of-figures ; on click
+ (lambda (keyword desc format)
+   (cond
+    ((eq format 'latex)
+     (format "\\listoffigures")))))
+#+END_SRC
+
+** List of Tables
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-ref-list-of-tables (&optional arg)
+  "Generate a buffer with a list of tables"
+  (interactive)
+  (save-excursion
+  (widen)
+  (let* ((c-b (buffer-name))
+        (counter 0)
+        (list-of-tables 
+         (org-element-map (org-element-parse-buffer 'element) 'table
+           (lambda (table) 
+             "create a link for to the table"
+             (incf counter)
+             (let ((start (org-element-property :begin table))
+                   (name  (org-element-property :name table))
+                   (caption (caaar (org-element-property :caption table))))
+               (if caption 
+                   (format 
+                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n" 
+                    c-b start counter (or name "") caption)
+                 (format 
+                  "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n" 
+                  c-b start counter (or name ""))))))))
+    (switch-to-buffer "*List of Tables*")
+    (setq buffer-read-only nil)
+    (org-mode)
+    (erase-buffer)
+    (insert (mapconcat 'identity list-of-tables ""))
+    (setq buffer-read-only t)
+    (use-local-map (copy-keymap org-mode-map))
+    (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
+
+(org-add-link-type 
+ "list-of-tables"
+ 'org-ref-list-of-tables
+ (lambda (keyword desc format)
+   (cond
+    ((eq format 'latex)
+     (format "\\listoftables")))))
+#+END_SRC
+** label
+
+The label link provides a way to create labels in org-mode. We make it clickable because we want to make sure labels are unique. This code will tell you how many instances of a label are found.  We search for label links, LaTeX labels, and the org-mode format for labels. We probably should search for tblnames too.
+*************** TODO search tblnames, custom_ids and check for case sensitivity
+*************** END
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(org-add-link-type
+ "label"
+ (lambda (label)
+   "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
+   (message (format "%s occurences"
+                   (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
+                       ;; for tblname, it is not enough to get word boundary
+                       ;; tab-little and tab-little-2 match then.
+                       (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
+                      (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
+                       ;; this is the org-format #+label:
+                      (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))))
+ (lambda (keyword desc format)
+   (cond
+    ((eq format 'html) (format "(<label>%s</label>)" path))
+    ((eq format 'latex)
+     (format "\\label{%s}" keyword)))))
+#+END_SRC
+
+We want to store links on labels, so you can put the cursor on the label, press C-c l, and later use C-c C-l to insert a link to the label. We also want to store links to tables with a table name, and for sections with CUSTOM_ID.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-label-store-link ()
+  "store a link to a label. The output will be a ref to that label"
+  ;; First we have to make sure we are on a label link. 
+  (let* ((object (org-element-context)))
+    (when (and (equal (org-element-type object) 'link) 
+               (equal (org-element-property :type object) "label"))
+      (org-store-link-props
+       :type "ref"
+       :link (concat "ref:" (org-element-property :path object))))
+
+    ;; Store link on table
+    (when (equal (org-element-type object) 'table)
+      (org-store-link-props
+       :type "ref"
+       :link (concat "ref:" (org-element-property :name object))))
+
+;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
+    ;; store link on heading with custom_id
+;    (when (and (equal (org-element-type object) 'headline)
+;             (org-entry-get (point) "CUSTOM_ID"))
+;      (org-store-link-props
+;       :type "ref"
+;       :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
+
+    ;; and to #+label: lines
+    (when (and (equal (org-element-type object) 'paragraph)
+              (org-element-property :name object))
+      (org-store-link-props
+       :type "ref"
+       :link (concat "ref:" (org-element-property :name object))))
+))
+
+(add-hook 'org-store-link-functions 'org-label-store-link)
+#+END_SRC
+** ref
+
+The ref link allows you make links to labels. Clicking on the link takes you to the label, and provides a mark to go back to. 
+
+At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(org-add-link-type
+ "ref"
+ (lambda (label)
+   "on clicking goto the label. Navigate back with C-c &"
+   (org-mark-ring-push)
+   ;; next search from beginning of the buffer
+
+   ;; it is possible you would not find the label if narrowing is in effect
+   (widen)
+
+   (unless
+       (or
+       ;; our label links
+       (progn 
+         (goto-char (point-min))
+         (re-search-forward (format "label:%s\\b" label) nil t))
+
+       ;; a latex label
+       (progn
+         (goto-char (point-min))
+         (re-search-forward (format "\\label{%s}" label) nil t))
+
+       ;; #+label: name  org-definition
+       (progn
+         (goto-char (point-min))
+         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
+       
+       ;; org tblname
+       (progn
+         (goto-char (point-min))
+         (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
+
+;; Commented out because these ref links do not actually translate correctly in LaTeX.
+;; you need [[#label]] links.
+       ;; CUSTOM_ID
+;      (progn
+;        (goto-char (point-min))
+;        (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
+       )
+     ;; we did not find anything, so go back to where we came
+     (org-mark-ring-goto)
+     (error "%s not found" label))
+   (message "go back with (org-mark-ring-goto) `C-c &`"))
+ ;formatting
+ (lambda (keyword desc format)
+   (cond
+    ((eq format 'html) (format "(<ref>%s</ref>)" path))
+    ((eq format 'latex)
+     (format "\\ref{%s}" keyword)))))
+#+END_SRC
+
+It would be nice to use completion to enter a ref link, where a list of labels is provided. The following code searches the buffer for labels, custom_ids, and table names as potential items to make a ref link to.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-custom-ids ()
+ "return a list of custom_id properties in the buffer"
+ (let ((results '()) custom_id)
+   (org-map-entries 
+    (lambda () 
+      (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
+       (when (not (null custom_id))
+         (setq results (append results (list custom_id)))))))
+results))
+#+END_SRC
+
+Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-latex-labels ()
+(save-excursion
+    (goto-char (point-min))
+    (let ((matches '()))
+      (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
+       (add-to-list 'matches (match-string-no-properties 1) t))
+matches)))
+#+END_SRC
+
+Finally, we get the table names.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-tblnames ()
+  (org-element-map (org-element-parse-buffer 'element) 'table
+    (lambda (table) 
+      (org-element-property :name table))))
+#+END_SRC
+
+Now, we can put all the labels together which will give us a list of candidates.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-ref-get-labels ()
+  "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
+  (save-excursion
+    (save-restriction
+      (widen)
+      (goto-char (point-min))
+      (let ((matches '()))
+       (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
+         (add-to-list 'matches (match-string-no-properties 1) t))
+       (append matches (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
+#+END_SRC
+
+Now we create the completion function. This works from the org-machinery, e.g. if you type C-c C-l to insert a link, and use completion by pressing tab.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-ref-complete-link (&optional arg)
+  "Completion function for ref links"
+  (let ((label))
+    (setq label (completing-read "label: " (org-ref-get-labels)))
+    (format "ref:%s" label)))
+#+END_SRC
+
+Alternatively, you may want to just call a function that inserts a link with completion:
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-ref-insert-ref-link ()
+ (interactive)
+ (insert (org-ref-complete-link)))
+#+END_SRC
+
+** pageref
+
+This refers to the page of a label in LaTeX.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(org-add-link-type
+ "pageref"
+ (lambda (label)
+   "on clicking goto the label. Navigate back with C-c &"
+   (org-mark-ring-push)
+   ;; next search from beginning of the buffer
+   (widen)
+   (unless
+       (or
+       ;; our label links
+       (progn 
+         (goto-char (point-min))
+         (re-search-forward (format "label:%s\\b" label) nil t))
+
+       ;; a latex label
+       (progn
+         (goto-char (point-min))
+         (re-search-forward (format "\\label{%s}" label) nil t))
+
+       ;; #+label: name  org-definition
+       (progn
+         (goto-char (point-min))
+         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
+       
+       ;; org tblname
+       (progn
+         (goto-char (point-min))
+         (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
+
+;; Commented out because these ref links do not actually translate correctly in LaTeX.
+;; you need [[#label]] links.
+       ;; CUSTOM_ID
+;      (progn
+;        (goto-char (point-min))
+;        (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
+       )
+     ;; we did not find anything, so go back to where we came
+     (org-mark-ring-goto)
+     (error "%s not found" label))
+   (message "go back with (org-mark-ring-goto) `C-c &`"))
+ ;formatting
+ (lambda (keyword desc format)
+   (cond
+    ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
+    ((eq format 'latex)
+     (format "\\pageref{%s}" keyword)))))
+#+END_SRC
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-pageref-complete-link (&optional arg)
+  "Completion function for ref links"
+  (let ((label))
+    (setq label (completing-read "label: " (org-ref-get-labels)))
+    (format "ref:%s" label)))
+#+END_SRC
+
+Alternatively, you may want to just call a function that inserts a link with completion:
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-pageref-insert-ref-link ()
+ (interactive)
+ (insert (org-pageref-complete-link)))
+#+END_SRC
+
+** nameref
+
+The nameref link allows you make links to the text of a section with a label. Clicking on the link takes you to the label, and provides a mark to go back to. This only works if you put a raw latex label in the headline.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(org-add-link-type
+ "nameref"
+ (lambda (label)
+   "on clicking goto the label. Navigate back with C-c &"
+   (org-mark-ring-push)
+   ;; next search from beginning of the buffer
+   (widen)
+   (unless
+       (or
+       ;; a latex label
+       (progn
+         (goto-char (point-min))
+         (re-search-forward (format "\\label{%s}" label) nil t))
+       )
+     ;; we did not find anything, so go back to where we came
+     (org-mark-ring-goto)
+     (error "%s not found" label))
+   (message "go back with (org-mark-ring-goto) `C-c &`"))
+ ;formatting
+ (lambda (keyword desc format)
+   (cond
+    ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
+    ((eq format 'latex)
+     (format "\\nameref{%s}" keyword)))))
+#+END_SRC
+
+** eqref
+This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(org-add-link-type
+ "eqref"
+ (lambda (label)
+   "on clicking goto the label. Navigate back with C-c &"
+   (org-mark-ring-push)
+   ;; next search from beginning of the buffer
+   (widen)
+   (goto-char (point-min))
+   (unless
+       (or
+       ;; search forward for the first match
+       ;; our label links
+       (re-search-forward (format "label:%s" label) nil t)
+       ;; a latex label
+       (re-search-forward (format "\\label{%s}" label) nil t)
+       ;; #+label: name  org-definition
+       (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
+     (org-mark-ring-goto)
+     (error "%s not found" label))
+   (message "go back with (org-mark-ring-goto) `C-c &`"))
+ ;formatting
+ (lambda (keyword desc format)
+   (cond
+    ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
+    ((eq format 'latex)
+     (format "\\eqref{%s}" keyword)))))
+#+END_SRC
+
+
+** cite
+This is the main reason this library exists. We want the following behavior. A cite link should be able to contain multiple bibtex keys. You should be able to click on the link, and get a brief citation of the entry for that key, and a menu of options to open the bibtex file, open a pdf if you have it, open your notes on the entry, or open a url if it exists. You should be able to insert new references onto an existing cite link, or create new ones easily. The following code implements these features.
+
+*** Implementing the click actions of cite
+
+**** Getting the key we clicked on
+The first thing we need is to get the bibtex key we clicked on.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-ref-get-bibtex-key-under-cursor ()
+  "returns key under the bibtex cursor. We search forward from
+point to get a comma, or the end of the link, and then backwards
+to get a comma, or the beginning of the link. that delimits the
+keyword we clicked on. We also strip the text properties."
+  (interactive)
+  (let* ((object (org-element-context))         
+        (link-string (org-element-property :path object)))    
+    
+    ;; we need the link path start and end
+    (save-excursion
+      (goto-char (org-element-property :begin object))
+      (search-forward link-string nil nil 1)
+      (setq link-string-beginning (match-beginning 0))
+      (setq link-string-end (match-end 0)))
+
+    ;; The key is the text between commas, or the link boundaries
+    (save-excursion
+      (if (search-forward "," link-string-end t 1)
+         (setq key-end (- (match-end 0) 1)) ; we found a match
+       (setq key-end link-string-end))) ; no comma found so take the end
+    ;; and backward to previous comma from point which defines the start character
+    (save-excursion
+      (if (search-backward "," link-string-beginning 1 1)
+         (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
+       (setq key-beginning link-string-beginning))) ; no match found
+    ;; save the key we clicked on.
+    (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
+    (set-text-properties 0 (length bibtex-key) nil bibtex-key)
+    bibtex-key
+    ))
+#+END_SRC
+
+We also need to find which bibliography file that key is in. For that, we need to know which bibliography files are referred to in the file. If none are specified with a bibliography link, we use the default bibliography. This function searches for a bibliography link, and then the LaTeX bibliography link. We also consider the addbibresource link which is used with biblatex.
+
+**** Getting the bibliographies
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-find-bibliography ()
+  "find the bibliography in the buffer.
+This function sets and returns cite-bibliography-files, which is a list of files
+either from bibliography:f1.bib,f2.bib
+\bibliography{f1,f2}
+internal bibliographies
+
+falling back to what the user has set in org-ref-default-bibliography
+"
+  (interactive)
+  (catch 'result
+    (save-excursion
+      (goto-char (point-min))
+      ;;  look for a bibliography link
+      (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
+       (setq org-ref-bibliography-files
+             (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
+       (throw 'result org-ref-bibliography-files))
+
+      
+      ;; we did not find a bibliography link. now look for \bibliography
+      (goto-char (point-min))
+      (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
+       ;; split, and add .bib to each file
+       (setq org-ref-bibliography-files
+             (mapcar (lambda (x) (concat x ".bib"))
+                     (mapcar 'org-ref-strip-string 
+                             (split-string (match-string 1) ","))))
+       (throw 'result org-ref-bibliography-files))
+
+      ;; no bibliography found. maybe we need a biblatex addbibresource
+      (goto-char (point-min))
+      ;;  look for a bibliography link
+      (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
+       (setq org-ref-bibliography-files
+             (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
+       (throw 'result org-ref-bibliography-files))
+         
+      ;; we did not find anything. use defaults
+      (setq org-ref-bibliography-files org-ref-default-bibliography)))
+
+    ;; set reftex-default-bibliography so we can search
+    (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
+    org-ref-bibliography-files)
+#+END_SRC
+
+**** Finding the bibliography file a key is in
+Now, we can see if an entry is in a file. 
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-key-in-file-p (key filename)
+  "determine if the key is in the file"
+  (interactive "skey: \nsFile: ")
+
+  (with-temp-buffer
+    (insert-file-contents filename)
+    (prog1
+        (bibtex-search-entry key nil 0))))
+#+END_SRC
+
+Finally, we want to know which file the key is in.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-bibtex-key-and-file (&optional key)
+  "returns the bibtex key and file that it is in. If no key is provided, get one under point"
+ (interactive)
+ (let ((org-ref-bibliography-files (org-ref-find-bibliography))
+       (file))
+   (unless key
+     (setq key (org-ref-get-bibtex-key-under-cursor)))
+   (setq file     (catch 'result
+                   (loop for file in org-ref-bibliography-files do
+                         (if (org-ref-key-in-file-p key (file-truename file)) 
+                             (throw 'result file)))))
+   (cons key file)))
+#+END_SRC
+
+**** Creating the menu for when we click on a key
+     :PROPERTIES:
+     :ID:       d7b7530b-802f-42b1-b61e-1e77da33e278
+     :END:
+When we click on a cite link, we want to get a menu in the minibuffer. We need to create a string for this. We want a citation, and some options that depend on the key. We want to know if the key is found, if there is a pdf, if etc... Here we create that string.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-ref-get-menu-options ()
+  "returns a dynamically determined string of options for the citation under point.
+
+we check to see if there is pdf, and if the key actually exists in the bibliography"
+  (interactive)
+  (let* ((results (org-ref-get-bibtex-key-and-file))
+        (key (car results))
+         (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
+         (bibfile (cdr results))
+        m1 m2 m3 m4 m5 menu-string)
+    (setq m1 (if bibfile                
+                "(o)pen"
+              "(No key found)"))
+
+    (setq m3 (if (file-exists-p pdf-file)
+                "(p)df"
+                    "(No pdf found)"))
+
+    (setq m4 (if (not
+                  (and bibfile
+                       (string= (catch 'url
+                                  (progn
+
+                                    (with-temp-buffer
+                                      (insert-file-contents bibfile)
+                                      (bibtex-search-entry key)
+                                      (when (not
+                                             (string= (setq url (bibtex-autokey-get-field "url")) ""))
+                                        (throw 'url url))
+
+                                      (when (not
+                                             (string= (setq url (bibtex-autokey-get-field "doi")) ""))
+                                        (throw 'url url))))) "")))
+               "(u)rl" "(no url found)"))
+    (setq m5 "(n)otes")
+    (setq m2 (if bibfile
+                (progn
+                   (setq citation (progn
+                                    (with-temp-buffer
+                                      (insert-file-contents bibfile)
+                                      (bibtex-search-entry key)
+                                      (org-ref-bib-citation))))
+                   citation)
+              "no key found"))
+
+    (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") "  "))
+    menu-string))
+#+END_SRC
+
+**** convenience functions to act on citation at point
+     :PROPERTIES:
+     :ID:       af0b2a82-a7c9-4c08-9dac-09f93abc4a92
+     :END:
+We need some convenience functions to open act on the citation at point. These will get the pdf, open the url, or open the notes.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-open-pdf-at-point ()
+  "open the pdf for bibtex key under point if it exists"
+  (interactive)
+  (let* ((results (org-ref-get-bibtex-key-and-file))
+        (key (car results))
+         (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
+    (if (file-exists-p pdf-file)
+       (org-open-file pdf-file)
+(message "no pdf found for %s" key))))
+
+
+(defun org-ref-open-url-at-point ()
+  "open the url for bibtex key under point."
+  (interactive)
+  (let* ((results (org-ref-get-bibtex-key-and-file))
+        (key (car results))
+        (bibfile (cdr results)))
+    (save-excursion
+      (with-temp-buffer
+        (insert-file-contents bibfile)
+        (bibtex-search-entry key)
+        ;; I like this better than bibtex-url which does not always find
+        ;; the urls
+        (catch 'done
+          (let ((url (bibtex-autokey-get-field "url")))
+            (when  url
+              (browse-url url)
+              (throw 'done nil)))
+
+          (let ((doi (bibtex-autokey-get-field "doi")))
+            (when doi
+              (if (string-match "^http" doi)
+                  (browse-url doi)
+                (browse-url (format "http://dx.doi.org/%s" doi)))
+              (throw 'done nil))))))))
+
+(defun org-ref-open-notes-at-point ()
+  "open the notes for bibtex key under point."
+  (interactive)
+  (let* ((results (org-ref-get-bibtex-key-and-file))
+        (key (car results))
+        (bibfile (cdr results)))
+    (save-excursion
+      (with-temp-buffer
+        (insert-file-contents bibfile)
+        (bibtex-search-entry key)
+        (org-ref-open-bibtex-notes)))))
+
+(defun org-ref-citation-at-point ()
+  "give message of current citation at point"
+  (interactive)
+  (let* ((cb (current-buffer))
+       (results (org-ref-get-bibtex-key-and-file))
+       (key (car results))
+       (bibfile (cdr results)))        
+    (message "%s" (progn
+                   (with-temp-buffer
+                      (insert-file-contents bibfile)
+                      (bibtex-search-entry key)
+                      (org-ref-bib-citation))))))
+
+(defun org-ref-open-citation-at-point ()
+  "open bibtex file to key at point"
+  (interactive)
+  (let* ((cb (current-buffer))
+       (results (org-ref-get-bibtex-key-and-file))
+       (key (car results))
+       (bibfile (cdr results)))
+    (find-file bibfile)
+    (bibtex-search-entry key)))
+#+END_SRC
+
+**** the actual minibuffer menu
+Now, we create the menu.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
+  "use a minibuffer to select options for the citation under point.
+
+you select your option with a single key press."
+  (interactive)
+  (let* ((choice (read-char (org-ref-get-menu-options)))
+        (results (org-ref-get-bibtex-key-and-file))
+        (key (car results))
+        (cb (current-buffer))
+         (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
+         (bibfile (cdr results)))
+
+    (cond
+     ;; open
+     ((= choice ?o)
+      (find-file bibfile)
+       (bibtex-search-entry key))
+
+     ;; cite
+     ((= choice ?c)
+      (org-ref-citation-at-point))
+      
+
+     ;; quit
+     ((or 
+      (= choice ?q) ; q
+      (= choice ?\ )) ; space
+      ;; this clears the minibuffer
+      (message ""))
+
+     ;; pdf
+     ((= choice ?p)
+      (org-ref-open-pdf-at-point))
+
+     ;; notes
+     ((= choice ?n)
+      (org-ref-open-notes-at-point))
+
+     ;; url
+     ((= choice ?u)
+      (org-ref-open-url-at-point))
+
+     ;; anything else we just quit.
+     (t (message "")))))
+    
+#+END_SRC
+
+*** A function to format a cite link
+
+Next, we define a formatting function for the cite link. This is done so that the cite link definition is very short, and easy to change. You just need to specify the functions in the definition. This function is deprecated. The formatting is defined later automatically.
+
+#+BEGIN_SRC emacs-lisp  :tangle no
+;(defun org-ref-cite-link-format (keyword desc format)
+;   (cond
+;    ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
+;    ((eq format 'latex)
+;     (concat "\\cite" (when desc (format "[%s]" desc)) "{"
+;           (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
+;           "}"))))
+#+END_SRC
+
+*** The actual cite link
+Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
+
+#+BEGIN_SRC emacs-lisp :tangle no
+;(org-add-link-type
+; "cite"
+; 'org-ref-cite-onclick-minibuffer-menu
+; 'org-ref-cite-link-format)
+#+END_SRC
+
+*** Automatic definition of the cite links
+There are many different kinds of citations in LaTeX, but they are all variants of a basic syntax of \citetype[optional text]{label1,label2}. Here we use lisp to generate the link definitions. We define a function that creates the code to create the link, and then we evaluate it. We also create the completion function for the new link, and add it to the list of known links. 
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el 
+(defmacro org-ref-make-completion-function (type)
+  `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
+     (interactive)
+     (format "%s:%s" 
+            ,type
+            (completing-read 
+             "bibtex key: " 
+             (let ((bibtex-files (org-ref-find-bibliography)))
+               (bibtex-global-key-alist))))))
+#+END_SRC
+
+We will want to generate formatting functions for each citation type. The reason for doing this is so we can on the fly change the formatting later.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el 
+(defmacro org-ref-make-format-function (type)
+  `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
+     (cond
+      ((eq format 'html) 
+       (mapconcat 
+       (lambda (key) 
+         (format "<a href=\"#%s\">%s</a>" key key))
+       (org-ref-split-and-strip-string keyword) ","))
+
+      ((eq format 'latex)
+       (if (string= (substring type -1) "s")
+          ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
+          (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
+                                        (org-ref-split-and-strip-string keyword) ""))
+        ;; bibtex format
+       (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
+              (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
+              "}"))))))
+#+END_SRC
+
+
+
+We create the links by mapping the function onto the list of defined link types. 
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-format-citation-description (desc)
+  "return formatted citation description. if the cite link has a description, it is optional text for the citation command. You can specify pre and post text by separating these with ::."
+  (interactive)
+  (cond
+   ((string-match "::" desc)
+    (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
+   (t (format "[%s]" desc))))
+
+(defun org-ref-define-citation-link (type &optional key)
+  "add a citation link for org-ref. With optional key, set the reftex binding. For example:
+(org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z, 
+and the completion function."
+  (interactive "sCitation Type: \ncKey: ")
+
+  ;; create the formatting function
+  (eval `(org-ref-make-format-function ,type))
+
+  (eval-expression 
+   `(org-add-link-type 
+     ,type
+     'org-ref-cite-onclick-minibuffer-menu
+     (quote ,(intern (format "org-ref-format-%s" type)))))
+
+  ;; create the completion function
+  (eval `(org-ref-make-completion-function ,type))
+  
+  ;; store new type so it works with adding citations, which checks
+  ;; for existence in this list
+  (add-to-list 'org-ref-cite-types type)
+
+  ;; and finally if a key is specified, we modify the reftex menu
+  (when key
+    (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
+         (append (nth 2 (assoc 'org reftex-cite-format-builtin)) 
+                 `((,key  . ,(concat type ":%l")))))))
+
+;; create all the link types and their completion functions
+(mapcar 'org-ref-define-citation-link org-ref-cite-types)
+#+END_SRC
+
+*** org-ref-insert-cite-link
+We need a convenient method to insert links. In reftex you use the keystroke C-c ], which gives you a minibuffer to search the bibtex files from. This function is bound to that same keystroke here [[*org-mode%20/%20reftex%20setup][org-mode / reftex setup]]. This function will append to a cite link if you call it while on a link.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-ref-insert-cite-link (alternative-cite)
+  "Insert a default citation link using reftex. If you are on a link, it
+appends to the end of the link, otherwise, a new link is
+inserted. Use a prefix arg to get a menu of citation types."
+  (interactive "P")
+  (org-ref-find-bibliography)
+  (let* ((object (org-element-context))
+        (link-string-beginning (org-element-property :begin object))
+        (link-string-end (org-element-property :end object))
+        (path (org-element-property :path object)))  
+
+    (if (not alternative-cite)
+       
+       (cond
+        ;; case where we are in a link
+        ((and (equal (org-element-type object) 'link) 
+              (-contains? org-ref-cite-types (org-element-property :type object)))
+         (goto-char link-string-end)
+         ;; sometimes there are spaces at the end of the link
+         ;; this code moves point pack until no spaces are there
+         (while (looking-back " ") (backward-char))  
+         (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
+
+        ;; We are next to a link, and we want to append
+        ((save-excursion 
+           (backward-char)
+           (and (equal (org-element-type (org-element-context)) 'link) 
+                (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
+         (while (looking-back " ") (backward-char))  
+         (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
+
+        ;; insert fresh link
+        (t 
+         (insert 
+          (concat org-ref-default-citation-link 
+                  ":" 
+                  (mapconcat 'identity (reftex-citation t) ",")))))
+
+      ;; you pressed a C-u so we run this code
+      (reftex-citation)))
+  )
+#+END_SRC
+
+#+RESULTS:
+: org-ref-insert-cite-link
+
+*** Completion in cite links
+If you know the specific bibtex key, you may like to use completion directly. You use this with the org-mode machinery and tab completion. Here is the prototypical completion function. These are now all created when the links are created.
+
+#+BEGIN_SRC emacs-lisp  :tangle no
+(defun org-cite-complete-link (&optional arg)
+  "Completion function for cite links"
+  (format "%s:%s" 
+          org-ref-default-citation-link
+         (completing-read 
+          "bibtex key: " 
+          (let ((bibtex-files (org-ref-find-bibliography)))
+            (bibtex-global-key-alist)))))
+#+END_SRC
+
+Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-insert-cite-with-completion (type)
+  "Insert a cite link with completion"
+  (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
+  (insert (funcall (intern (format "org-%s-complete-link" type)))))
+#+END_SRC
+
+** Storing links to a bibtex entry
+org-mode already defines a store link function for bibtex entries. It does not store the link I want though, it only stores a brief citation of the entry. I want a citation link. Here is a function to do that.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-store-bibtex-entry-link ()
+  "Save a citation link to the current bibtex entry. Saves in the default link type."
+  (interactive)
+  (let ((link (concat org-ref-default-citation-link 
+                ":"   
+                (save-excursion
+                  (bibtex-beginning-of-entry)
+                  (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
+    (message "saved %s" link)
+    (push (list link) org-stored-links)
+    (car org-stored-links)))
+#+END_SRC
+
+** An html bibliography
+This code provides some functions to generate a simple bibliography in html.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-bibtex-keys ()
+  "return a list of unique keys in the buffer"
+  (interactive)
+  (let ((keys '()))
+    (org-element-map (org-element-parse-buffer) 'link
+      (lambda (link)       
+       (let ((plist (nth 1 link)))                          
+         (when (-contains? org-ref-cite-types (plist-get plist ':type))
+           (dolist 
+               (key 
+                (org-ref-split-and-strip-string (plist-get plist ':path)))
+             (when (not (-contains? keys key))
+               (setq keys (append keys (list key)))))))))
+    keys))
+#+END_SRC
+
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-bibtex-entry-html (key)
+ (let ((org-ref-bibliography-files (org-ref-find-bibliography))
+       (file) (entry))
+
+   (setq file (catch 'result
+               (loop for file in org-ref-bibliography-files do
+                     (if (org-ref-key-in-file-p key (file-truename file)) 
+                         (throw 'result file)))))
+   (if file (with-temp-buffer
+              (insert-file-contents file)
+              (prog1
+                  (bibtex-search-entry key nil 0)
+                (setq entry  (org-ref-bib-html-citation)))
+              (format "<li><a id=\"%s\">[%s] %s</a></li>" key key entry)))))
+#+END_SRC
+
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el 
+(defun org-ref-get-html-bibliography ()
+  "Create an html bibliography when there are keys"
+  (let ((keys (org-ref-get-bibtex-keys)))
+    (when keys
+      (concat "<h1>Bibliography</h1>
+<ul>"
+             (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
+             "\n</ul>"))))
+#+END_SRC
+
+* Utilities
+** create simple text citation from bibtex entry
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-bib-citation ()
+  "from a bibtex entry, create and return a simple citation string."
+
+  (bibtex-beginning-of-entry)
+  (let* ((cb (current-buffer))
+        (bibtex-expand-strings t)
+        (entry (loop for (key . value) in (bibtex-parse-entry t)
+                     collect (cons (downcase key) value)))
+        (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
+        (year  (reftex-get-bib-field "year" entry))
+        (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
+        (key (reftex-get-bib-field "=key=" entry))
+        (journal (reftex-get-bib-field "journal" entry))
+        (volume (reftex-get-bib-field "volume" entry))
+        (pages (reftex-get-bib-field "pages" entry))
+        (doi (reftex-get-bib-field "doi" entry))
+        (url (reftex-get-bib-field "url" entry))
+        )
+    ;;authors, "title", Journal, vol(iss):pages (year).
+    (format "%s, \"%s\", %s, %s:%s (%s)"
+           author title journal  volume pages year)))
+#+END_SRC
+
+#+RESULTS:
+: org-ref-bib-citation
+
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-bib-html-citation ()
+  "from a bibtex entry, create and return a simple citation with html links."
+
+  (bibtex-beginning-of-entry)
+  (let* ((cb (current-buffer))
+        (bibtex-expand-strings t)
+        (entry (loop for (key . value) in (bibtex-parse-entry t)
+                     collect (cons (downcase key) value)))
+        (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
+        (year  (reftex-get-bib-field "year" entry))
+        (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
+        (key (reftex-get-bib-field "=key=" entry))
+        (journal (reftex-get-bib-field "journal" entry))
+        (volume (reftex-get-bib-field "volume" entry))
+        (pages (reftex-get-bib-field "pages" entry))
+        (doi (reftex-get-bib-field "doi" entry))
+        (url (reftex-get-bib-field "url" entry))
+        )
+    ;;authors, "title", Journal, vol(iss):pages (year).
+    (concat (format "%s, \"%s\", %s, %s:%s (%s)."
+                   author title journal  volume pages year)
+           (when url (format " <a href=\"%s\">link</a>" url))
+           (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
+    ))
+#+END_SRC
+
+** open pdf from bibtex
+We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-open-bibtex-pdf ()
+  "open pdf for a bibtex entry, if it exists. assumes point is in
+the entry of interest in the bibfile. but does not check that."
+  (interactive)
+  (save-excursion
+    (bibtex-beginning-of-entry)
+    (let* ((bibtex-expand-strings t)
+           (entry (bibtex-parse-entry t))
+           (key (reftex-get-bib-field "=key=" entry))
+           (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
+      (message "%s" pdf)
+      (if (file-exists-p pdf)
+          (org-open-link-from-string (format "[[file:%s]]" pdf))
+        (ding)))))
+#+END_SRC
+
+** open notes from bibtex
+We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-open-bibtex-notes ()
+  "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
+
+I never did figure out how to use reftex to make this happen
+non-interactively. the reftex-format-citation function did not
+work perfectly; there were carriage returns in the strings, and
+it did not put the key where it needed to be. so, below I replace
+the carriage returns and extra spaces with a single space and
+construct the heading by hand."
+  (interactive)
+
+  (bibtex-beginning-of-entry)
+  (let* ((cb (current-buffer))
+        (bibtex-expand-strings t)
+        (entry (loop for (key . value) in (bibtex-parse-entry t)
+                     collect (cons (downcase key) value)))
+        (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
+        (year  (reftex-get-bib-field "year" entry))
+        (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
+        (key (reftex-get-bib-field "=key=" entry))
+        (journal (reftex-get-bib-field "journal" entry))
+        (volume (reftex-get-bib-field "volume" entry))
+        (pages (reftex-get-bib-field "pages" entry))
+        (doi (reftex-get-bib-field "doi" entry))
+        (url (reftex-get-bib-field "url" entry))
+        )
+
+    ;; save key to clipboard to make saving pdf later easier by pasting.
+    (with-temp-buffer
+      (insert key)
+      (kill-ring-save (point-min) (point-max)))
+    
+    ;; now look for entry in the notes file
+    (if  org-ref-bibliography-notes
+       (find-file org-ref-bibliography-notes)
+      (error "org-ref-bib-bibliography-notes is not set to anything"))
+    
+    (goto-char (point-min))
+    ;; put new entry in notes if we don't find it.
+    (unless (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
+      (insert (format "\n** TODO %s - %s" year title))
+      (insert (format"
+ :PROPERTIES:
+  :Custom_ID: %s
+  :AUTHOR: %s
+  :JOURNAL: %s
+  :YEAR: %s
+  :VOLUME: %s
+  :PAGES: %s
+  :DOI: %s
+  :URL: %s
+ :END:
+[[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
+key author journal year volume pages doi url key org-ref-pdf-directory key))
+(save-buffer))))
+#+END_SRC
+
+** open url in browser from bibtex
+
+We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
+
++ This function may be duplicative of bibtex-url. But I think my function is better unless you do some complicated customization of bibtex-generate-url-list.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-open-in-browser ()
+  "Open the bibtex entry at point in a browser using the url field or doi field"
+(interactive)
+(save-excursion
+  (bibtex-beginning-of-entry)
+  (catch 'done
+    (let ((url (bibtex-autokey-get-field "url")))
+      (when  url
+        (browse-url url)
+        (throw 'done nil)))
+
+    (let ((doi (bibtex-autokey-get-field "doi")))
+      (when doi
+        (if (string-match "^http" doi)
+            (browse-url doi)
+          (browse-url (format "http://dx.doi.org/%s" doi)))
+        (throw 'done nil)))
+    (message "No url or doi found"))))
+#+END_SRC
+
+** citeulike
+   I discovered you could upload a bibtex entry to citeulike using http requests. The upload is actually done by a [[*The%20upload%20script][python script]], because it was easy to write. Here is the emacs command to do this. It is not a fast operation, and  do not use it frequently.
+
+*** function to upload bibtex to citeulike
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-upload-bibtex-entry-to-citeulike ()
+  "with point in  a bibtex entry get bibtex string and submit to citeulike.
+
+Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
+  (interactive)
+  (message "uploading to citeulike")
+  (save-restriction
+    (bibtex-narrow-to-entry)
+    (let ((startpos (point-min))
+          (endpos (point-max))
+          (bibtex-string (buffer-string))
+          (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
+      (with-temp-buffer (insert bibtex-string)
+                        (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
+#+END_SRC
+
+*** The upload script
+Here is the python script for uploading. 
+
+*************** TODO document how to get the cookies
+*************** END
+
+
+#+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
+#!python
+import pickle, requests, sys
+
+# reload cookies
+with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
+    cookies = pickle.load(f)
+
+url = 'http://www.citeulike.org/profile/jkitchin/import_do'
+
+bibtex = sys.stdin.read()
+
+data = {'pasted':bibtex,
+        'to_read':2,
+        'tag_parsing':'simple',
+        'strip_brackets':'no',
+        'update_id':'bib-key',
+        'btn_bibtex':'Import BibTeX file ...'}
+
+headers = {'content-type': 'multipart/form-data',
+           'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
+
+r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
+print r
+#+END_SRC
+
+** Build a pdf from a bibtex file
+   It is useful to have a pdf version of an entire bibliography to check it for formatting, spelling, or to share it. This function creates a pdf from a bibtex file. I only include the packages  I commonly use in my bitex files.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-build-full-bibliography ()
+  "build pdf of all bibtex entries, and open it."
+  (interactive)
+  (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
+       (bib-base (file-name-sans-extension bibfile))
+       (texfile (concat bib-base ".tex"))
+       (pdffile (concat bib-base ".pdf")))
+    (find-file texfile)
+    (erase-buffer)
+    (insert (format "\\documentclass[12pt]{article}
+\\usepackage[version=3]{mhchem}
+\\usepackage{url}
+\\usepackage[numbers]{natbib}
+\\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
+\\usepackage{doi}
+\\begin{document}
+\\nocite{*}
+\\bibliographystyle{unsrtnat}
+\\bibliography{%s}
+\\end{document}" bib-base))
+    (save-buffer)
+    (shell-command (concat "pdflatex " bib-base))
+    (shell-command (concat "bibtex " bib-base))
+    (shell-command (concat "pdflatex " bib-base))
+    (shell-command (concat "pdflatex " bib-base))
+    (kill-buffer texfile)
+    (org-open-file pdffile)
+    )) 
+#+END_SRC
+
+** Extract bibtex entries cited in an org-file
+When you use your default bibliography file, and you want to send an org-file to a collaborator, you may need to include bibtex entries so the other person can see them. This function does that and puts the entries in a section at the end of the document that can be tangled to a bib-file.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(defun org-ref-extract-bibtex-entries ()
+  "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
+
+If no bibliography is in the buffer the `reftex-default-bibliography' is used."
+  (interactive)
+  (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
+         (tempname (make-temp-file "extract-bib"))
+         (contents (buffer-string))
+         (cb (current-buffer))
+        basename texfile bibfile results)
+    
+    ;; open tempfile and insert org-buffer contents
+    (find-file tempname)
+    (insert contents)
+    (setq basename (file-name-sans-extension 
+                   (file-name-nondirectory buffer-file-name))
+         texfile (concat tempname ".tex")
+         bibfile (concat tempname ".bib"))
+    
+    ;; see if we have a bibliography, and insert the default one if not.
+    (save-excursion
+      (goto-char (point-min))
+      (unless (re-search-forward "^bibliography:" (point-max) 'end)
+       (insert (format "\nbibliography:%s" 
+                       (mapconcat 'identity reftex-default-bibliography ",")))))
+    (save-buffer)
+
+    ;; get a latex file and extract the references
+    (org-latex-export-to-latex)
+    (find-file texfile)
+    (reftex-parse-all)
+    (reftex-create-bibtex-file bibfile)
+    (save-buffer)
+    ;; save results of the references
+    (setq results (buffer-string))
+
+    ;; kill buffers. these are named by basename, not full path
+    (kill-buffer (concat basename ".bib"))
+    (kill-buffer (concat basename ".tex"))
+    (kill-buffer basename)
+
+    (delete-file bibfile)
+    (delete-file texfile)
+    (delete-file tempname)
+
+    ;; Now back to the original org buffer and insert the results
+    (switch-to-buffer cb)
+    (when (not (string= "" results))
+      (save-excursion
+        (goto-char (point-max))
+        (insert "\n\n")
+       (org-insert-heading)
+       (insert (format " Bibtex entries
+
+,#+BEGIN_SRC text :tangle %s
+%s
+,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
+#+END_SRC
+
+** Find bad cite links
+Depending on how you enter citations, you may have citations with no corresponding bibtex entry. This function finds them and gives you a clickable table to navigate to them.
+
+#+BEGIN_SRC emacs-lisp  :tangle org-ref.el
+(require 'cl)
+
+(defun index (substring list)
+  "return the index of string in a list of strings"
+  (let ((i 0)
+       (found nil))
+    (dolist (arg list i)
+      (if (string-match (concat "^" substring "$") arg)
+         (progn 
+           (setq found t)
+           (return i)))
+      (setq i (+ i 1)))
+    ;; return counter if found, otherwise return nil
+    (if found i nil)))
+
+
+(defun org-ref-find-bad-citations ()
+  "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
+
+Makes a new buffer with clickable links."
+  (interactive)
+  ;; generate the list of bibtex-keys and cited keys
+  (let* ((bibtex-files (org-ref-find-bibliography))
+         (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
+        (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
+        (bad-citations '()))
+
+    (org-element-map (org-element-parse-buffer) 'link
+      (lambda (link)       
+       (let ((plist (nth 1 link)))                          
+         (when (equal (plist-get plist ':type) "cite")
+           (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
+             (when (not (index key bibtex-keys))
+               (setq bad-citations (append bad-citations
+                                           `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
+                                                      key (buffer-name)(plist-get plist ':begin)))))
+               ))))))
+
+    (if bad-citations
+      (progn
+       (switch-to-buffer-other-window "*Missing citations*")
+       (org-mode)
+       (erase-buffer)
+       (insert "* List of bad cite links\n")
+       (insert (mapconcat 'identity bad-citations ""))
+                                       ;(setq buffer-read-only t)
+       (use-local-map (copy-keymap org-mode-map))
+       (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
+
+      (when (get-buffer "*Missing citations*")
+          (kill-buffer "*Missing citations*"))
+      (message "No bad cite links found"))))
+#+END_SRC
+
+** Finding non-ascii characters
+I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them. 
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-find-non-ascii-characters ()
+  "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
+  (interactive)
+  (occur "[^[:ascii:]]"))
+#+END_SRC
+
+** Resort a bibtex entry
+I like neat and orderly bibtex entries.That means the fields are in a standard order that I like. This function reorders the fields in an entry for articles, and makes sure the fields are in lowercase.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-sort-bibtex-entry ()
+  "sort fields of entry in standard order and downcase them"
+  (interactive)
+  (bibtex-beginning-of-entry)
+  (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
+        (entry (bibtex-parse-entry))
+        (entry-fields)
+        (other-fields)
+        (type (cdr (assoc "=type=" entry)))
+        (key (cdr (assoc "=key=" entry))))
+
+    ;; these are the fields we want to order that are in this entry
+    (setq entry-fields (mapcar (lambda (x) (car x)) entry))
+    ;; we do not want to reenter these fields
+    (setq entry-fields (remove "=key=" entry-fields))
+    (setq entry-fields (remove "=type=" entry-fields))
+
+    ;;these are the other fields in the entry
+    (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
+
+    (cond
+     ;; right now we only resort articles
+     ((string= (downcase type) "article") 
+      (bibtex-kill-entry)
+      (insert
+       (concat "@article{" key ",\n" 
+              (mapconcat  
+               (lambda (field) 
+                 (when (member field entry-fields)
+                   (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
+              (mapconcat 
+               (lambda (field) 
+                 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
+              "\n}\n\n"))
+      (bibtex-find-entry key)
+      (bibtex-fill-entry)
+      (bibtex-clean-entry)
+       ))))
+#+END_SRC
+
+** Clean a bibtex entry
+   I like neat and orderly bibtex entries. This code will eventually replace the key with my style key, clean the entry, and sort the fields in the order I like them.
+see [[file:emacs-24.3/lisp/textmodes/bibtex.el::bibtex-autokey-before-presentation-function]] for how to set a function that checks for uniqueness of the key.
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-clean-bibtex-entry(&optional keep-key)
+  "clean and replace the key in a bibtex function. When keep-key is t, do not replace it. You can use a prefix to specify the key should be kept"
+  (interactive "P")
+  (bibtex-beginning-of-entry) 
+(end-of-line)
+  ;; some entries do not have a key or comma in first line. We check and add it, if needed.
+  (unless (string-match ",$" (thing-at-point 'line))
+    (end-of-line)
+    (insert ","))
+
+  ;; check for empty pages, and put eid or article id in its place
+  (let ((entry (bibtex-parse-entry))
+       (pages (bibtex-autokey-get-field "pages"))
+       (year (bibtex-autokey-get-field "year"))
+        (doi  (bibtex-autokey-get-field "doi"))
+        ;; The Journal of Chemical Physics uses eid
+       (eid (bibtex-autokey-get-field "eid")))
+
+    ;; replace http://dx.doi.org/ in doi. some journals put that in,
+    ;; but we only want the doi.
+    (when (string-match "^http://dx.doi.org/" doi)
+      (bibtex-beginning-of-entry)
+      (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
+      (bibtex-kill-field)
+      (bibtex-make-field "doi")
+      (backward-char)
+      (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
+
+    ;; asap articles often set year to 0, which messes up key
+    ;; generation. fix that.
+    (when (string= "0" year)  
+      (bibtex-beginning-of-entry)
+      (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
+      (bibtex-kill-field)
+      (bibtex-make-field "year")
+      (backward-char)
+      (insert (read-string "Enter year: ")))
+
+    ;; fix pages if they are empty if there is an eid to put there.
+    (when (string= "-" pages)
+      (when eid          
+       (bibtex-beginning-of-entry)
+       ;; this seems like a clunky way to set the pages field.But I
+       ;; cannot find a better way.
+       (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
+       (bibtex-kill-field)
+       (bibtex-make-field "pages")
+       (backward-char)
+       (insert eid)))
+
+    ;; replace naked & with \&
+    (save-restriction
+      (bibtex-narrow-to-entry)
+      (bibtex-beginning-of-entry)
+      (message "checking &")
+      (replace-regexp " & " " \\\\& ")
+      (widen))
+
+    ;; generate a key, and if it duplicates an existing key, edit it.
+    (unless keep-key
+      (let ((key (bibtex-generate-autokey)))
+
+       ;; first we delete the existing key
+       (bibtex-beginning-of-entry)
+       (re-search-forward bibtex-entry-maybe-empty-head)
+       (if (match-beginning bibtex-key-in-head)
+           (delete-region (match-beginning bibtex-key-in-head)
+                          (match-end bibtex-key-in-head)))
+       ;; check if the key is in the buffer
+       (when (save-excursion
+               (bibtex-search-entry key))
+         (save-excursion
+           (bibtex-search-entry key)
+           (bibtex-copy-entry-as-kill)
+           (switch-to-buffer-other-window "*duplicate entry*")
+           (bibtex-yank))
+         (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
+
+       (insert key)
+       (kill-new key))) ;; save key for pasting            
+
+    ;; run hooks. each of these operates on the entry with no arguments.
+    ;; this did not work like  i thought, it gives a symbolp error.
+    ;; (run-hooks org-ref-clean-bibtex-entry-hook)
+    (mapcar (lambda (x)
+             (save-restriction
+               (save-excursion
+                 (funcall x))))
+           org-ref-clean-bibtex-entry-hook)
+    
+    ;; sort fields within entry
+    (org-ref-sort-bibtex-entry)
+    ;; check for non-ascii characters
+    (occur "[^[:ascii:]]")
+    ))
+#+END_SRC
+
+#+RESULTS:
+: org-ref-clean-bibtex-entry
+
+** Sort the entries in a citation link by year
+I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-get-citation-year (key)
+  "get the year of an entry with key. Returns year as a string."
+  (interactive)
+  (let* ((results (org-ref-get-bibtex-key-and-file key))
+        (bibfile (cdr results)))
+    (with-temp-buffer
+      (insert-file-contents bibfile)
+      (bibtex-search-entry key nil 0)
+      (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
+        ))))
+
+(defun org-ref-sort-citation-link ()
+ "replace link at point with sorted link by year"
+ (interactive)
+ (let* ((object (org-element-context))  
+        (type (org-element-property :type object))
+       (begin (org-element-property :begin object))
+       (end (org-element-property :end object))
+       (link-string (org-element-property :path object))
+       keys years data)
+  (setq keys (org-ref-split-and-strip-string link-string))
+  (setq years (mapcar 'org-ref-get-citation-year keys)) 
+  (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
+  (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
+  ;; now get the keys separated by commas
+  (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
+  ;; and replace the link with the sorted keys
+  (cl--set-buffer-substring begin end (concat type ":" keys))))
+#+END_SRC
+
+** Sort entries in citation links with shift-arrow keys
+Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defun org-ref-swap-keys (i j keys)
+ "swap the keys in a list with index i and j"
+ (let ((tempi (nth i keys)))
+   (setf (nth i keys) (nth j keys))
+   (setf (nth j keys) tempi))
+  keys)
+
+(defun org-ref-swap-citation-link (direction)
+ "move citation at point in direction +1 is to the right, -1 to the left"
+ (interactive)
+ (let* ((object (org-element-context))  
+        (type (org-element-property :type object))
+       (begin (org-element-property :begin object))
+       (end (org-element-property :end object))
+       (link-string (org-element-property :path object))
+       key keys i)
+   ;;   We only want this to work on citation links
+   (when (-contains? org-ref-cite-types type)
+        (setq key (org-ref-get-bibtex-key-under-cursor))
+       (setq keys (org-ref-split-and-strip-string link-string))
+        (setq i (index key keys))  ;; defined in org-ref
+       (if (> direction 0) ;; shift right
+           (org-ref-swap-keys i (+ i 1) keys)
+         (org-ref-swap-keys i (- i 1) keys))   
+       (setq keys (mapconcat 'identity keys ","))
+       ;; and replace the link with the sorted keys
+       (cl--set-buffer-substring begin end (concat type ":" keys))
+       ;; now go forward to key so we can move with the key
+       (re-search-forward key) 
+       (goto-char (match-beginning 0)))))
+
+;; add hooks to make it work
+(add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
+(add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
+#+END_SRC
+* Aliases
+I like convenience. Here are some aliases for faster typing.
+
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(defalias 'oro 'org-ref-open-citation-at-point)
+(defalias 'orc 'org-ref-citation-at-point)
+(defalias 'orp 'org-ref-open-pdf-at-point)
+(defalias 'oru 'org-ref-open-url-at-point)
+(defalias 'orn 'org-ref-open-notes-at-point)
+
+(defalias 'orib 'org-ref-insert-bibliography-link)
+(defalias 'oric 'org-ref-insert-cite-link)
+(defalias 'orir 'org-ref-insert-ref-link)
+(defalias 'orsl 'org-ref-store-bibtex-entry-link)
+
+(defalias 'orcb 'org-ref-clean-bibtex-entry)
+#+END_SRC
+* End of code
+#+BEGIN_SRC emacs-lisp :tangle org-ref.el
+(provide 'org-ref)
+#+END_SRC
+
+
+* Build                                                                   :noexport:
+
+[[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
+
+[[elisp:(org-babel-load-file "org-ref.org")]]
+
+
+
diff --git a/org-show.el b/org-show.el
new file mode 100644 (file)
index 0000000..a1220d7
--- /dev/null
@@ -0,0 +1,357 @@
+
+;;; org-show.el --- Summary
+;; Copyright(C) 2014 John Kitchin
+
+;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
+;; Contributions from Sacha Chua.
+;; This file is not currently part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2, or (at
+;; your option) any later version.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program ; see the file COPYING.  If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+;; A simple mode for presenting org-files as slide-shows
+
+(defvar org-show-presentation-file nil "File containing the presentation.")
+(defvar org-show-slide-tag "slide" "Tag that marks slides.")
+(defvar org-show-slide-tag-regexp (concat ":" (regexp-quote org-show-slide-tag) ":"))
+(defvar org-show-latex-scale 4.0 "scale for latex preview")
+
+(defvar org-show-original-latex-scale
+  (plist-get org-format-latex-options :scale)
+  "Original scale for latex preview, so we can reset it.")
+
+(defvar org-show-text-scale 4 "scale for text in presentation")
+(defvar org-show-current-slide-number 1 "holds current slide number")
+
+(defvar org-show-mogrify-p (executable-find "mogrify"))
+
+(defvar org-show-tags-column -60 "column position to move tags to in slide mode")
+(defvar org-show-original-tags-column org-tags-column "Save value so we can change back to it")
+
+(when org-show-mogrify-p (require 'eimp))
+
+(require 'easymenu)
+
+(defvar org-show-mode-map
+  (let ((map (make-sparse-keymap)))
+    (define-key map [next] 'org-show-next-slide)
+    (define-key map [prior] 'org-show-previous-slide)
+    
+    (define-key map [f5] 'org-show-start-slideshow)
+    (define-key map [f6] 'org-show-execute-slide)
+    (define-key map (kbd "C--") 'org-show-decrease-text-size)
+    (define-key map (kbd "C-=") 'org-show-increase-text-size)
+    (define-key map (kbd "\e\eg") 'org-show-goto-slide)
+    (define-key map (kbd "\e\et") 'org-show-toc)
+    (define-key map (kbd "\e\eq") 'org-show-stop-slideshow)
+    map)
+  "Keymap for org-show-mode.")
+
+(easy-menu-define my-menu org-show-mode-map "My own menu"
+  '("org-show"
+    ["Start slide show" org-show-start-slideshow t]
+    ["Next slide" org-show-next-slide t]
+    ["Previous slide" org-show-previous-slide t]
+    ["Open this slide" org-show-open-slide t]
+    ["Goto slide" org-show-goto-slide t]
+    ["Table of contents" org-show-toc t]
+    ["Stop slide show"  org-show-stop-slideshow t]
+))
+
+
+(define-minor-mode org-show-mode
+  "Minor mode for org-show
+
+\\{org-show-mode-map}"
+  :lighter " org-show"
+  :global t
+  :keymap org-show-mode-map)
+
+(defvar org-show-temp-images '() "list of temporary images")
+
+(defun org-show-execute-slide ()
+  "Process slide at point.
+  If it contains an Emacs Lisp source block, evaluate it.
+  If it contains an image, view it in a split buffer
+  Else, focus on that buffer.
+  Hide all drawers."
+  (interactive)
+  (setq org-show-presentation-file (expand-file-name (buffer-name)))
+  (delete-other-windows)  
+
+  ;; make sure nothing is folded. This seems to be necessary to
+  ;; prevent an error on narrowing then trying to make latex fragments
+  ;; I think.
+  (org-cycle '(64))
+
+  (org-narrow-to-subtree)
+  (visual-line-mode 1)
+  (let ((heading-text (nth 4 (org-heading-components)))
+        (org-format-latex-options (plist-put org-format-latex-options :scale org-show-latex-scale)))
+
+    (set-frame-name (format "%-180s%15s%s" heading-text "slide " (cdr (assoc heading-text org-show-slide-titles))))
+
+    ;; preview equations in the current subtree
+    (org-preview-latex-fragment '(4))
+    (message "") ; clear minibuffer
+    (cond
+
+     ;; view images if there is one. WE only do this this for the first one.
+     ((and (goto-char (point-min))
+           (re-search-forward "\\[\\[\\(.*\\.\\(jpg\\|gif\\|png\\)\\)" nil t))
+      
+      (unless (file-exists-p "org-show-images")
+       (make-directory "org-show-images"))
+      
+      (let* ((png-file (match-string 1))
+            (temp-png (expand-file-name (concat "org-show-images/" (secure-hash 'sha1
+                                           (with-temp-buffer
+                                             (insert-file-contents png-file)
+                                             (buffer-string))) ".png"))))
+
+        (add-to-list 'org-show-temp-images temp-png)
+       (unless (file-exists-p temp-png)
+         (copy-file png-file temp-png t))
+      
+       (split-window-right)      
+      
+       (other-window 1)
+       (find-file temp-png)
+        (when org-show-mogrify-p
+          (eimp-fit-image-width-to-window nil)))
+                  
+      (other-window 1) ; back to slide
+      (goto-char (point-min))
+      (text-scale-set org-show-text-scale)
+      (org-display-inline-images)
+      (org-cycle-hide-drawers t)
+      (org-show-subtree))
+
+     ;; find and execute source code blocks.
+     ;; you can either have images, or code. Not both.
+     ;; Only code blocks of type emacs-lisp-slide are used.
+     ((and (goto-char (point-min))
+           (re-search-forward "#\\+begin_src emacs-lisp-slide" nil t))
+      (let ((info (org-babel-get-src-block-info)))
+        (unwind-protect
+            (eval (read (concat "(progn " (nth 1 info) ")"))))))
+
+     ;; plain text slides
+     (t
+      (switch-to-buffer (current-buffer))
+      (text-scale-set org-show-text-scale)
+      (org-show-subtree)
+      (org-cycle-hide-drawers t)
+      (org-display-inline-images)
+      (delete-other-windows)))))
+
+(defun org-show-next-slide ()
+  "Goto next slide in presentation"
+  (interactive)
+  (find-file org-show-presentation-file)
+  (widen)
+  (if (<= (+ org-show-current-slide-number 1) (length org-show-slide-titles))
+      (progn
+       (setq org-show-current-slide-number (+ org-show-current-slide-number 1))
+       (org-show-goto-slide org-show-current-slide-number))
+    (org-show-goto-slide org-show-current-slide-number)
+    (message "This is the end. My only friend the end.  Jim Morrison.")))
+
+(defun org-show-previous-slide ()
+  "Goto previous slide in the list"
+  (interactive)
+  (find-file org-show-presentation-file)
+  (widen)
+  (if (> (- org-show-current-slide-number 1) 0)
+      (progn
+       (setq org-show-current-slide-number (- org-show-current-slide-number 1))
+       (org-show-goto-slide org-show-current-slide-number))
+    (org-show-goto-slide org-show-current-slide-number)
+    (message "Once upon a time...")))
+
+(defun org-show-open-slide ()
+ "Start show at this slide"
+ (setq org-show-presentation-file (expand-file-name (buffer-name))) 
+ (org-show-initialize)
+ (let ((n (cdr (assoc (nth 4 (org-heading-components)) org-show-slide-titles))))
+   (setq org-show-current-slide-number n)
+   (org-show-goto-slide n)))
+
+(defvar org-show-slide-list '() "List of slide numbers and markers to each slide")
+(defvar org-show-slide-titles '() "List of titles and slide numbers for each slide")
+
+(defun org-show-initialize ()
+  ;; make slide lists for future navigation. rerun this if you change slide order
+  (setq  org-show-slide-titles '()
+         org-show-temp-images '()
+         org-show-slide-list '())
+     
+  (let ((n 0))
+    (org-map-entries
+     (lambda ()
+       (when (string-match-p ":slide:" (or (nth 5 (org-heading-components)) ""))
+        (setq n (+ n 1))
+         
+        (add-to-list 'org-show-slide-titles 
+                     (cons (nth 4 (org-heading-components)) n) t)
+
+        (add-to-list 'org-show-slide-list 
+                     (cons n (set-marker (make-marker) (point))) t))))))
+
+(defun org-show-start-slideshow ()
+  "Start the slide show, at the beginning"
+  (interactive)
+    
+  (setq org-show-presentation-file (expand-file-name (buffer-name)))
+  (beginning-of-buffer)
+  (setq org-tags-column org-show-tags-column)
+  (org-set-tags-command '(4) t)
+
+  (org-show-initialize)
+  ;; hide slide tags
+  (save-excursion
+    (while (re-search-forward ":slide:" nil t)
+      (overlay-put
+       (make-overlay (match-beginning 0)(match-end 0))
+       'invisible 'slide)))
+  (add-to-invisibility-spec 'slide)
+  (beginning-of-buffer)
+  (delete-other-windows)
+  (org-show-mode 1)
+  (setq org-show-current-slide-number 1)
+  (org-show-goto-slide 1))
+
+(defun org-show-stop-slideshow ()
+  (interactive)
+  ;; make slide tag visible again
+  (remove-from-invisibility-spec 'slide)
+
+  ;; reset latex scale
+  (plist-put org-format-latex-options :scale org-show-original-latex-scale)
+
+  ;; clean up temp images
+  (mapcar (lambda (x)
+           (let ((bname (file-name-nondirectory x)))
+             (when (get-buffer bname)
+                (set-buffer bname) 
+                (save-buffer)
+               (kill-buffer bname)))
+
+           (when (file-exists-p x)
+             (delete-file x)))
+         org-show-temp-images)
+  (setq org-show-temp-images '())
+
+  ;; ;; clean up miscellaneous buffers
+  (when (get-buffer "*Animation*") (kill-buffer "*Animation*"))
+
+  (when org-show-presentation-file (find-file org-show-presentation-file))
+  (widen)
+  (text-scale-set 0)
+  (delete-other-windows)
+  (setq org-show-presentation-file nil)
+  (setq org-show-current-slide-number 1)
+  (set-frame-name (if (buffer-file-name)
+                   (abbreviate-file-name (buffer-file-name))))
+  (setq org-tags-column org-show-original-tags-column)
+  (org-set-tags-command '(4) t)
+
+  (org-show-mode -1))
+
+(defalias 'stop 'org-show-stop-slideshow)
+
+(defun org-show-goto-slide (n)
+ "Goto slide N"
+ (interactive "nSlide number: ")
+ (message "Going to slide %s" n)
+ (find-file org-show-presentation-file)
+ (setq org-show-current-slide-number n)
+ (widen)
+ (goto-char (cdr (assoc n org-show-slide-list)))
+ (org-show-execute-slide))
+
+(defun org-show-toc ()
+  (interactive)
+  (let ((links) (c-b (buffer-name)) (n))
+    (save-excursion
+      (widen)
+      (mapcar
+       (lambda (x)
+        (setq n (car x))
+        (goto-char (cdr x))
+        (add-to-list
+         'links
+         (format " [[elisp:(progn (switch-to-buffer \"%s\")(goto-char %s)(org-show-execute-slide))][%2s %s]]\n\n"
+                 (marker-buffer (cdr x))
+                 (marker-position (cdr x))
+                 (car x)
+                 (nth 4 (org-heading-components))) t))
+             org-show-slide-list))
+    
+    (switch-to-buffer "*List of Slides*")
+    (org-mode)
+    (erase-buffer)
+    
+    (insert (mapconcat 'identity links ""))
+  
+    ;(setq buffer-read-only t)
+    (use-local-map (copy-keymap org-mode-map))
+    (local-set-key "q" #'(lambda () (interactive) (kill-buffer)))))
+
+(require 'animate)
+
+(defun org-show-animate (strings)
+  "Animate STRINGS in an *Animation* buffer"
+  (switch-to-buffer (get-buffer-create
+                     (or animation-buffer-name
+                         "*Animation*")))
+  (erase-buffer)
+  (text-scale-set 6)
+  (let* ((vpos (/ (- 20
+                    1 ;; For the mode-line
+                    (1- (length strings)) 
+                    (length strings))
+                 2))
+        (width 43)
+        hpos)
+    (while strings
+      (setq hpos (/ (- width (length (car strings))) 2))
+      (when (> 0 hpos) (setq hpos 0))
+      (when (> 0 vpos) (setq vpos 0))
+      (animate-string (car strings) vpos hpos)
+      (setq vpos (1+ vpos))
+      (setq strings (cdr strings)))))
+
+(defun org-show-increase-text-size (&optional arg)
+  "Increase text size. Bound to \\[org-show-increase-text-size].
+
+With prefix ARG, set `org-show-text-scale' so subsquent slides are the same text size."
+  (interactive "P")
+  (text-scale-increase 1.5)
+  (when arg
+    (setq org-show-text-scale (* org-show-text-scale 1.5))))
+
+(defun org-show-decrease-text-size (&optional arg)
+  "Increase text size. Bound to \\[org-show-decrease-text-size].
+
+With prefix ARG, set `org-show-text-scale' so subsquent slides are the same text size."
+  (interactive "P")
+  (text-scale-decrease 1.5)
+  (when arg
+    (setq org-show-text-scale (/ org-show-text-scale 1.5)))
+)
+
+(provide 'org-show)
diff --git a/org-show.org b/org-show.org
new file mode 100644 (file)
index 0000000..d917a60
--- /dev/null
@@ -0,0 +1,679 @@
+#+TITLE: org-show - simple presentations in org-mode
+#+AUTHOR: John Kitchin
+
+There are several options for "presenting" from org-mode. Here are the options I found.
+
+https://github.com/rlister/org-present
+https://github.com/eschulte/epresent
+
+https://github.com/yjwen/org-reveal
+https://github.com/takaxp/org-tree-slide/
+https://github.com/tucasp/org-presie
+
+http://orgmode.org/worg/exporters/beamer/tutorial.html
+http://orgmode.org/worg/org-tutorials/non-beamer-presentations.html#sec-3
+
+The one I like the best is discussed here: http://sachachua.com/blog/2013/04/how-to-present-using-org-mode-in-emacs/. I like it best because you can edit the slides as you go, execute arbitrary emacs code, and it is still pretty simple. I used Sacha's code as the basis for org-show. There is a lot of similarity.
+
+elisp:org-show-mode
+
+elisp:org-show-start-slideshow
+
+* org-show
+You can have: 
+
+1. code run
+2. split to show slide and full image
+3. plain text
+
+** Title slide                                                       :slide:
+#+BEGIN_SRC emacs-lisp-slide
+(org-show-animate '("Welcome to the org-show" "John Kitchin"))
+#+END_SRC
+
+** Presentations in org-mode                                         :slide:
+This should be easy
+
+1. Create your org-file. Tag headlines with :slide:
+2. Enter org-show-mode, press f5. Use PageUp and PageDn to navigate slides
+3. Go back and forth from the presentation to other files in Emacs or other software.
+4. Edit yours slides as you go, e.g. to demonstrate something 
+5. Totally interactive, run code, etc...
+
+org-show is based on this blog post: http://sachachua.com/blog/2013/04/how-to-present-using-org-mode-in-emacs/
+
+Thanks Sacha!
+** Test out some themes                                                      :slide:
+
+[[elisp:(load-theme 'my)]] [[elisp:(disable-theme 'my)]]
+
+[[elisp:(load-theme 'adwaita)]] [[elisp:(disable-theme 'adwaita)]]
+
+[[elisp:(load-theme 'deeper-blue)]] [[elisp:(disable-theme 'deeper-blue)]]
+
+[[elisp:(load-theme 'light-blue)]] [[elisp:(disable-theme 'light-blue)]]
+
+[[elisp:(load-theme 'manoj-dark)]] [[elisp:(disable-theme 'manoj-dark)]]
+
+[[elisp:(load-theme 'misterioso)]] [[elisp:(disable-theme 'misterioso)]]
+
+[[elisp:(load-theme 'tango)]] [[elisp:(disable-theme 'tango)]]
+
+[[elisp:(load-theme 'tango-dark)]] [[elisp:(disable-theme 'tango-dark)]]
+
+[[elisp:(load-theme 'tsdh-dark)]] [[elisp:(disable-theme 'tsdh-dark)]]
+
+[[elisp:(load-theme 'tsdh-light)]] [[elisp:(disable-theme 'tsdh-light)]]
+
+[[elisp:(load-theme 'wheatgrass)]] [[elisp:(disable-theme 'wheatgrass)]]
+
+[[elisp:(load-theme 'whiteboard)]] [[elisp:(disable-theme 'whiteboard)]]
+
+[[elisp:(load-theme 'wombat)]] [[elisp:(disable-theme 'wombat)]]
+
+[[elisp:(load-theme 'solarized-light t)]] [[elisp:(disable-theme 'solarized-light)]] 
+
+[[elisp:(load-theme 'solarized-dark t)]] [[elisp:(disable-theme 'solarized-dark)]]
+
+[[elisp:(load-theme 'zenburn t)]] [[elisp:(disable-theme 'zenburn)]]
+
+[[elisp:(load-theme 'anti-zenburn t)]] [[elisp:(disable-theme 'anti-zenburn)]]
+
+** Equations                                                         :slide:
+It should be easy to show equations like this  $\int_0^x \frac{1}{2} \sin x dx = 6$.
+
+It is. Maybe you prefer equation environments?
+
+\begin{equation}
+e^x = 55
+\end{equation}
+
+Want to see the equation source? [[elisp:(org-ctrl-c-ctrl-c)][click here]]
+
+Back to equations: C-c C-x C-l
+** Figures                                                           :slide:
+
+Figures should show up in two panes.
+The left pane shows the slide. The right pane shows the figure, scaled to fit in the window.
+
+Here is a little screen capture:
+[[./taskbar.png]]
+
+** Need a more complicated layout?                                   :slide:
+Write some code to generate it, and put it in an emacs-lisp-slide block. org-show will run it and show you the result
+
+#+BEGIN_SRC emacs-lisp
+(delete-other-windows)
+(split-window-right)
+(other-window 1)
+(find-file "taskbar.png")
+(split-window-below)
+(other-window 1)
+(find-file "doi-utils.org")
+#+END_SRC
+
+#+RESULTS:
+: #<buffer doi-utils.org>
+
+#+BEGIN_EXAMPLE
+,#+BEGIN_SRC emacs-lisp-slide
+(delete-other-windows)
+(split-window-right)
+(other-window 1)
+(find-file "taskbar.png")
+(split-window-below)
+(other-window 1)
+(find-file "doi-utils.org")
+,#+END_SRC
+#+END_EXAMPLE
+
+** A complicated layout                                                      :slide:
+#+BEGIN_SRC emacs-lisp-slide
+(delete-other-windows)
+(split-window-right)
+(other-window 1)
+(find-file "taskbar.png")
+(split-window-below)
+(other-window 1)
+(find-file "doi-utils.org")
+#+END_SRC
+** Code blocks should be runnable and editable                       :slide:
+
+#+BEGIN_SRC python
+print 6 + 62
+#+END_SRC
+
+
+They are.
+** We can use many languages                                         :slide:
+(of course, you must have them installed on your computer)
+
+#+BEGIN_SRC emacs-lisp
+(+ 6 6)
+#+END_SRC
+
+
+#+BEGIN_SRC R 
+sum(c(6, 6))
+#+END_SRC
+
+
+
+#+BEGIN_SRC perl :results output
+print 6 + 6
+#+END_SRC
+
+
+#+BEGIN_SRC ruby
+print 6 + 6
+#+END_SRC
+
+#+RESULTS:
+
+
+** Interactivity is important  
+We get it.
+*** Snake                                                            :slide:
+#+BEGIN_SRC emacs-lisp-slide
+(snake)
+#+END_SRC
+
+*** tetris                                                           :slide:
+
+#+BEGIN_SRC emacs-lisp-slide
+(when (and (boundp 'snake-buffer-name) (get-buffer snake-buffer-name))
+  (kill-buffer snake-buffer-name))
+(delete-other-windows)
+(tetris)
+#+END_SRC
+
+
+*** doctor                                                           :slide:
+#+BEGIN_SRC emacs-lisp-slide
+(doctor)
+#+END_SRC
+
+
+*** Become a graffiti artist                                         :slide:
+#+BEGIN_SRC emacs-lisp-slide
+(progn
+  (switch-to-buffer (get-buffer-create "*artist*"))
+  (erase-buffer)
+  (artist-mode 1)
+  (menu-bar-mode 1)
+  (text-scale-set 0)
+  (artist-select-op-spray-can))
+#+END_SRC
+
+
+*** Or draw lines                                                    :slide:
+#+BEGIN_SRC emacs-lisp-slide
+(progn
+  (switch-to-buffer (get-buffer-create "*artist*"))
+  (artist-select-op-line))
+#+END_SRC
+
+** No seriously, we can do real work!                                :slide:
+   :PROPERTIES:
+   :CUSTOM_ID: sec:data-tab-code
+   :END:
+
+Use this table as a data source.
+#+tblname: tab-data
+| x |  y |
+|---+----|
+| 1 |  1 |
+| 2 |  4 |
+| 3 |  9 |
+| 4 | 16 |
+
+#+BEGIN_SRC python :var data=tab-data
+import matplotlib.pyplot as plt
+import numpy as np
+d = np.array(data)
+plt.plot(d[:,0], d[:,1])
+plt.show()
+#+END_SRC  
+
+#+RESULTS:
+
+You can make links to a table like this: ref:tab-data.
+** Interactive links                                                 :slide:
+<<beginning>>
+
+You can have links that take you to places: [[beginning]], [[end]], to a [[#sec:data-tab-code][section]],
+
+Or links that are functional: cite:mehta-2014-ident-poten. 
+
+Or that run code [[elisp:(message "Hello %s" user-full-name)]]
+
+Or links to info: [[info:org#External%20links][info:org#External links]]
+
+Or to open a [[http://kitchingroup.cheme.cmu.edu][website]].
+
+<<end>>
+** Conclusions                                                       :slide:
+That is the end!
+
+#+BEGIN_SRC emacs-lisp-slide
+(org-show-animate '("That's the end of the org-show." "Thank you for your attention!" "http://github.com/jkitchin/jmax"))
+#+END_SRC
+
+
+* The code
+
+** The header
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+;;; org-show.el --- Summary
+;; Copyright(C) 2014 John Kitchin
+
+;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
+;; Contributions from Sacha Chua.
+;; This file is not currently part of GNU Emacs.
+
+;; This program is free software; you can redistribute it and/or
+;; modify it under the terms of the GNU General Public License as
+;; published by the Free Software Foundation; either version 2, or (at
+;; your option) any later version.
+
+;; This program is distributed in the hope that it will be useful, but
+;; WITHOUT ANY WARRANTY; without even the implied warranty of
+;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+;; General Public License for more details.
+
+;; You should have received a copy of the GNU General Public License
+;; along with this program ; see the file COPYING.  If not, write to
+;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+;; Boston, MA 02111-1307, USA.
+
+;;; Commentary:
+;; A simple mode for presenting org-files as slide-shows
+#+END_SRC
+
+** Some basic setup
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defvar org-show-presentation-file nil "File containing the presentation.")
+(defvar org-show-slide-tag "slide" "Tag that marks slides.")
+(defvar org-show-slide-tag-regexp (concat ":" (regexp-quote org-show-slide-tag) ":"))
+(defvar org-show-latex-scale 4.0 "scale for latex preview")
+
+(defvar org-show-original-latex-scale
+  (plist-get org-format-latex-options :scale)
+  "Original scale for latex preview, so we can reset it.")
+
+(defvar org-show-text-scale 4 "scale for text in presentation")
+(defvar org-show-current-slide-number 1 "holds current slide number")
+
+(defvar org-show-mogrify-p (executable-find "mogrify"))
+
+(defvar org-show-tags-column -60 "column position to move tags to in slide mode")
+(defvar org-show-original-tags-column org-tags-column "Save value so we can change back to it")
+
+(when org-show-mogrify-p (require 'eimp))
+
+
+#+END_SRC
+
+** Make a minor mode and menu
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(require 'easymenu)
+
+(defvar org-show-mode-map
+  (let ((map (make-sparse-keymap)))
+    (define-key map [next] 'org-show-next-slide)
+    (define-key map [prior] 'org-show-previous-slide)
+    
+    (define-key map [f5] 'org-show-start-slideshow)
+    (define-key map [f6] 'org-show-execute-slide)
+    (define-key map (kbd "C--") 'org-show-decrease-text-size)
+    (define-key map (kbd "C-=") 'org-show-increase-text-size)
+    (define-key map (kbd "\e\eg") 'org-show-goto-slide)
+    (define-key map (kbd "\e\et") 'org-show-toc)
+    (define-key map (kbd "\e\eq") 'org-show-stop-slideshow)
+    map)
+  "Keymap for org-show-mode.")
+
+(easy-menu-define my-menu org-show-mode-map "My own menu"
+  '("org-show"
+    ["Start slide show" org-show-start-slideshow t]
+    ["Next slide" org-show-next-slide t]
+    ["Previous slide" org-show-previous-slide t]
+    ["Open this slide" org-show-open-slide t]
+    ["Goto slide" org-show-goto-slide t]
+    ["Table of contents" org-show-toc t]
+    ["Stop slide show"  org-show-stop-slideshow t]
+))
+
+
+(define-minor-mode org-show-mode
+  "Minor mode for org-show
+
+\\{org-show-mode-map}"
+  :lighter " org-show"
+  :global t
+  :keymap org-show-mode-map)
+#+END_SRC
+
+** Prepare and show the slide 
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+
+(defvar org-show-temp-images '() "list of temporary images")
+
+(defun org-show-execute-slide ()
+  "Process slide at point.
+  If it contains an Emacs Lisp source block, evaluate it.
+  If it contains an image, view it in a split buffer
+  Else, focus on that buffer.
+  Hide all drawers."
+  (interactive)
+  (setq org-show-presentation-file (expand-file-name (buffer-name)))
+  (delete-other-windows)  
+
+  ;; make sure nothing is folded. This seems to be necessary to
+  ;; prevent an error on narrowing then trying to make latex fragments
+  ;; I think.
+  (org-cycle '(64))
+
+  (org-narrow-to-subtree)
+  (visual-line-mode 1)
+  (let ((heading-text (nth 4 (org-heading-components)))
+        (org-format-latex-options (plist-put org-format-latex-options :scale org-show-latex-scale)))
+
+    (set-frame-name (format "%-180s%15s%s" heading-text "slide " (cdr (assoc heading-text org-show-slide-titles))))
+
+    ;; preview equations in the current subtree
+    (org-preview-latex-fragment '(4))
+    (message "") ; clear minibuffer
+    (cond
+
+     ;; view images if there is one. WE only do this this for the first one.
+     ((and (goto-char (point-min))
+           (re-search-forward "\\[\\[\\(.*\\.\\(jpg\\|gif\\|png\\)\\)" nil t))
+      
+      (unless (file-exists-p "org-show-images")
+       (make-directory "org-show-images"))
+      
+      (let* ((png-file (match-string 1))
+            (temp-png (expand-file-name (concat "org-show-images/" (secure-hash 'sha1
+                                           (with-temp-buffer
+                                             (insert-file-contents png-file)
+                                             (buffer-string))) ".png"))))
+
+        (add-to-list 'org-show-temp-images temp-png)
+       (unless (file-exists-p temp-png)
+         (copy-file png-file temp-png t))
+      
+       (split-window-right)      
+      
+       (other-window 1)
+       (find-file temp-png)
+        (when org-show-mogrify-p
+          (eimp-fit-image-width-to-window nil)))
+                  
+      (other-window 1) ; back to slide
+      (goto-char (point-min))
+      (text-scale-set org-show-text-scale)
+      (org-display-inline-images)
+      (org-cycle-hide-drawers t)
+      (org-show-subtree))
+
+     ;; find and execute source code blocks.
+     ;; you can either have images, or code. Not both.
+     ;; Only code blocks of type emacs-lisp-slide are used.
+     ((and (goto-char (point-min))
+           (re-search-forward "#\\+begin_src emacs-lisp-slide" nil t))
+      (let ((info (org-babel-get-src-block-info)))
+        (unwind-protect
+            (eval (read (concat "(progn " (nth 1 info) ")"))))))
+
+     ;; plain text slides
+     (t
+      (switch-to-buffer (current-buffer))
+      (text-scale-set org-show-text-scale)
+      (org-show-subtree)
+      (org-cycle-hide-drawers t)
+      (org-display-inline-images)
+      (delete-other-windows)))))
+#+END_SRC
+
+** Next and previous slides
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defun org-show-next-slide ()
+  "Goto next slide in presentation"
+  (interactive)
+  (find-file org-show-presentation-file)
+  (widen)
+  (if (<= (+ org-show-current-slide-number 1) (length org-show-slide-titles))
+      (progn
+       (setq org-show-current-slide-number (+ org-show-current-slide-number 1))
+       (org-show-goto-slide org-show-current-slide-number))
+    (org-show-goto-slide org-show-current-slide-number)
+    (message "This is the end. My only friend the end.  Jim Morrison.")))
+#+END_SRC
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defun org-show-previous-slide ()
+  "Goto previous slide in the list"
+  (interactive)
+  (find-file org-show-presentation-file)
+  (widen)
+  (if (> (- org-show-current-slide-number 1) 0)
+      (progn
+       (setq org-show-current-slide-number (- org-show-current-slide-number 1))
+       (org-show-goto-slide org-show-current-slide-number))
+    (org-show-goto-slide org-show-current-slide-number)
+    (message "Once upon a time...")))
+#+END_SRC
+
+** Open this slide
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defun org-show-open-slide ()
+ "Start show at this slide"
+ (setq org-show-presentation-file (expand-file-name (buffer-name))) 
+ (org-show-initialize)
+ (let ((n (cdr (assoc (nth 4 (org-heading-components)) org-show-slide-titles))))
+   (setq org-show-current-slide-number n)
+   (org-show-goto-slide n)))
+#+END_SRC
+
+** Starting the show
+We need some functions for convenient starting and stopping.
+
+On starting, we want to map the slides so we can get slide numbers for navigation and to display them on the frame. We also make the slide tags invisible. We set some temporary key bindings. These need to be global because sometimes we navigate out of the slideshow buffer, and we want page up and down to go to the next slides no matter where we are.
+
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defvar org-show-slide-list '() "List of slide numbers and markers to each slide")
+(defvar org-show-slide-titles '() "List of titles and slide numbers for each slide")
+
+(defun org-show-initialize ()
+  ;; make slide lists for future navigation. rerun this if you change slide order
+  (setq  org-show-slide-titles '()
+         org-show-temp-images '()
+         org-show-slide-list '())
+     
+  (let ((n 0))
+    (org-map-entries
+     (lambda ()
+       (when (string-match-p ":slide:" (or (nth 5 (org-heading-components)) ""))
+        (setq n (+ n 1))
+         
+        (add-to-list 'org-show-slide-titles 
+                     (cons (nth 4 (org-heading-components)) n) t)
+
+        (add-to-list 'org-show-slide-list 
+                     (cons n (set-marker (make-marker) (point))) t))))))
+
+(defun org-show-start-slideshow ()
+  "Start the slide show, at the beginning"
+  (interactive)
+    
+  (setq org-show-presentation-file (expand-file-name (buffer-name)))
+  (beginning-of-buffer)
+  (setq org-tags-column org-show-tags-column)
+  (org-set-tags-command '(4) t)
+
+  (org-show-initialize)
+  ;; hide slide tags
+  (save-excursion
+    (while (re-search-forward ":slide:" nil t)
+      (overlay-put
+       (make-overlay (match-beginning 0)(match-end 0))
+       'invisible 'slide)))
+  (add-to-invisibility-spec 'slide)
+  (beginning-of-buffer)
+  (delete-other-windows)
+  (org-show-mode 1)
+  (setq org-show-current-slide-number 1)
+  (org-show-goto-slide 1))
+#+END_SRC
+
+** Stop the show
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defun org-show-stop-slideshow ()
+  (interactive)
+  ;; make slide tag visible again
+  (remove-from-invisibility-spec 'slide)
+
+  ;; reset latex scale
+  (plist-put org-format-latex-options :scale org-show-original-latex-scale)
+
+  ;; clean up temp images
+  (mapcar (lambda (x)
+           (let ((bname (file-name-nondirectory x)))
+             (when (get-buffer bname)
+                (set-buffer bname) 
+                (save-buffer)
+               (kill-buffer bname)))
+
+           (when (file-exists-p x)
+             (delete-file x)))
+         org-show-temp-images)
+  (setq org-show-temp-images '())
+
+  ;; ;; clean up miscellaneous buffers
+  (when (get-buffer "*Animation*") (kill-buffer "*Animation*"))
+
+  (when org-show-presentation-file (find-file org-show-presentation-file))
+  (widen)
+  (text-scale-set 0)
+  (delete-other-windows)
+  (setq org-show-presentation-file nil)
+  (setq org-show-current-slide-number 1)
+  (set-frame-name (if (buffer-file-name)
+                   (abbreviate-file-name (buffer-file-name))))
+  (setq org-tags-column org-show-original-tags-column)
+  (org-set-tags-command '(4) t)
+
+  (org-show-mode -1))
+
+(defalias 'stop 'org-show-stop-slideshow)
+#+END_SRC
+
+** Goto a slide
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defun org-show-goto-slide (n)
+ "Goto slide N"
+ (interactive "nSlide number: ")
+ (message "Going to slide %s" n)
+ (find-file org-show-presentation-file)
+ (setq org-show-current-slide-number n)
+ (widen)
+ (goto-char (cdr (assoc n org-show-slide-list)))
+ (org-show-execute-slide))
+#+END_SRC
+
+** Table of contents
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defun org-show-toc ()
+  (interactive)
+  (let ((links) (c-b (buffer-name)) (n))
+    (save-excursion
+      (widen)
+      (mapcar
+       (lambda (x)
+        (setq n (car x))
+        (goto-char (cdr x))
+        (add-to-list
+         'links
+         (format " [[elisp:(progn (switch-to-buffer \"%s\")(goto-char %s)(org-show-execute-slide))][%2s %s]]\n\n"
+                 (marker-buffer (cdr x))
+                 (marker-position (cdr x))
+                 (car x)
+                 (nth 4 (org-heading-components))) t))
+             org-show-slide-list))
+    
+    (switch-to-buffer "*List of Slides*")
+    (org-mode)
+    (erase-buffer)
+    
+    (insert (mapconcat 'identity links ""))
+  
+    ;(setq buffer-read-only t)
+    (use-local-map (copy-keymap org-mode-map))
+    (local-set-key "q" #'(lambda () (interactive) (kill-buffer)))))
+#+END_SRC
+
+** Utilities
+It seems like we might animate enough to have a function
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(require 'animate)
+
+(defun org-show-animate (strings)
+  "Animate STRINGS in an *Animation* buffer"
+  (switch-to-buffer (get-buffer-create
+                     (or animation-buffer-name
+                         "*Animation*")))
+  (erase-buffer)
+  (text-scale-set 6)
+  (let* ((vpos (/ (- 20
+                    1 ;; For the mode-line
+                    (1- (length strings)) 
+                    (length strings))
+                 2))
+        (width 43)
+        hpos)
+    (while strings
+      (setq hpos (/ (- width (length (car strings))) 2))
+      (when (> 0 hpos) (setq hpos 0))
+      (when (> 0 vpos) (setq vpos 0))
+      (animate-string (car strings) vpos hpos)
+      (setq vpos (1+ vpos))
+      (setq strings (cdr strings)))))
+#+END_SRC
+
+dynamic rescalling of text size
+
+#+BEGIN_SRC emacs-lisp :tangle org-show.el
+(defun org-show-increase-text-size (&optional arg)
+  "Increase text size. Bound to \\[org-show-increase-text-size].
+
+With prefix ARG, set `org-show-text-scale' so subsquent slides are the same text size."
+  (interactive "P")
+  (text-scale-increase 1.5)
+  (when arg
+    (setq org-show-text-scale (* org-show-text-scale 1.5))))
+
+(defun org-show-decrease-text-size (&optional arg)
+  "Increase text size. Bound to \\[org-show-decrease-text-size].
+
+With prefix ARG, set `org-show-text-scale' so subsquent slides are the same text size."
+  (interactive "P")
+  (text-scale-decrease 1.5)
+  (when arg
+    (setq org-show-text-scale (/ org-show-text-scale 1.5)))
+)
+#+END_SRC
+
+** End
+#+BEGIN_SRC emacs-lisp  :tangle org-show.el
+(provide 'org-show)
+#+END_SRC
+* build
+[[elisp:(org-babel-load-file "org-show.org")]]