]> git.donarmstrong.com Git - org-ref.git/blob - doi-utils.el
a round of checkdoc fixing
[org-ref.git] / doi-utils.el
1 ;;; doi-utils.el --- DOI utilities for making bibtex entries
2
3 ;; Copyright (C) 2015  John Kitchin
4
5 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
6 ;; Keywords: convenience
7 ;; Version: 0.1
8 ;; Package-Requires: ((org-ref))
9
10 ;; This program is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; This program is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; 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.
26
27 ;; The principle commands you will use from here are:
28
29 ;; - doi-utils-get-bibtex-entry-pdf with the cursor in a bibtex entry.
30 ;; - doi-utils-insert-bibtex-entry-from-doi to insert a bibtex entry at your cursor, clean it and try to get a pdf.
31 ;; - doi-utils-add-bibtex-entry-from-doi to add an entry to your default bibliography (cleaned with pdf if possible).
32 ;; - doi-utils-add-bibtex-entry-from-region to add an entry from a highlighed doi to your default bibliography.
33 ;; - doi-utils-update-bibtex-entry-from-doi with cursor in an entry to update its fields.
34
35 (require 'json)
36
37 ;;; Code:
38 ;; * Getting pdf files from a DOI
39 ;; 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.
40
41 ;; 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.
42
43 (defvar *doi-utils-waiting* t
44   "Stores waiting state for url retrieval.")
45
46 (defvar *doi-utils-redirect* nil
47   "Stores redirect url from a callback function.")
48
49 (defun doi-utils-redirect-callback (&optional status)
50   "Callback for url-retrieve to set the redirect."
51   (when (plist-get status :error)
52     (signal (car (plist-get status :error)) (cdr(plist-get status :error))))
53   (when (plist-get status :redirect) ;  is nil if there none
54     (message "redirects = %s" (plist-get status :redirect))
55     (message "*doi-utils-redirect* set to %s"
56              (setq *doi-utils-redirect* (plist-get status :redirect))))
57   ;; we have done our job, so we are not waiting any more.
58   (setq *doi-utils-waiting* nil))
59
60 ;; To actually get the redirect we use url-retrieve like this.
61
62 (defun doi-utils-get-redirect (doi)
63   "Get redirect url from dx.DOI.org/doi."
64   ;; we are going to wait until the url-retrieve is done
65   (setq *doi-utils-waiting* t)
66   ;; start with no redirect. it will be set in the callback.
67   (setq *doi-utils-redirect* nil)
68   (url-retrieve
69    (format "http://dx.doi.org/%s" doi)
70    'doi-utils-redirect-callback)
71   ; I suspect we need to wait here for the asynchronous process to
72   ; finish. we loop and sleep until the callback says it is done via
73   ; `*doi-utils-waiting*'. this works as far as i can tell. Before I
74   ; had to run this a few times to get it to work, which i suspect
75   ; just gave the first one enough time to finish.
76   (while *doi-utils-waiting* (sleep-for 0.1)))
77
78 ;; 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:
79
80 (defvar doi-utils-pdf-url-functions nil
81   "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.")
82
83
84 ;; ** APS journals
85
86 (defun aps-pdf-url (*doi-utils-redirect*)
87   (when (string-match "^http://journals.aps.org" *doi-utils-redirect*)
88     (replace-regexp-in-string "/abstract/" "/pdf/" *doi-utils-redirect*)))
89
90
91 ;; ** Science
92
93 (defun science-pdf-url (*doi-utils-redirect*)
94   (when (string-match "^http://www.sciencemag.org" *doi-utils-redirect*)
95     (concat *doi-utils-redirect* ".full.pdf")))
96
97
98 ;; ** Nature
99
100 (defun nature-pdf-url (*doi-utils-redirect*)
101   (when (string-match "^http://www.nature.com" *doi-utils-redirect*)
102     (let ((result *doi-utils-redirect*))
103       (setq result (replace-regexp-in-string "/full/" "/pdf/" result))
104       (replace-regexp-in-string "\.html$" "\.pdf" result))))
105
106
107 ;; ** Wiley
108 ;; http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/abstract
109 ;; http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/pdf
110
111 ;; 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.
112
113 ;; This is where the link is hidden:
114
115 ;; <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>
116
117
118 (defun doi-utils-get-wiley-pdf-url (redirect-url)
119   "Wileyscience direct hides the pdf url in html.
120 We get it out here by parsing the html."
121   (setq *doi-utils-waiting* t)
122   (url-retrieve redirect-url
123                 (lambda (status)
124                   (goto-char (point-min))
125                   (re-search-forward "<iframe id=\"pdfDocument\" src=\"\\([^\"]*\\)\"" nil)
126                   (setq *doi-utils-pdf-url* (match-string 1)
127                         *doi-utils-waiting* nil)))
128   (while *doi-utils-waiting* (sleep-for 0.1))
129   *doi-utils-pdf-url*)
130
131 (defun wiley-pdf-url (*doi-utils-redirect*)
132   (when (string-match "^http://onlinelibrary.wiley.com" *doi-utils-redirect*)
133     (doi-utils-get-wiley-pdf-url
134      (replace-regexp-in-string "/abstract" "/pdf" *doi-utils-redirect*))
135    *doi-utils-pdf-url*))
136
137
138 ;; ** Springer
139
140 (defun springer-pdf-url (*doi-utils-redirect*)
141   (when (string-match "^http://link.springer.com" *doi-utils-redirect*)
142     (replace-regexp-in-string "/article/" "/content/pdf/" (concat *doi-utils-redirect* ".pdf"))))
143
144
145 ;; ** ACS
146 ;; here is a typical url http://pubs.acs.org/doi/abs/10.1021/nl500037x
147 ;; the pdf is found at http://pubs.acs.org/doi/pdf/10.1021/nl500037x
148
149 ;; we just change /abs/ to /pdf/.
150
151 (defun acs-pdf-url (*doi-utils-redirect*)
152   (when (string-match "^http://pubs.acs.org" *doi-utils-redirect*)
153     (replace-regexp-in-string "/abs/" "/pdf/" *doi-utils-redirect*)))
154
155
156 ;; ** IOP
157
158 (defun iop-pdf-url (*doi-utils-redirect*)
159   (when (string-match "^http://iopscience.iop.org" *doi-utils-redirect*)
160     (let ((tail (replace-regexp-in-string
161                  "^http://iopscience.iop.org" "" *doi-utils-redirect*)))
162       (concat "http://iopscience.iop.org" tail
163               "/pdf" (replace-regexp-in-string "/" "_" tail) ".pdf"))))
164
165
166 ;; ** JSTOR
167
168 (defun jstor-pdf-url (*doi-utils-redirect*)
169   (when (string-match "^http://www.jstor.org" *doi-utils-redirect*)
170     (concat (replace-regexp-in-string "/stable/" "/stable/pdfplus/" *doi-utils-redirect*) ".pdf")))
171
172
173 ;; ** AIP
174
175 (defun aip-pdf-url (*doi-utils-redirect*)
176   (when (string-match "^http://scitation.aip.org" *doi-utils-redirect*)
177     ;; get stuff after content
178     (let (p1 p2 s p3)
179       (setq p2 (replace-regexp-in-string "^http://scitation.aip.org/" "" *doi-utils-redirect*))
180       (setq s (split-string p2 "/"))
181       (setq p1 (mapconcat 'identity (-remove-at-indices '(0 6) s) "/"))
182       (setq p3 (concat "/" (nth 0 s) (nth 1 s) "/" (nth 2 s) "/" (nth 3 s)))
183       (format "http://scitation.aip.org/deliver/fulltext/%s.pdf?itemId=/%s&mimeType=pdf&containerItemId=%s"
184               p1 p2 p3))))
185
186 ;; ** Taylor and Francis
187
188 (defun tandfonline-pdf-url (*doi-utils-redirect*)
189   (when (string-match "^http://www.tandfonline.com" *doi-utils-redirect*)
190     (replace-regexp-in-string "/abs/\\|/full/" "/pdf/" *doi-utils-redirect*)))
191
192 ;; ** ECS
193
194 (defun ecs-pdf-url (*doi-utils-redirect*)
195   (when (string-match "^http://jes.ecsdl.org" *doi-utils-redirect*)
196     (replace-regexp-in-string "\.abstract$" ".full.pdf" *doi-utils-redirect*)))
197
198 ;; http://ecst.ecsdl.org/content/25/2/2769
199 ;; http://ecst.ecsdl.org/content/25/2/2769.full.pdf
200
201
202 (defun ecst-pdf-url (*doi-utils-redirect*)
203   (when (string-match "^http://ecst.ecsdl.org" *doi-utils-redirect*)
204     (concat *doi-utils-redirect* ".full.pdf")))
205
206
207
208 ;; ** RSC
209
210 (defun rsc-pdf-url (*doi-utils-redirect*)
211   (when (string-match "^http://pubs.rsc.org" *doi-utils-redirect*)
212     (let ((url (downcase *doi-utils-redirect*)))
213       (setq url (replace-regexp-in-string "articlelanding" "articlepdf" url))
214       url)))
215
216 ;; ** Elsevier/ScienceDirect
217 ;; You cannot compute these pdf links; they are embedded in the redirected pages.
218
219 (defvar *doi-utils-pdf-url* nil
220   "stores url to pdf download from a callback function")
221
222 (defun doi-utils-get-science-direct-pdf-url (redirect-url)
223   "Science direct hides the pdf url in html. we get it out here."
224   (setq *doi-utils-waiting* t)
225   (url-retrieve redirect-url
226                 (lambda (status)
227                   (beginning-of-buffer)
228                   (re-search-forward "pdfurl=\"\\([^\"]*\\)\"" nil t)
229                   (setq *doi-utils-pdf-url* (match-string 1)
230                         *doi-utils-waiting* nil)))
231   (while *doi-utils-waiting* (sleep-for 0.1))
232   *doi-utils-pdf-url*)
233
234
235 (defun science-direct-pdf-url (*doi-utils-redirect*)
236   (when (string-match "^http://www.sciencedirect.com" *doi-utils-redirect*)
237     (doi-utils-get-science-direct-pdf-url *doi-utils-redirect*)
238     *doi-utils-pdf-url*))
239
240 ;; sometimes I get
241 ;; http://linkinghub.elsevier.com/retrieve/pii/S0927025609004558
242 ;; which actually redirect to
243 ;; http://www.sciencedirect.com/science/article/pii/S0927025609004558
244 (defun linkinghub-elsevier-pdf-url (*doi-utils-redirect*)
245   (when (string-match "^http://linkinghub.elsevier.com/retrieve" *doi-utils-redirect*)
246     (let ((second-redirect (replace-regexp-in-string
247                             "http://linkinghub.elsevier.com/retrieve"
248                             "http://www.sciencedirect.com/science/article"
249                             *doi-utils-redirect*)))
250       (message "getting pdf url from %s" second-redirect)
251       *doi-utils-pdf-url*)))
252
253 ;; ** PNAS
254 ;; http://www.pnas.org/content/early/2014/05/08/1319030111
255 ;; http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf
256
257 ;; with supporting info
258 ;; http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf+html?with-ds=yes
259
260 (defun pnas-pdf-url (*doi-utils-redirect*)
261   (when (string-match "^http://www.pnas.org" *doi-utils-redirect*)
262     (concat *doi-utils-redirect* ".full.pdf?with-ds=yes")))
263
264
265 ;; ** Add all functions
266
267 (setq doi-utils-pdf-url-functions
268       (list
269        'aps-pdf-url
270        'science-pdf-url
271        'nature-pdf-url
272        'wiley-pdf-url
273        'springer-pdf-url
274        'acs-pdf-url
275        'iop-pdf-url
276        'jstor-pdf-url
277        'aip-pdf-url
278        'science-direct-pdf-url
279        'linkinghub-elsevier-pdf-url
280        'tandfonline-pdf-url
281        'ecs-pdf-url
282        'ecst-pdf-url
283        'rsc-pdf-url
284        'pnas-pdf-url))
285
286 ;; ** Get the pdf url for a doi
287
288 (defun doi-utils-get-pdf-url (doi)
289   "Return a url to a pdf for the DOI if one can be calculated.
290 Loops through the functions in `doi-utils-pdf-url-functions'
291 until one is found"
292   (doi-utils-get-redirect doi)
293
294   (unless *doi-utils-redirect*
295     (error "No redirect found for %s" doi))
296   (message "applying functions")
297   (catch 'pdf-url
298     (dolist (func doi-utils-pdf-url-functions)
299      (message "calling %s" func)
300       (let ((this-pdf-url (funcall func *doi-utils-redirect*)))
301 (message "t: %s" this-pdf-url)
302         (when this-pdf-url
303           (message "found pdf url: %s" this-pdf-url)
304           (throw 'pdf-url this-pdf-url))))))
305
306 ;; ** Finally, download the pdf
307
308 (defun doi-utils-get-bibtex-entry-pdf ()
309   "Download pdf for entry at point if the pdf does not already exist locally.
310 The entry must have a doi.  The pdf will be saved
311 to `org-ref-pdf-directory', by the name %s.pdf where %s is the
312 bibtex label.  Files will not be overwritten.  The pdf will be
313 checked to make sure it is a pdf, and not some html failure
314 page.  you must have permission to access the pdf.  We open the pdf
315 at the end."
316   (interactive)
317   (save-excursion
318     (bibtex-beginning-of-entry)
319     (let (;; get doi, removing http://dx.doi.org/ if it is there.
320           (doi (replace-regexp-in-string
321                 "http://dx.doi.org/" ""
322                 (bibtex-autokey-get-field "doi")))
323           (key)
324           (pdf-url)
325           (pdf-file)
326           (content))
327       ;; get the key and build pdf filename.
328       (re-search-forward bibtex-entry-maybe-empty-head)
329       (setq key (match-string bibtex-key-in-head))
330       (setq pdf-file (concat org-ref-pdf-directory key ".pdf"))
331
332       ;; now get file if needed.
333       (when (and doi (not (file-exists-p pdf-file)))
334         (setq pdf-url (doi-utils-get-pdf-url doi))
335         (if pdf-url
336             (progn
337               (url-copy-file pdf-url pdf-file)
338               ;; now check if we got a pdf
339               (with-temp-buffer
340                 (insert-file-contents pdf-file)
341                 ;; PDFS start with %PDF-1.x as the first few characters.
342                 (if (not (string= (buffer-substring 1 6) "%PDF-"))
343                     (progn
344                       (message "%s" (buffer-string))
345                       (delete-file pdf-file))
346                   (message "%s saved" pdf-file)))
347
348               (when (file-exists-p pdf-file)
349                 (org-open-file pdf-file)))
350           (message "No pdf-url found for %s at %s" doi *doi-utils-redirect* ))
351           pdf-file))))
352
353 ;; * Getting bibtex entries from a DOI
354
355 ;; 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.
356
357 (defun doi-utils-get-json-metadata (doi)
358   "Try to get json metadata for DOI.  Open the DOI in a browser if we do not get it."
359   (let ((url-request-method "GET")
360         (url-mime-accept-string "application/citeproc+json")
361         (json-object-type 'plist)
362         (json-data))
363     (with-current-buffer
364         (url-retrieve-synchronously
365          (concat "http://dx.doi.org/" doi))
366       (setq json-data (buffer-substring url-http-end-of-headers (point-max)))
367       (if (string-match "Resource not found" json-data)
368           (progn
369             (browse-url (concat "http://dx.doi.org/" doi))
370             (error "Resource not found.  Opening website"))
371         (json-read-from-string json-data)))))
372
373 ;; 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.
374
375
376 (defun doi-utils-expand-template (s)
377   "Expand a template containing %{} with the eval of its contents."
378   (replace-regexp-in-string "%{\\([^}]+\\)}"
379                             (lambda (arg)
380                               (let ((sexp (substring arg 2 -1)))
381                                 (format "%s" (eval (read sexp))))) s))
382
383
384 ;; Now we define a function that fills in that template from the metadata.
385
386 ;; As different bibtex types share common keys, it is advantageous to separate data extraction from json, and the formatting of the bibtex entry.
387
388
389 (setq doi-utils-json-metadata-extract
390       '((type       (plist-get results :type))
391         (author     (mapconcat (lambda (x) (concat (plist-get x :given) " " (plist-get x :family)))
392                      (plist-get results :author) " and "))
393         (title      (plist-get results :title))
394         (subtitle   (plist-get results :subtitle))
395         (journal    (plist-get results :container-title))
396         (series     (plist-get results :container-title))
397         (publisher  (plist-get results :publisher))
398         (volume     (plist-get results :volume))
399         (issue      (plist-get results :issue))
400         (number     (plist-get results :issue))
401         (year       (elt (elt (plist-get (plist-get results :issued) :date-parts) 0) 0))
402         (month      (elt (elt (plist-get (plist-get results :issued) :date-parts) 0) 1))
403         (pages      (plist-get results :page))
404         (doi        (plist-get results :DOI))
405         (url        (plist-get results :URL))
406         (booktitle  (plist-get results :container-title))))
407
408 ;; Next, we need to define the different bibtex types. Each type has a bibtex type (for output) and the type as provided in the doi record. Finally, we have to declare the fields we want to output.
409
410 (setq doi-utils-bibtex-type-generators nil)
411
412 (defun doi-utils-concat-prepare (lst &optional acc)
413   "Given a list `lst' of strings and other expressions, which are
414 intented to passed to `concat', concat any subsequent strings,
415 minimising the number of arguments being passed to `concat'
416 without changing the results."
417   (cond ((null lst) (nreverse acc))
418         ((and (stringp (car lst))
419               (stringp (car acc)))
420          (doi-utils-concat-prepare (cdr lst) (cons (concat (car acc) (car lst))
421                                          (cdr acc))))
422         (t (doi-utils-concat-prepare (cdr lst) (cons (car lst) acc)))))
423
424 (defmacro doi-utils-def-bibtex-type (name matching-types &rest fields)
425   "Define a BibTeX type identified by (symbol) `name' with
426 `fields' (given as symbols), matching to retrieval expressions in
427 `doi-utils-json-metadata-extract'. This type will only be used
428 when the `:type' parameter in the JSON metadata is contained in
429 `matching-types' - a list of strings."
430   `(push (lambda (type results)
431            (when (or ,@(mapcar (lambda (match-type) `(string= type ,match-type)) matching-types))
432              (let ,(mapcar (lambda (field)
433                              (let ((field-expr (assoc field doi-utils-json-metadata-extract)))
434                                (if field-expr
435                                    ;; need to convert to string first
436                                    `(,(car field-expr) (format "%s" ,(cadr field-expr)))
437                                    (error "Unknown bibtex field type %s" field))))
438                            fields)
439                (concat
440                 ,@(doi-utils-concat-prepare
441                    (-flatten
442                     (list (concat "@" (symbol-name name) "{,\n")
443                           ;; there seems to be some bug with mapcan,
444                           ;; so we fall back to flatten
445                           (mapcar (lambda (field)
446                                     `("  " ,(symbol-name field) " = {" ,field "},\n"))
447                                   fields)
448                           "}\n")))))))
449          doi-utils-bibtex-type-generators))
450
451 (doi-utils-def-bibtex-type article ("journal-article" "article-journal")
452                            author title journal year volume number pages doi url)
453
454 (doi-utils-def-bibtex-type inproceedings ("proceedings-article")
455                            author title booktitle year month pages doi url)
456
457 (doi-utils-def-bibtex-type book ("book")
458                            author title series publisher year pages doi url)
459
460 (doi-utils-def-bibtex-type inbook ("book-chapter")
461                            author title booktitle series publisher year pages doi url)
462
463
464
465 ;; With the code generating the bibtex entry in place, we can glue it to the json retrieval code.
466
467 (defun doi-utils-doi-to-bibtex-string (doi)
468   "Return a bibtex entry as a string for the DOI.  Not all types are supported yet."
469   (let* ((results (doi-utils-get-json-metadata doi))
470          (type (plist-get results :type)))
471     ;(format "%s" results) ; json-data
472     (or (some (lambda (g) (funcall g type results)) doi-utils-bibtex-type-generators)
473         (message "%s not supported yet\n%S." type results))))
474
475 ;; 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.
476
477
478 (defun doi-utils-insert-bibtex-entry-from-doi (doi)
479   "Insert bibtex entry from a DOI.
480 Also cleans entry using org-ref, and tries to download the corresponding pdf."
481   (interactive "sDOI :")
482   (insert (doi-utils-doi-to-bibtex-string doi))
483   (backward-char)
484   ;; set date added for the record
485   (bibtex-set-field "DATE_ADDED" (current-time-string))
486   (if (bibtex-key-in-head nil)
487        (org-ref-clean-bibtex-entry t)
488      (org-ref-clean-bibtex-entry))
489    ;; try to get pdf
490    (doi-utils-get-bibtex-entry-pdf)
491    (save-selected-window
492      (org-ref-open-bibtex-notes)))
493
494
495 ;; 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.
496
497
498 (defun doi-utils-add-bibtex-entry-from-doi (doi bibfile)
499   "Add entry to end of a file in in the current directory ending
500 with .bib or in `org-ref-default-bibliography'. If you have an
501 active region that starts like a DOI, that will be the initial
502 prompt. If no region is selected and the first entry of the
503 kill-ring starts like a DOI, then that is the intial
504 prompt. Otherwise, you have to type or pste in a DOI."
505   (interactive
506    (list (read-input "DOI: "
507                      ;; now set initial input
508                      (cond
509                       ;; If region is active and it starts like a doi we want it.
510                       ((and  (region-active-p)
511                              (s-match "^10" (buffer-substring
512                                               (region-beginning)
513                                               (region-end))))
514                        (buffer-substring (region-beginning) (region-end)))
515                       ;; if the first entry in the kill-ring looks
516                       ;; like a DOI, let's use it.
517                       ((if (s-match "^10" (car kill-ring))
518                            (car kill-ring)))
519                       ;; otherwise, we have no initial input. You
520                       ;; will have to type it in.
521                       (t
522                        nil)))
523          ;;  now get the bibfile to add it to
524          (ido-completing-read
525           "Bibfile: "
526           (append (f-entries "." (lambda (f) (f-ext? f "bib")))
527                   org-ref-default-bibliography))))
528   ;; Wrap in save-window-excursion to restore your window arrangement after this
529   ;; is done.
530   (save-window-excursion
531     (find-file bibfile)
532     ;; Check if the doi already exists
533     (goto-char (point-min))
534     (if (search-forward doi nil t)
535         (message "%s is already in this file" doi)
536       (end-of-buffer)
537       (insert "\n\n")
538       (doi-utils-insert-bibtex-entry-from-doi doi)
539       (save-buffer))))
540
541
542 ;; * Updating bibtex entries
543 ;; 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.
544
545 ;; There is not bibtex set field function, so I wrote this one.
546
547
548 (defun bibtex-set-field (field value &optional nodelim)
549   "Set FIELD to VALUE in bibtex file. create field if it does not exist."
550   (interactive "sfield: \nsvalue: ")
551   (bibtex-beginning-of-entry)
552   (let ((found))
553     (if (setq found (bibtex-search-forward-field field t))
554         ;; we found a field
555         (progn
556           (goto-char (car (cdr found)))
557           (when value
558             (bibtex-kill-field)
559             (bibtex-make-field field nil nil nodelim)
560             (backward-char)
561             (insert value)))
562       ;; make a new field
563       (message "new field being made")
564       (bibtex-beginning-of-entry)
565       (forward-line) (beginning-of-line)
566       (bibtex-next-field nil)
567       (forward-char)
568       (bibtex-make-field field nil nil nodelim)
569       (backward-char)
570       (insert value))))
571
572
573 ;; The updating function for a whole entry looks like this. We get all the keys from the json plist metadata, and update the fields if they exist.
574
575
576 (defun plist-get-keys (plist)
577    "Return keys in a PLIST."
578   (loop
579    for key in results by #'cddr collect key))
580
581 (defun doi-utils-update-bibtex-entry-from-doi (doi)
582   "Update fields in a bibtex entry from the DOI.  Every field will be updated, so previous change will be lost."
583   (interactive (list
584                 (or (replace-regexp-in-string "http://dx.doi.org/" "" (bibtex-autokey-get-field "doi"))
585                     (read-string "DOI: "))))
586   (let* ((results (doi-utils-get-json-metadata doi))
587          (type (plist-get results :type))
588          (author (mapconcat
589                   (lambda (x) (concat (plist-get x :given)
590                                     " " (plist-get x :family)))
591                   (plist-get results :author) " and "))
592          (title (plist-get results :title))
593          (journal (plist-get results :container-title))
594          (year (format "%s"
595                        (elt
596                         (elt
597                          (plist-get
598                           (plist-get results :issued) :date-parts) 0) 0)))
599         (volume (plist-get results :volume))
600         (number (or (plist-get results :issue) ""))
601         (pages (or (plist-get results :page) ""))
602         (url (or (plist-get results :URL) ""))
603         (doi (plist-get results :DOI)))
604
605     ;; map the json fields to bibtex fields. The code each field is mapped to is evaluated.
606     (setq mapping '((:author . (bibtex-set-field "author" author))
607                     (:title . (bibtex-set-field "title" title))
608                     (:container-title . (bibtex-set-field "journal" journal))
609                     (:issued . (bibtex-set-field "year" year))
610                     (:volume . (bibtex-set-field "volume" volume))
611                     (:issue . (bibtex-set-field "number" number))
612                     (:page . (bibtex-set-field "pages" pages))
613                     (:DOI . (bibtex-set-field "doi" doi))
614                     (:URL . (bibtex-set-field "url" url))))
615
616     ;; now we have code to run for each entry. we map over them and evaluate the code
617     (mapcar
618      (lambda (key)
619        (eval (cdr (assoc key mapping))))
620      (plist-get-keys results)))
621
622   ; reclean entry, but keep key if it exists.
623   (if (bibtex-key-in-head)
624       (org-ref-clean-bibtex-entry t)
625     (org-ref-clean-bibtex-entry)))
626
627
628 ;; A downside to updating an entry is it overwrites what you have already fixed. So, we next develop a function to update the field at point.
629
630
631 (defun doi-utils-update-field ()
632   "Update the field at point in the bibtex entry.
633 Data is retrieved from the doi in the entry."
634   (interactive)
635   (let* ((doi (bibtex-autokey-get-field "doi"))
636          (results (doi-utils-get-json-metadata doi))
637          (field (car (bibtex-find-text-internal nil nil ","))))
638     (cond
639      ((string= field "volume")
640       (bibtex-set-field field (plist-get results :volume)))
641      ((string= field "number")
642       (bibtex-set-field field (plist-get results :issue)))
643      ((string= field "pages")
644       (bibtex-set-field field (plist-get results :page)))
645      ((string= field "year")
646       (bibtex-set-field field (plist-get results :year)))
647      (t
648       (message "%s not supported yet." field)))))
649
650
651
652 ;; * DOI functions for WOS
653 ;; 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.
654
655
656 ;; 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
657 ;; 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
658 ;; 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
659
660 ;; 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.
661
662 (defun doi-utils-wos (doi)
663   "Open Web of Science entry for DOI."
664   (interactive "sDOI: ")
665   (browse-url
666    (format
667     "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info:doi/%s" doi)))
668
669 (defun doi-utils-wos-citing (doi)
670   "Open Web of Science citing articles entry. May be empty if none are found."
671   (interactive "sDOI: ")
672   (browse-url
673    (concat
674     "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
675     doi
676     "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.citing=yes")))
677
678 (defun doi-utils-wos-related (doi)
679   "Open Web of Science related articles page."
680   (interactive "sDOI: ")
681   (browse-url
682    (concat "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
683            doi
684            "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.related=yes")))
685
686
687
688
689 ;; * A new doi link for org-mode
690 ;; 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.
691 ;; 1. open doi
692 ;; 2. open in wos
693 ;; 3. open citing articles
694 ;; 4. open related articles
695 ;; 5. open bibtex entry
696 ;; 6. get bibtex entry
697
698
699 (defun doi-utils-open (doi)
700  (interactive "sDOI: ")
701  (browse-url (concat "http://dx.doi.org/" doi)))
702
703
704 (defun doi-utils-open-bibtex (doi)
705   "Search through variable `reftex-default-bibliography' for DOI."
706   (interactive "sDOI: ")
707   (catch 'file
708     (dolist (f reftex-default-bibliography)
709       (find-file f)
710       (when (search-forward doi (point-max) t)
711         (bibtex-beginning-of-entry)
712         (throw 'file t)))))
713
714
715 (defun doi-utils-crossref (doi)
716   "Search DOI in CrossRef."
717   (interactive "sDOI: ")
718   (browse-url
719    (format
720     "http://search.crossref.org/?q=%s" doi)))
721
722
723 (defun doi-utils-google-scholar (doi)
724   "Google scholar the DOI."
725   (interactive "sDOI: ")
726   (browse-url
727    (format
728     "http://scholar.google.com/scholar?q=%s" doi)))
729
730
731 (defun doi-utils-pubmed (doi)
732   "Search Pubmed for the DOI."
733   (interactive "sDOI: ")
734   (browse-url
735    (format
736     "http://www.ncbi.nlm.nih.gov/pubmed/?term=%s"
737     (url-hexify-string doi))))
738
739
740 (defvar doi-link-menu-funcs '()
741  "Functions to run in doi menu. Each entry is a list of (key menu-name function).
742 The function must take one argument, the doi.")
743
744 (setq doi-link-menu-funcs
745       '(("o" "pen" doi-utils-open)
746         ("w" "os" doi-utils-wos)
747         ("c" "iting articles" doi-utils-wos-citing)
748         ("r" "elated articles" doi-utils-wos-related)
749         ("s" "Google Scholar" doi-utils-google-scholar)
750         ("f" "CrossRef" doi-utils-crossref)
751         ("p" "ubmed" doi-utils-pubmed)
752         ("b" "open in bibtex" doi-utils-open-bibtex)
753         ("g" "et bibtex entry" doi-utils-add-bibtex-entry-from-doi)))
754
755
756 (defun doi-link-menu (link-string)
757    "Generate the link menu message, get choice and execute it.
758 Options are stored in `doi-link-menu-funcs'."
759    (interactive)
760    (message
761    (concat
762     (mapconcat
763      (lambda (tup)
764        (concat "[" (elt tup 0) "]"
765                (elt tup 1) " "))
766      doi-link-menu-funcs "") ": "))
767    (let* ((input (read-char-exclusive))
768           (choice (assoc
769                    (char-to-string input) doi-link-menu-funcs)))
770      (when choice
771        (funcall
772         (elt
773          choice
774          2)
775         link-string))))
776
777 (org-add-link-type
778  "doi"
779  'doi-link-menu)
780
781
782 ;; * Getting a doi for a bibtex entry missing one
783 ;; Some bibtex entries do not have a DOI, maybe because they were entered by hand, or copied from a source that did not have it available. Here we develop some functions to help you find the DOI using Crossref.
784
785 ;; Here is our example bibtex entry.
786 ;; #+BEGIN_SRC bibtex
787 ;; @article{deml-2014-oxide,
788 ;;   author =    {Ann M. Deml and Vladan Stevanovi{\'c} and
789 ;;                   Christopher L. Muhich and Charles B. Musgrave and
790 ;;                   Ryan O'Hayre},
791 ;;   title =     {Oxide Enthalpy of Formation and Band Gap Energy As
792 ;;                   Accurate Descriptors of Oxygen Vacancy Formation
793 ;;                   Energetics},
794 ;;   journal =   {Energy Environ. Sci.},
795 ;;   volume =    7,
796 ;;   number =    6,
797 ;;   pages =     1996,
798 ;;   year =      2014,
799 ;;   doi =               {10.1039/c3ee43874k,
800 ;;   url =               {http://dx.doi.org/10.1039/c3ee43874k}},
801
802 ;; }
803
804
805 ;; The idea is to query Crossref in a way that is likely to give us a hit relevant to the entry.
806
807 ;; According to http://search.crossref.org/help/api we can send a query with a free form citation that may give us something back. We do this to get a list of candidates, and run a helm command to get the doi.
808
809
810
811 (defun doi-utils-crossref-citation-query ()
812   "Query Crossref with the title of the bibtex entry at point to
813 get a list of possible matches. This opens a helm buffer to
814 select an entry. The default action inserts a doi and url field
815 in the bibtex entry at point. The second action opens the doi
816 url. If there is already a doi field, the function raises an
817 error."
818   (interactive)
819   (bibtex-beginning-of-entry)
820   (let* ((entry (bibtex-parse-entry))
821          (json-string)
822          (json-data)
823          (doi))
824     (unless (string= ""(reftex-get-bib-field "doi" entry))
825       (error "Entry already has a doi field"))
826
827     (with-current-buffer
828         (url-retrieve-synchronously
829          (concat
830           "http://search.crossref.org/dois?q="
831           (url-hexify-string (org-ref-bib-citation))))
832       (setq json-string (buffer-substring url-http-end-of-headers (point-max)))
833       (setq json-data (json-read-from-string json-string)))
834
835     (let* ((name (format "Crossref hits for %s" (org-ref-bib-citation)))
836            (helm-candidates (mapcar (lambda (x)
837                                       (cons
838                                        (concat
839                                         (cdr (assoc 'fullCitation x))
840                                         " "
841                                         (cdr (assoc 'doi x)))
842                                        (cdr (assoc 'doi x))))
843                                       json-data))
844            (source `((name . ,name)
845                      (candidates . ,helm-candidates)
846                      ;; just return the candidate
847                      (action . (("Insert doi and url field" . (lambda (doi)
848                                                                 (bibtex-make-field "doi")
849                                                                 (backward-char)
850                                                                 ;; crossref returns doi url, but I prefer only a doi for the doi field
851                                                                 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi))
852                                                                 (when (string= ""(reftex-get-bib-field "url" entry))
853                                                                   (bibtex-make-field "url")
854                                                                   (backward-char)
855                                                                   (insert doi))))
856                                 ("Open url" . (lambda (doi)
857                                                 (browse-url doi))))))))
858       (helm :sources '(source)))))
859
860
861
862 ;; * Debugging a DOI
863 ;; I wrote this function to help debug a DOI. This function generates an org-buffer with the doi, gets the json metadata, shows the bibtex entry, and the pdf link for it.
864
865 (defun doi-utils-debug (doi)
866   "Generate an org-buffer showing data about DOI."
867   (interactive "sDOI: ")
868   (switch-to-buffer "*debug-doi*")
869   (erase-buffer)
870   (org-mode)
871   (insert (concat "doi:" doi) "\n\n")
872   (insert "* JSON
873 " (format "%s" (doi-utils-get-json-metadata doi)) "
874
875 * Bibtex
876
877 " (doi-utils-doi-to-bibtex-string doi) "
878
879 * PDF
880 " (doi-utils-get-pdf-url doi)))
881
882 ;; * Adding a bibtex entry from a crossref query
883 ;; The idea here is to perform a query on Crossref, get a helm buffer of candidates, and select the entry(ies) you want to add to your bibtex file. You can select a region, e.g. a free form citation, or set of words, or you can type the query in by hand.
884
885 (defun doi-utils-add-entry-from-crossref-query (query bibtex-file)
886   "Search Crossref with QUERY and use helm to select an entry to add to BIBTEX-FILE."
887   (interactive (list
888                 (read-input
889                  "Query: "
890                  ;; now set initial input
891                  (cond
892                   ;; If region is active assume we want it
893                   ((region-active-p)
894                    (replace-regexp-in-string
895                     "\n" " "
896                     (buffer-substring (region-beginning) (region-end))))
897                   ;; type or paste it in
898                   (t
899                    nil)))
900                 (ido-completing-read
901                  "Bibfile: "
902                  (append (f-entries "." (lambda (f) (f-ext? f "bib")))
903                          org-ref-default-bibliography))))
904   (let* ((json-string)
905          (json-data)
906          (doi))
907
908     (with-current-buffer
909         (url-retrieve-synchronously
910          (concat
911           "http://search.crossref.org/dois?q="
912           (url-hexify-string query)))
913       (setq json-string (buffer-substring url-http-end-of-headers (point-max)))
914       (setq json-data (json-read-from-string json-string)))
915
916     (let* ((name (format "Crossref hits for %s"
917                          ;; remove carriage returns. they cause problems in helm.
918                          (replace-regexp-in-string "\n" " " query)))
919            (helm-candidates (mapcar (lambda (x)
920                                       (cons
921                                        (concat
922                                         (cdr (assoc 'fullCitation x))
923                                         " "
924                                         (cdr (assoc 'doi x)))
925                                        (cdr (assoc 'doi x))))
926                                       json-data))
927            (source `((name . ,name)
928                      (candidates . ,helm-candidates)
929                      ;; just return the candidate
930                      (action . (("Insert bibtex entry" . (lambda (doi)
931                                                            (doi-utils-add-bibtex-entry-from-doi
932                                                             (replace-regexp-in-string "^http://dx.doi.org/" "" doi) ,bibtex-file)))
933                                 ("Open url" . (lambda (doi)
934                                                 (browse-url doi))))))))
935       (helm :sources '(source)))))
936
937 ;; * The end
938 (provide 'doi-utils)
939 ;;; doi-utils.el ends here