]> git.donarmstrong.com Git - org-ref.git/blob - doi-utils.org
5e539dbff3147bee8be0b3535df4e62a83255b68
[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
415   (let ((url-request-method "GET") 
416         (url-mime-accept-string "application/citeproc+json")
417         (json-object-type 'plist)
418         (json-data))
419     (with-current-buffer
420         (url-retrieve-synchronously
421          (concat "http://dx.doi.org/" doi))
422       (setq json-data (buffer-substring url-http-end-of-headers (point-max)))
423       (message "%s" json-data)
424       (json-read-from-string json-data))))
425 #+END_SRC
426
427 #+RESULTS:
428 : doi-utils-get-json-metadata
429
430 For example:
431 #+BEGIN_SRC emacs-lisp :tangle no
432 (doi-utils-get-json-metadata "10.1103/PhysRevLett.99.016105")
433 #+END_SRC
434
435 #+RESULTS:
436 | :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 | [] |
437
438 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.
439
440 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
441 (defun doi-utils-expand-template (s)
442   "expand a template containing %{} with the eval of its contents"
443   (replace-regexp-in-string "%{\\([^}]+\\)}"
444                             (lambda (arg)
445                               (let ((sexp (substring arg 2 -1)))
446                                 (format "%s" (eval (read sexp))))) s))
447 #+END_SRC
448
449 Now we define a function that fills in that template from the metadata.
450
451 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
452 (defun doi-utils-doi-to-bibtex-string (doi)
453   "return a bibtex entry as a string for the doi. Only articles are currently supported"
454   (let (type
455         results
456         author
457         title
458         booktitle
459         journal
460         year
461         volume
462         number
463         pages
464         month
465         url
466         json-data)
467     (setq results (doi-utils-get-json-metadata doi)
468           json-data (format "%s" results)
469           type (plist-get results :type)
470           author (mapconcat (lambda (x) (concat (plist-get x :given) " " (plist-get x :family)))
471                             (plist-get results :author) " and ")
472           title (plist-get results :title)
473           journal (plist-get results :container-title)
474           volume (plist-get results :volume)
475           issue (plist-get results :issue)
476           year (elt (elt (plist-get (plist-get results :issued) :date-parts) 0) 0)
477           pages (plist-get results :page)
478           doi (plist-get results :DOI)
479           url (plist-get results :URL))
480     (cond
481      ((or (string= type "journal-article") (string= type "article-journal"))
482       (doi-utils-expand-template "@article{,
483   author =       {%{author}},
484   title =        {%{title}},
485   journal =      {%{journal}},
486   year =         {%{year}},
487   volume =       {%{volume}},
488   number =       {%{issue}},
489   pages =        {%{pages}},
490   doi =          {%{doi}},
491   url =          {%{url}},
492 }"))
493      
494      ((string= type "proceedings-article")
495       (setq booktitle (plist-get results :container-title))
496       (doi-utils-expand-template "@inproceedings{,
497   author =       {%{author}},
498   title =        {%{title}},
499   booktitle =    {%{booktitle}},
500   year =         {%{year}},
501   month =        {%{month}},
502   pages =        {%{pages}},
503   doi =          {%{doi}},
504   url =          {%{url}},
505 }"))
506      
507     (t (message-box "%s not supported yet." type)))))
508 #+END_SRC
509
510 #+RESULTS:
511 : doi-utils-doi-to-bibtex-string
512
513 To see that in action:
514 #+BEGIN_SRC emacs-lisp :tangle no
515 (doi-utils-doi-to-bibtex-string "10.1103/PhysRevLett.99.016105")
516 #+END_SRC
517
518 #+RESULTS:
519 #+begin_example
520 @article{,
521   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},
522   title =        {Scaling Properties of Adsorption Energies for Hydrogen-Containing Molecules on Transition-Metal Surfaces},
523   journal =      {Phys. Rev. Lett.},
524   year =         {2007},
525   volume =       {99},
526   number =       {1},
527   pages =        {nil},
528   doi =          {10.1103/physrevlett.99.016105},
529   url =          {http://dx.doi.org/10.1103/PhysRevLett.99.016105},
530 }
531 #+end_example
532
533 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.
534
535 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
536 (defun doi-utils-insert-bibtex-entry-from-doi (doi)
537   "insert bibtex entry from a doi. Also cleans entry using
538 org-ref, and tries to download the corresponding pdf."
539   (interactive "sDOI: ")
540   (insert (doi-utils-doi-to-bibtex-string doi))
541   (backward-char)
542   (if (bibtex-key-in-head nil)
543        (org-ref-clean-bibtex-entry t)
544      (org-ref-clean-bibtex-entry))
545    ;; try to get pdf
546    (doi-utils-get-bibtex-entry-pdf)
547    (save-selected-window
548      (org-ref-open-bibtex-notes)))
549 #+END_SRC
550
551 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.
552
553 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
554 (defun doi-utils-add-bibtex-entry-from-doi (doi bibfile)
555   "add entry to end of a file in `org-ref-default-bibliography' or in the current directory ending with .bib."
556   (interactive
557    (list
558     (read-string "DOI: ")
559     (ido-completing-read
560      "Bibfile: "
561      (append org-ref-default-bibliography
562              (f-entries "." (lambda (f) (f-ext? f "bib")))))))
563   (find-file bibfile)
564   (goto-char (point-min))
565   (if (search-forward doi nil t)
566       (message "%s is already in this file" doi)
567     (end-of-buffer)
568     (insert "\n\n")
569     (doi-utils-insert-bibtex-entry-from-doi doi)
570     (save-buffer)))
571 #+END_SRC
572
573 It may be you want to just highlight a doi, and then add it. Here is that function.
574
575 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
576 (defun doi-utils-add-bibtex-entry-from-region (start end)
577   "add entry assuming region is a doi to end of first entry in `org-ref-default-bibliography'."
578   (interactive "r")
579   (let ((doi (buffer-substring start end)))
580     (find-file (car org-ref-default-bibliography))
581     (end-of-buffer)
582     (insert "\n")
583     (doi-utils-insert-bibtex-entry-from-doi doi)))
584 #+END_SRC
585
586 #+RESULTS:
587 : doi-utils-add-bibtex-entry-from-region
588
589 * Updating bibtex entries
590 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.
591
592 There is not bibtex set field function, so I wrote this one.
593
594 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
595 (defun bibtex-set-field (field value &optional nodelim)
596   "set field to value in bibtex file. create field if it does not exist"
597   (interactive "sfield: \nsvalue: ")
598   (bibtex-beginning-of-entry)
599   (let ((found))
600     (if (setq found (bibtex-search-forward-field field t))
601         ;; we found a field
602         (progn
603           (goto-char (car (cdr found)))
604           (when value
605             (bibtex-kill-field)
606             (bibtex-make-field field nil nil nodelim)
607             (backward-char)
608             (insert value)))
609       ;; make a new field
610       (message "new field being made")
611       (bibtex-beginning-of-entry)
612       (forward-line) (beginning-of-line)
613       (bibtex-next-field nil)
614       (forward-char)
615       (bibtex-make-field field nil nil nodelim)
616       (backward-char)
617       (insert value))))
618 #+END_SRC
619
620 The updating function looks like this. We get all the keys from the json plist metadata, and update the fields if they exist.
621
622 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
623 (defun plist-get-keys (plist)
624    "return keys in a plist"
625   (loop
626    for key in results by #'cddr collect key))
627
628 (defun doi-utils-update-bibtex-entry-from-doi (doi)
629   "update fields in a bibtex entry from the doi. Every field will be updated, so previous changes will be lost."
630   (interactive (list
631                 (or (replace-regexp-in-string "http://dx.doi.org/" "" (bibtex-autokey-get-field "doi"))
632                     (read-string "DOI: "))))
633   (let* ((results (doi-utils-get-json-metadata doi))
634          (type (plist-get results :type))
635          (author (mapconcat
636                   (lambda (x) (concat (plist-get x :given)
637                                     " " (plist-get x :family)))
638                   (plist-get results :author) " and "))
639          (title (plist-get results :title))
640          (journal (plist-get results :container-title))
641          (year (format "%s"
642                        (elt
643                         (elt
644                          (plist-get
645                           (plist-get results :issued) :date-parts) 0) 0)))      
646         (volume (plist-get results :volume))
647         (number (or (plist-get results :issue) ""))
648         (pages (or (plist-get results :page) ""))
649         (url (or (plist-get results :URL) ""))
650         (doi (plist-get results :DOI)))
651     
652     ;; map the json fields to bibtex fields. The code each field is mapped to is evaluated.
653     (setq mapping '((:author . (bibtex-set-field "author" author))
654                     (:title . (bibtex-set-field "title" title))
655                     (:container-title . (bibtex-set-field "journal" journal))
656                     (:issued . (bibtex-set-field "year" year))
657                     (:volume . (bibtex-set-field "volume" volume))
658                     (:issue . (bibtex-set-field "number" number))
659                     (:page . (bibtex-set-field "pages" pages))
660                     (:DOI . (bibtex-set-field "doi" doi))
661                     (:URL . (bibtex-set-field "url" url))))
662
663     ;; now we have code to run for each entry. we map over them and evaluate the code
664     (mapcar
665      (lambda (key)
666        (eval (cdr (assoc key mapping))))
667      (plist-get-keys results)))
668   
669   ; reclean entry, but keep key if it exists.
670   (if (bibtex-key-in-head)
671       (org-ref-clean-bibtex-entry t)
672     (org-ref-clean-bibtex-entry)))
673 #+END_SRC
674 * DOI functions for WOS
675 I came across this API http://wokinfo.com/media/pdf/OpenURL-guide.pdf to make links to the things I am interested in here. Based on that document, here are three links based on a doi:10.1021/jp047349j that take you to different Web Of Science (WOS) pages.
676
677
678 1. go to article in WOS: http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info:doi/10.1021/jp047349j
679 2. citing articles: http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F10.1021/jp047349j&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.citing=yes
680 3. related articles: http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F10.1021/jp047349j&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.related=yes
681
682 These are pretty easy to construct, so we can write functions that will create them and open the url in our browser. There are some other options that could be considered, but since we usually have a doi, it seems like the best way to go for creating the links. Here are the functions.
683
684 #+BEGIN_SRC emacs-lisp  :tangle doi-utils.el
685 (defun doi-utils-wos (doi)
686   "Open Web of Science entry for DOI"
687   (interactive "sDOI: ")
688   (browse-url
689    (format
690     "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info:doi/%s" doi)))
691
692 (defun doi-utils-wos-citing (doi)
693   "Open Web of Science citing articles entry. May be empty if none are found"
694   (interactive "sDOI: ")
695   (browse-url
696    (concat
697     "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
698     doi
699     "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.citing=yes")))
700
701 (defun doi-utils-wos-related (doi)
702   "Open Web of Science related articles page."
703   (interactive "sDOI: ")
704   (browse-url
705    (concat "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
706            doi
707            "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.related=yes")))
708
709 #+END_SRC
710
711 * A new doi link for org-mode
712 The idea is to add a menu to the doi link, so rather than just clicking to open the article, you can do other things.
713 1. open doi
714 2. open in wos
715 3. open citing articles
716 4. open related articles
717 5. open bibtex entry
718 6. get bibtex entry
719
720 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el :results silent
721 (defun doi-utils-open (doi)
722  (interactive "sDOI: ")
723  (browse-url (concat "http://dx.doi.org/" doi)))
724
725
726 (defun doi-utils-open-bibtex (doi)
727   "Search through `reftex-default-bibliography' for DOI."
728   (interactive "sDOI: ")
729   (catch 'file
730     (dolist (f reftex-default-bibliography)
731       (find-file f)
732       (when (search-forward doi (point-max) t)
733         (bibtex-beginning-of-entry)
734         (throw 'file t)))))
735
736
737 (defun doi-utils-crossref (doi)
738   "Search DOI in CrossRef."
739   (interactive "sDOI: ")
740   (browse-url
741    (format
742     "http://search.crossref.org/?q=%s" doi)))
743
744
745 (defun doi-utils-google-scholar (doi)
746   "Google scholar the word at point or selection."
747   (interactive "sDOI: ")
748   (browse-url
749    (format
750     "http://scholar.google.com/scholar?q=%s" doi)))
751
752
753 (defun doi-utils-pubmed (doi)
754   "Pubmed the word at point or selection."
755   (interactive "sDOI: ")
756   (browse-url
757    (format
758     "http://www.ncbi.nlm.nih.gov/pubmed/?term=%s"
759     (url-hexify-string doi))))
760
761
762 (defvar doi-link-menu-funcs '()
763  "Functions to run in doi menu. Each entry is a list of (key menu-name function). 
764 The function must take one argument, the doi.")
765
766 (setq doi-link-menu-funcs
767       '(("o" "pen" doi-utils-open)
768         ("w" "os" doi-utils-wos)
769         ("c" "iting articles" doi-utils-wos-citing)
770         ("r" "elated articles" doi-utils-wos-related)
771         ("s" "Google Scholar" doi-utils-google-scholar)
772         ("f" "CrossRef" doi-utils-crossref)
773         ("p" "ubmed" doi-utils-pubmed)
774         ("b" "open in bibtex" doi-utils-open-bibtex)
775         ("g" "et bibtex entry" doi-utils-add-bibtex-entry-from-doi)))
776
777
778 (defun doi-link-menu (link-string)
779    "Generate the link menu message, get choice and execute it. 
780 Options are stored in `doi-link-menu-funcs'."
781    (interactive)
782    (message
783    (concat
784     (mapconcat
785      (lambda (tup)
786        (concat "[" (elt tup 0) "]"
787                (elt tup 1) " "))
788      doi-link-menu-funcs "") ": "))
789    (let* ((input (read-char-exclusive))
790           (choice (assoc
791                    (char-to-string input) doi-link-menu-funcs)))
792      (when choice
793        (funcall
794         (elt 
795          choice
796          2)
797         link-string))))
798
799 (org-add-link-type
800  "doi"
801  'doi-link-menu)
802 #+END_SRC
803
804 doi:10.1021/jp047349j  
805
806 * end of file
807 #+BEGIN_SRC emacs-lisp :tangle doi-utils.el
808 (provide 'doi-utils)
809 #+END_SRC
810 * load
811 #+BEGIN_SRC emacs-lisp :tangle no
812 (org-babel-load-file "doi-utils.org")
813 #+END_SRC
814
815 #+RESULTS:
816 : Loaded doi-utils.el
817