]> git.donarmstrong.com Git - org-ref.git/blob - doi-utils.org
e6c026688399f477ba677b39961d8b756efbe90a
[org-ref.git] / doi-utils.org
1 #+TITLE: DOI utilities for making bibtex entries and downloading pdfs
2
3 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.
4
5 The principle commands you will use from here are:
6
7 - doi-utils-get-bibtex-entry-pdf with the cursor in a bibtex entry.
8 - doi-utils-insert-bibtex-entry-from-doi to insert a bibtex entry at your cursor, clean it and try to get a pdf.
9 - doi-utils-add-bibtex-entry-from-doi to add an entry to your default bibliography (cleaned with pdf if possible).
10 - doi-utils-add-bibtex-entry-from-region to add an entry from a highlighed doi to your default bibliography.
11 - doi-utils-update-bibtex-entry-from-doi with cursor in an entry to update its fields.
12
13 * Header
14 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
15 ;;; doi-utils.el --- get bibtex entries and pdfs from a DOI
16
17 ;; Copyright(C) 2014 John Kitchin
18
19 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
20 ;; This file is not currently part of GNU Emacs.
21
22 ;; This program is free software; you can redistribute it and/or
23 ;; modify it under the terms of the GNU General Public License as
24 ;; published by the Free Software Foundation; either version 2, or (at
25 ;; your option) any later version.
26
27 ;; This program is distributed in the hope that it will be useful, but
28 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
29 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
30 ;; General Public License for more details.
31
32 ;; You should have received a copy of the GNU General Public License
33 ;; along with this program ; see the file COPYING.  If not, write to
34 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
35 ;; Boston, MA 02111-1307, USA.
36
37 ;;; Commentary:
38 ;;
39 ;; Lisp code to generate and update bibtex entries from a DOI, and to
40 ;; download pdfs from publisher websites from a DOI.
41 ;;
42 ;; Package-Requires: ((org-ref))
43
44 (require 'json)
45 #+END_SRC
46
47 * Getting pdf files from a DOI
48 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. 
49
50 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. 
51
52 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
53 (defvar *doi-utils-waiting* t
54   "stores waiting state for url retrieval.")
55
56 (defvar *doi-utils-redirect* nil
57   "stores redirect url from a callback function")
58
59 (defun doi-utils-redirect-callback (&optional status)
60   "callback for url-retrieve to set the redirect"
61   (when (plist-get status :error)
62     (signal (car (plist-get status :error)) (cdr(plist-get status :error))))
63   (when (plist-get status :redirect) ;  is nil if there none
64     (message "redirects = %s" (plist-get status :redirect))
65     (message "*doi-utils-redirect* set to %s"
66              (setq *doi-utils-redirect* (plist-get status :redirect))))
67   ;; we have done our job, so we are not waiting any more.
68   (setq *doi-utils-waiting* nil))
69 #+END_SRC
70
71 To actually get the redirect we use url-retrieve like this.
72
73 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
74 (defun doi-utils-get-redirect (doi)
75   "get redirect url from dx.doi.org/doi"
76   ;; we are going to wait until the url-retrieve is done
77   (setq *doi-utils-waiting* t)
78   ;; start with no redirect. it will be set in the callback.
79   (setq *doi-utils-redirect* nil) 
80   (url-retrieve 
81    (format "http://dx.doi.org/%s" doi)
82    'doi-utils-redirect-callback)
83   ; I suspect we need to wait here for the asynchronous process to
84   ; finish. we loop and sleep until the callback says it is done via
85   ; `*doi-utils-waiting*'. this works as far as i can tell. Before I
86   ; had to run this a few times to get it to work, which i suspect
87   ; just gave the first one enough time to finish.
88   (while *doi-utils-waiting* (sleep-for 0.1)))
89 #+END_SRC
90
91 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:
92
93 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
94 (defvar doi-utils-pdf-url-functions nil
95   "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.")
96 #+END_SRC
97
98 ** APS journals
99 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
100 (defun aps-pdf-url (*doi-utils-redirect*)
101   (when (string-match "^http://journals.aps.org" *doi-utils-redirect*)
102     (replace-regexp-in-string "/abstract/" "/pdf/" *doi-utils-redirect*)))
103 #+END_SRC
104
105 ** Science
106 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
107 (defun science-pdf-url (*doi-utils-redirect*)
108   (when (string-match "^http://www.sciencemag.org" *doi-utils-redirect*)
109     (concat *doi-utils-redirect* ".full.pdf")))
110 #+END_SRC
111
112 ** Nature
113 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
114 (defun nature-pdf-url (*doi-utils-redirect*)
115   (when (string-match "^http://www.nature.com" *doi-utils-redirect*)
116     (let ((result *doi-utils-redirect*))
117       (setq result (replace-regexp-in-string "/full/" "/pdf/" result))
118       (replace-regexp-in-string "\.html$" "\.pdf" result))))
119 #+END_SRC
120
121 ** Wiley
122 http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/abstract
123 http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/pdf
124
125 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.
126
127 This is where the link is hidden:
128
129 <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>
130
131
132
133 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
134 (defun doi-utils-get-wiley-pdf-url (redirect-url)
135   "wileyscience direct hides the pdf url in html. we get it out here"
136   (setq *doi-utils-waiting* t)
137   (url-retrieve redirect-url
138                 (lambda (status)
139                   (beginning-of-buffer)
140                   (re-search-forward "<iframe id=\"pdfDocument\" src=\"\\([^\"]*\\)\"" nil)
141                   (setq *doi-utils-pdf-url* (match-string 1)
142                         ,*doi-utils-waiting* nil)))
143   (while *doi-utils-waiting* (sleep-for 0.1))
144   ,*doi-utils-pdf-url*)
145
146 (defun wiley-pdf-url (*doi-utils-redirect*)
147   (when (string-match "^http://onlinelibrary.wiley.com" *doi-utils-redirect*)
148    (doi-utils-get-wiley-pdf-url (replace-regexp-in-string "/abstract" "/pdf" *doi-utils-redirect*))
149    ,*doi-utils-pdf-url*))
150 #+END_SRC
151
152 ** Springer
153 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
154 (defun springer-pdf-url (*doi-utils-redirect*)
155   (when (string-match "^http://link.springer.com" *doi-utils-redirect*)
156     (replace-regexp-in-string "/article/" "/content/pdf/" (concat *doi-utils-redirect* ".pdf"))))
157 #+END_SRC
158
159 ** ACS
160 here is a typical url http://pubs.acs.org/doi/abs/10.1021/nl500037x
161 the pdf is found at http://pubs.acs.org/doi/pdf/10.1021/nl500037x
162
163 we just change /abs/ to /pdf/.
164
165 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
166 (defun acs-pdf-url (*doi-utils-redirect*)
167   (when (string-match "^http://pubs.acs.org" *doi-utils-redirect*)
168     (replace-regexp-in-string "/abs/" "/pdf/" *doi-utils-redirect*)))
169 #+END_SRC
170
171 #+BEGIN_SRC emacs-lisp
172 (acs-pdf-url  "http://pubs.acs.org/doi/abs/10.1021/nl500037x")
173 #+END_SRC
174
175 #+RESULTS:
176 : http://pubs.acs.org/doi/pdf/10.1021/nl500037x
177
178 ** IOP
179 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
180 (defun iop-pdf-url (*doi-utils-redirect*)
181   (when (string-match "^http://iopscience.iop.org" *doi-utils-redirect*)
182     (let ((tail (replace-regexp-in-string "^http://iopscience.iop.org" "" *doi-utils-redirect*)))
183       (concat "http://iopscience.iop.org" tail "/pdf" (replace-regexp-in-string "/" "_" tail) ".pdf"))))
184 #+END_SRC
185
186 ** JSTOR
187 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
188 (defun jstor-pdf-url (*doi-utils-redirect*)
189   (when (string-match "^http://www.jstor.org" *doi-utils-redirect*)
190     (concat (replace-regexp-in-string "/stable/" "/stable/pdfplus/" *doi-utils-redirect*) ".pdf")))
191 #+END_SRC
192
193 ** AIP 
194 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
195 (defun aip-pdf-url (*doi-utils-redirect*)
196   (when (string-match "^http://scitation.aip.org" *doi-utils-redirect*)
197     ;; get stuff after content
198     (let (p1 p2 s p3)
199       (setq p2 (replace-regexp-in-string "^http://scitation.aip.org/" "" *doi-utils-redirect*))
200       (setq s (split-string p2 "/"))
201       (setq p1 (mapconcat 'identity (-remove-at-indices '(0 6) s) "/"))
202       (setq p3 (concat "/" (nth 0 s) (nth 1 s) "/" (nth 2 s) "/" (nth 3 s)))
203       (format "http://scitation.aip.org/deliver/fulltext/%s.pdf?itemId=/%s&mimeType=pdf&containerItemId=%s"
204               p1 p2 p3))))
205 #+END_SRC
206
207 ** Taylor and Francis
208 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
209 (defun tandfonline-pdf-url (*doi-utils-redirect*)
210   (when (string-match "^http://www.tandfonline.com" *doi-utils-redirect*)
211     (replace-regexp-in-string "/abs/\\|/full/" "/pdf/" *doi-utils-redirect*)))
212 #+END_SRC
213 ** ECS
214 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
215 (defun ecs-pdf-url (*doi-utils-redirect*)
216   (when (string-match "^http://jes.ecsdl.org" *doi-utils-redirect*)
217     (replace-regexp-in-string "\.abstract$" ".full.pdf" *doi-utils-redirect*)))
218 #+END_SRC
219
220 http://ecst.ecsdl.org/content/25/2/2769
221 http://ecst.ecsdl.org/content/25/2/2769.full.pdf
222
223 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
224 (defun ecst-pdf-url (*doi-utils-redirect*)
225   (when (string-match "^http://ecst.ecsdl.org" *doi-utils-redirect*)
226     (concat *doi-utils-redirect* ".full.pdf")))
227 #+END_SRC
228
229
230 ** RSC
231 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
232 (defun rsc-pdf-url (*doi-utils-redirect*)
233   (when (string-match "^http://pubs.rsc.org" *doi-utils-redirect*)
234     (let ((url (downcase *doi-utils-redirect*)))
235       (setq url (replace-regexp-in-string "articlelanding" "articlepdf" url))
236       url)))
237 #+END_SRC
238
239 ** Elsevier/ScienceDirect
240 You cannot compute these pdf links; they are embedded in the redirected pages.
241
242 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
243 (defvar *doi-utils-pdf-url* nil
244   "stores url to pdf download from a callback function")
245
246 (defun doi-utils-get-science-direct-pdf-url (redirect-url)
247   "science direct hides the pdf url in html. we get it out here"
248   (setq *doi-utils-waiting* t)
249   (url-retrieve redirect-url
250                 (lambda (status)
251                   (beginning-of-buffer)
252                   (re-search-forward "pdfurl=\"\\([^\"]*\\)\"" nil t)
253                   (setq *doi-utils-pdf-url* (match-string 1)
254                         ,*doi-utils-waiting* nil)))
255   (while *doi-utils-waiting* (sleep-for 0.1))
256   ,*doi-utils-pdf-url*)
257
258
259 (defun science-direct-pdf-url (*doi-utils-redirect*)
260   (when (string-match "^http://www.sciencedirect.com" *doi-utils-redirect*)
261     (doi-utils-get-science-direct-pdf-url *doi-utils-redirect*)
262     ,*doi-utils-pdf-url*))
263
264 ;; sometimes I get
265 ;; http://linkinghub.elsevier.com/retrieve/pii/S0927025609004558
266 ;; which actually redirect to
267 ;; http://www.sciencedirect.com/science/article/pii/S0927025609004558
268 (defun linkinghub-elsevier-pdf-url (*doi-utils-redirect*)
269   (when (string-match "^http://linkinghub.elsevier.com/retrieve" *doi-utils-redirect*)
270     (let ((second-redirect (replace-regexp-in-string
271                             "http://linkinghub.elsevier.com/retrieve"
272                             "http://www.sciencedirect.com/science/article"
273                             ,*doi-utils-redirect*)))
274       (message "getting pdf url from %s" second-redirect)
275       ;(doi-utils-get-science-direct-pdf-url second-redirect)
276       ,*doi-utils-pdf-url*)))
277 #+END_SRC
278
279 ** PNAS
280 http://www.pnas.org/content/early/2014/05/08/1319030111
281 http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf
282
283 with supporting info
284 http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf+html?with-ds=yes
285 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
286 (defun pnas-pdf-url (*doi-utils-redirect*)
287   (when (string-match "^http://www.pnas.org" *doi-utils-redirect*)
288     (concat *doi-utils-redirect* ".full.pdf?with-ds=yes")))
289 #+END_SRC
290
291 ** Add all functions
292 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
293 (setq doi-utils-pdf-url-functions
294       (list
295        'aps-pdf-url
296        'science-pdf-url
297        'nature-pdf-url
298        'wiley-pdf-url        
299        'springer-pdf-url
300        'acs-pdf-url
301        'iop-pdf-url
302        'jstor-pdf-url
303        'aip-pdf-url
304        'science-direct-pdf-url
305        'linkinghub-elsevier-pdf-url
306        'tandfonline-pdf-url
307        'ecs-pdf-url
308        'ecst-pdf-url
309        'rsc-pdf-url
310        'pnas-pdf-url))
311 #+END_SRC
312
313 ** Get the pdf url for a doi
314 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
315 (defun doi-utils-get-pdf-url (doi)
316   "returns a url to a pdf for the doi if one can be
317 calculated. Loops through the functions in `doi-utils-pdf-url-functions'
318 until one is found"
319   (doi-utils-get-redirect doi)
320   
321   (unless *doi-utils-redirect*
322     (error "No redirect found for %s" doi))
323   (message "applying functions")
324   (catch 'pdf-url
325     (dolist (func doi-utils-pdf-url-functions)
326      (message "calling %s" func)
327       (let ((this-pdf-url (funcall func *doi-utils-redirect*)))
328 (message "t: %s" this-pdf-url)
329         (when this-pdf-url
330           (message "found pdf url: %s" this-pdf-url)
331           (throw 'pdf-url this-pdf-url))))))
332 #+END_SRC
333
334 #+RESULTS:
335 : doi-utils-get-pdf-url
336
337
338 #+BEGIN_SRC emacs-lisp :tangle no
339 (doi-utils-get-pdf-url "10.1126/science.1158722")
340 #+END_SRC
341
342 #+RESULTS:
343 : http://www.sciencemag.org/content/321/5890/792.full.pdf
344
345 #+BEGIN_SRC emacs-lisp :tangle no
346 (doi-utils-get-pdf-url  "10.1021/nl500037x")
347 #+END_SRC
348
349 #+RESULTS:
350 : http://pubs.acs.org/doi/pdf/10.1021/nl500037x
351
352
353 #+BEGIN_SRC emacs-lisp :tangle no
354 (doi-utils-get-pdf-url  "10.1002/anie.201402680")
355 #+END_SRC
356
357 #+RESULTS:
358 : http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/pdf
359
360 ** Finally, download the pdf
361 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
362 (defun doi-utils-get-bibtex-entry-pdf ()
363   "download pdf for entry at point if the pdf does not already
364 exist locally. The entry must have a doi. The pdf will be saved
365 to `org-ref-pdf-directory', by the name %s.pdf where %s is the
366 bibtex label. Files will not be overwritten. The pdf will be
367 checked to make sure it is a pdf, and not some html failure
368 page. you must have permission to access the pdf. We open the pdf
369 at the end."
370   (interactive)
371   (save-excursion
372     (bibtex-beginning-of-entry) 
373     (let (;; get doi, removing http://dx.doi.org/ if it is there.
374           (doi (replace-regexp-in-string
375                 "http://dx.doi.org/" ""
376                 (bibtex-autokey-get-field "doi")))             
377           (key)
378           (pdf-url)
379           (pdf-file)
380           (content))
381       ;; get the key and build pdf filename.
382       (re-search-forward bibtex-entry-maybe-empty-head)
383       (setq key (match-string bibtex-key-in-head))
384       (setq pdf-file (concat org-ref-pdf-directory key ".pdf"))
385
386       ;; now get file if needed.
387       (when (and doi (not (file-exists-p pdf-file)))
388         (setq pdf-url (doi-utils-get-pdf-url doi))
389         (if pdf-url
390             (progn
391               (url-copy-file pdf-url pdf-file)
392               ;; now check if we got a pdf
393               (with-temp-buffer
394                 (insert-file-contents pdf-file)
395                 ;; PDFS start with %PDF-1.x as the first few characters.
396                 (if (not (string= (buffer-substring 1 6) "%PDF-"))
397                     (progn
398                       (message "%s" (buffer-string))
399                       (delete-file pdf-file))
400                   (message "%s saved" pdf-file)))
401         
402               (when (file-exists-p pdf-file)
403                 (org-open-file pdf-file)))
404           (message "No pdf-url found for %s at %s" doi *doi-utils-redirect* ))
405           pdf-file))))
406 #+END_SRC
407
408 * Getting bibtex entries from a DOI
409
410 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.
411
412 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
413 (defun doi-utils-get-json-metadata (doi)
414   (let ((url-request-method "GET") 
415        (url-mime-accept-string "application/citeproc+json")
416        (json-object-type 'plist))
417     (with-current-buffer
418         (url-retrieve-synchronously
419          (concat "http://dx.doi.org/" doi))
420       (json-read-from-string (buffer-substring url-http-end-of-headers (point-max))))))       
421 #+END_SRC
422
423 #+RESULTS:
424 : doi-utils-get-json-metadata
425
426 For example:
427 #+BEGIN_SRC emacs-lisp :tangle no
428 (doi-utils-get-json-metadata "10.1103/PhysRevLett.99.016105")
429 #+END_SRC
430
431 #+RESULTS:
432 | :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 | [] |
433
434 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.
435
436 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
437 (defun doi-utils-expand-template (s)
438   "expand a template containing %{} with the eval of its contents"
439   (replace-regexp-in-string "%{\\([^}]+\\)}"
440                             (lambda (arg)
441                               (let ((sexp (substring arg 2 -1)))
442                                 (format "%s" (eval (read sexp))))) s))
443 #+END_SRC
444
445 Now we define a function that fills in that template from the metadata.
446
447 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
448 (defun doi-utils-doi-to-bibtex-string (doi)
449   "return a bibtex entry as a string for the doi. Only articles are currently supported"
450   (let (type
451         results
452         author
453         title
454         booktitle
455         journal
456         year
457         volume
458         number
459         pages
460         month
461         url
462         json-data)
463     (setq results (doi-utils-get-json-metadata doi)
464           json-data (format "%s" results)
465           type (plist-get results :type)
466           author (mapconcat (lambda (x) (concat (plist-get x :given) " " (plist-get x :family)))
467                             (plist-get results :author) " and ")
468           title (plist-get results :title)
469           journal (plist-get results :container-title)
470           volume (plist-get results :volume)
471           issue (plist-get results :issue)
472           year (elt (elt (plist-get (plist-get results :issued) :date-parts) 0) 0)
473           pages (plist-get results :page)
474           doi (plist-get results :DOI)
475           url (plist-get results :URL))
476     (cond
477      ((or (string= type "journal-article") (string= type "article-journal"))
478       (doi-utils-expand-template "@article{,
479   author =       {%{author}},
480   title =        {%{title}},
481   journal =      {%{journal}},
482   year =         {%{year}},
483   volume =       {%{volume}},
484   number =       {%{issue}},
485   pages =        {%{pages}},
486   doi =          {%{doi}},
487   url =          {%{url}},
488 }"))
489      
490      ((string= type "proceedings-article")
491       (setq booktitle (plist-get results :container-title))
492       (doi-utils-expand-template "@inproceedings{,
493   author =       {%{author}},
494   title =        {%{title}},
495   booktitle =    {%{booktitle}},
496   year =         {%{year}},
497   month =        {%{month}},
498   pages =        {%{pages}},
499   doi =          {%{doi}},
500   url =          {%{url}},
501 }"))
502      
503     (t (message-box "%s not supported yet." type)))))
504 #+END_SRC
505
506 #+RESULTS:
507 : doi-utils-doi-to-bibtex-string
508
509 To see that in action:
510 #+BEGIN_SRC emacs-lisp :tangle no
511 (doi-utils-doi-to-bibtex-string "10.1103/PhysRevLett.99.016105")
512 #+END_SRC
513
514 #+RESULTS:
515 #+begin_example
516 @article{,
517   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},
518   title =        {Scaling Properties of Adsorption Energies for Hydrogen-Containing Molecules on Transition-Metal Surfaces},
519   journal =      {Phys. Rev. Lett.},
520   year =         {2007},
521   volume =       {99},
522   number =       {1},
523   pages =        {nil},
524   doi =          {10.1103/physrevlett.99.016105},
525   url =          {http://dx.doi.org/10.1103/PhysRevLett.99.016105},
526 }
527 #+end_example
528
529 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.
530
531 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
532 (defun doi-utils-insert-bibtex-entry-from-doi (doi)
533   "insert bibtex entry from a doi. Also cleans entry using
534 org-ref, and tries to download the corresponding pdf."
535   (interactive "sDOI: ")
536   (insert (doi-utils-doi-to-bibtex-string doi))
537   (backward-char)
538   (if (bibtex-key-in-head nil)
539        (org-ref-clean-bibtex-entry t)
540      (org-ref-clean-bibtex-entry))
541    ;; try to get pdf
542    (doi-utils-get-bibtex-entry-pdf)
543    (save-selected-window
544      (org-ref-open-bibtex-notes)))
545 #+END_SRC
546
547 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.
548
549 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
550 (defun doi-utils-add-bibtex-entry-from-doi (doi)
551   "add entry to end of first entry in `org-ref-default-bibliography'."
552   (interactive "sDOI: ")
553   (find-file (car org-ref-default-bibliography))
554   (end-of-buffer)
555   (insert "\n\n")
556   (doi-utils-insert-bibtex-entry-from-doi doi))
557 #+END_SRC
558
559 It may be you want to just highlight a doi, and then add it. Here is that function.
560
561 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
562 (defun doi-utils-add-bibtex-entry-from-region (start end)
563   "add entry assuming region is a doi to end of first entry in `org-ref-default-bibliography'."
564   (interactive "r")
565   (let ((doi (buffer-substring start end)))
566     (find-file (car org-ref-default-bibliography))
567     (end-of-buffer)
568     (insert "\n")
569     (doi-utils-insert-bibtex-entry-from-doi doi)))
570 #+END_SRC
571
572 #+RESULTS:
573 : doi-utils-add-bibtex-entry-from-region
574
575 * Updating bibtex entries
576 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.
577
578 There is not bibtex set field function, so I wrote this one.
579
580 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
581 (defun bibtex-set-field (field value)
582   "set field to value in bibtex file. create field if it does not exist"
583   (interactive "sfield: \nsvalue: ")
584   (bibtex-beginning-of-entry)
585   (let ((found))
586     (if (setq found (bibtex-search-forward-field field t))
587         ;; we found a field
588         (progn
589           (goto-char (car (cdr found)))
590           (when value
591             (bibtex-kill-field)
592             (bibtex-make-field field)
593             (backward-char)
594             (insert value)))
595       ;; make a new field
596       (message "new field being made")
597       (bibtex-beginning-of-entry)
598       (forward-line) (beginning-of-line)
599       (bibtex-next-field nil)
600       (forward-char)
601       (bibtex-make-field field)
602       (backward-char)
603       (insert value))))
604 #+END_SRC
605
606 The updating function looks like this. We get all the keys from the json plist metadata, and update the fields if they exist.
607
608 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
609 (defun plist-get-keys (plist)
610    "return keys in a plist"
611   (loop
612    for key in results by #'cddr collect key))
613
614 (defun doi-utils-update-bibtex-entry-from-doi (doi)
615   "update fields in a bibtex entry from the doi. Every field will be updated, so previous changes will be lost."
616   (interactive (list
617                 (or (replace-regexp-in-string "http://dx.doi.org/" "" (bibtex-autokey-get-field "doi"))
618                     (read-string "DOI: "))))
619   (let* ((results (doi-utils-get-json-metadata doi))
620          (type (plist-get results :type))
621          (author (mapconcat
622                   (lambda (x) (concat (plist-get x :given)
623                                     " " (plist-get x :family)))
624                   (plist-get results :author) " and "))
625          (title (plist-get results :title))
626          (journal (plist-get results :container-title))
627          (year (format "%s"
628                        (elt
629                         (elt
630                          (plist-get
631                           (plist-get results :issued) :date-parts) 0) 0)))      
632         (volume (plist-get results :volume))
633         (number (or (plist-get results :issue) ""))
634         (pages (or (plist-get results :page) ""))
635         (url (or (plist-get results :URL) ""))
636         (doi (plist-get results :DOI)))
637     
638     ;; map the json fields to bibtex fields. The code each field is mapped to is evaluated.
639     (setq mapping '((:author . (bibtex-set-field "author" author))
640                     (:title . (bibtex-set-field "title" title))
641                     (:container-title . (bibtex-set-field "journal" journal))
642                     (:issued . (bibtex-set-field "year" year))
643                     (:volume . (bibtex-set-field "volume" volume))
644                     (:issue . (bibtex-set-field "number" number))
645                     (:page . (bibtex-set-field "pages" pages))
646                     (:DOI . (bibtex-set-field "doi" doi))
647                     (:URL . (bibtex-set-field "url" url))))
648
649     ;; now we have code to run for each entry. we map over them and evaluate the code
650     (mapcar
651      (lambda (key)
652        (eval (cdr (assoc key mapping))))
653      (plist-get-keys results)))
654   
655   ; reclean entry, but keep key if it exists.
656   (if (bibtex-key-in-head)
657       (org-ref-clean-bibtex-entry t)
658     (org-ref-clean-bibtex-entry)))
659 #+END_SRC
660 * end of file
661 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
662 (provide 'doi-utils)
663 #+END_SRC
664 * load
665 #+BEGIN_SRC emacs-lisp :tangle no
666 (org-babel-load-file "doi-utils.org")
667 #+END_SRC
668
669 #+RESULTS:
670 : Loaded doi-utils.el
671