]> git.donarmstrong.com Git - org-ref.git/blob - doi-utils.el
fix two other ,* typos
[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   "returns a url to a pdf for the doi if one can be
290 calculated. 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
310 exist locally. 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. Also cleans entry using
480 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 changes 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   (interactive)
633   (let* ((doi (bibtex-autokey-get-field "doi"))
634          (results (doi-utils-get-json-metadata doi))
635          (field (car (bibtex-find-text-internal nil nil ","))))
636     (cond
637      ((string= field "volume")
638       (bibtex-set-field field (plist-get results :volume)))
639      ((string= field "number")
640       (bibtex-set-field field (plist-get results :issue)))
641      ((string= field "pages")
642       (bibtex-set-field field (plist-get results :page)))
643      ((string= field "year")
644       (bibtex-set-field field (plist-get results :year)))
645      (t
646       (message "%s not supported yet." field)))))
647
648
649
650 ;; * DOI functions for WOS
651 ;; 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.
652
653
654 ;; 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
655 ;; 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
656 ;; 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
657
658 ;; 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.
659
660 (defun doi-utils-wos (doi)
661   "Open Web of Science entry for DOI"
662   (interactive "sDOI: ")
663   (browse-url
664    (format
665     "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info:doi/%s" doi)))
666
667 (defun doi-utils-wos-citing (doi)
668   "Open Web of Science citing articles entry. May be empty if none are found"
669   (interactive "sDOI: ")
670   (browse-url
671    (concat
672     "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
673     doi
674     "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.citing=yes")))
675
676 (defun doi-utils-wos-related (doi)
677   "Open Web of Science related articles page."
678   (interactive "sDOI: ")
679   (browse-url
680    (concat "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
681            doi
682            "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.related=yes")))
683
684
685
686
687 ;; * A new doi link for org-mode
688 ;; 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.
689 ;; 1. open doi
690 ;; 2. open in wos
691 ;; 3. open citing articles
692 ;; 4. open related articles
693 ;; 5. open bibtex entry
694 ;; 6. get bibtex entry
695
696
697 (defun doi-utils-open (doi)
698  (interactive "sDOI: ")
699  (browse-url (concat "http://dx.doi.org/" doi)))
700
701
702 (defun doi-utils-open-bibtex (doi)
703   "Search through `reftex-default-bibliography' for DOI."
704   (interactive "sDOI: ")
705   (catch 'file
706     (dolist (f reftex-default-bibliography)
707       (find-file f)
708       (when (search-forward doi (point-max) t)
709         (bibtex-beginning-of-entry)
710         (throw 'file t)))))
711
712
713 (defun doi-utils-crossref (doi)
714   "Search DOI in CrossRef."
715   (interactive "sDOI: ")
716   (browse-url
717    (format
718     "http://search.crossref.org/?q=%s" doi)))
719
720
721 (defun doi-utils-google-scholar (doi)
722   "Google scholar the word at point or selection."
723   (interactive "sDOI: ")
724   (browse-url
725    (format
726     "http://scholar.google.com/scholar?q=%s" doi)))
727
728
729 (defun doi-utils-pubmed (doi)
730   "Pubmed the word at point or selection."
731   (interactive "sDOI: ")
732   (browse-url
733    (format
734     "http://www.ncbi.nlm.nih.gov/pubmed/?term=%s"
735     (url-hexify-string doi))))
736
737
738 (defvar doi-link-menu-funcs '()
739  "Functions to run in doi menu. Each entry is a list of (key menu-name function).
740 The function must take one argument, the doi.")
741
742 (setq doi-link-menu-funcs
743       '(("o" "pen" doi-utils-open)
744         ("w" "os" doi-utils-wos)
745         ("c" "iting articles" doi-utils-wos-citing)
746         ("r" "elated articles" doi-utils-wos-related)
747         ("s" "Google Scholar" doi-utils-google-scholar)
748         ("f" "CrossRef" doi-utils-crossref)
749         ("p" "ubmed" doi-utils-pubmed)
750         ("b" "open in bibtex" doi-utils-open-bibtex)
751         ("g" "et bibtex entry" doi-utils-add-bibtex-entry-from-doi)))
752
753
754 (defun doi-link-menu (link-string)
755    "Generate the link menu message, get choice and execute it.
756 Options are stored in `doi-link-menu-funcs'."
757    (interactive)
758    (message
759    (concat
760     (mapconcat
761      (lambda (tup)
762        (concat "[" (elt tup 0) "]"
763                (elt tup 1) " "))
764      doi-link-menu-funcs "") ": "))
765    (let* ((input (read-char-exclusive))
766           (choice (assoc
767                    (char-to-string input) doi-link-menu-funcs)))
768      (when choice
769        (funcall
770         (elt
771          choice
772          2)
773         link-string))))
774
775 (org-add-link-type
776  "doi"
777  'doi-link-menu)
778
779
780 ;; * Getting a doi for a bibtex entry missing one
781 ;; 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.
782
783 ;; Here is our example bibtex entry.
784 ;; #+BEGIN_SRC bibtex
785 ;; @article{deml-2014-oxide,
786 ;;   author =    {Ann M. Deml and Vladan Stevanovi{\'c} and
787 ;;                   Christopher L. Muhich and Charles B. Musgrave and
788 ;;                   Ryan O'Hayre},
789 ;;   title =     {Oxide Enthalpy of Formation and Band Gap Energy As
790 ;;                   Accurate Descriptors of Oxygen Vacancy Formation
791 ;;                   Energetics},
792 ;;   journal =   {Energy Environ. Sci.},
793 ;;   volume =    7,
794 ;;   number =    6,
795 ;;   pages =     1996,
796 ;;   year =      2014,
797 ;;   doi =               {10.1039/c3ee43874k,
798 ;;   url =               {http://dx.doi.org/10.1039/c3ee43874k}},
799
800 ;; }
801
802
803 ;; The idea is to query Crossref in a way that is likely to give us a hit relevant to the entry.
804
805 ;; 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.
806
807
808
809 (defun doi-utils-crossref-citation-query ()
810   "Query Crossref with the title of the bibtex entry at point to
811 get a list of possible matches. This opens a helm buffer to
812 select an entry. The default action inserts a doi and url field
813 in the bibtex entry at point. The second action opens the doi
814 url. If there is already a doi field, the function raises an
815 error."
816   (interactive)
817   (bibtex-beginning-of-entry)
818   (let* ((entry (bibtex-parse-entry))
819          (json-string)
820          (json-data)
821          (doi))
822     (unless (string= ""(reftex-get-bib-field "doi" entry))
823       (error "Entry already has a doi field"))
824
825     (with-current-buffer
826         (url-retrieve-synchronously
827          (concat
828           "http://search.crossref.org/dois?q="
829           (url-hexify-string (org-ref-bib-citation))))
830       (setq json-string (buffer-substring url-http-end-of-headers (point-max)))
831       (setq json-data (json-read-from-string json-string)))
832
833     (let* ((name (format "Crossref hits for %s" (org-ref-bib-citation)))
834            (helm-candidates (mapcar (lambda (x)
835                                       (cons
836                                        (concat
837                                         (cdr (assoc 'fullCitation x))
838                                         " "
839                                         (cdr (assoc 'doi x)))
840                                        (cdr (assoc 'doi x))))
841                                       json-data))
842            (source `((name . ,name)
843                      (candidates . ,helm-candidates)
844                      ;; just return the candidate
845                      (action . (("Insert doi and url field" . (lambda (doi)
846                                                                 (bibtex-make-field "doi")
847                                                                 (backward-char)
848                                                                 ;; crossref returns doi url, but I prefer only a doi for the doi field
849                                                                 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi))
850                                                                 (when (string= ""(reftex-get-bib-field "url" entry))
851                                                                   (bibtex-make-field "url")
852                                                                   (backward-char)
853                                                                   (insert doi))))
854                                 ("Open url" . (lambda (doi)
855                                                 (browse-url doi))))))))
856       (helm :sources '(source)))))
857
858
859
860 ;; * Debugging a DOI
861 ;; 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.
862
863 (defun doi-utils-debug (doi)
864   "Generate an org-buffer showing data about DOI."
865   (interactive "sDOI: ")
866   (switch-to-buffer "*debug-doi*")
867   (erase-buffer)
868   (org-mode)
869   (insert (concat "doi:" doi) "\n\n")
870   (insert "* JSON
871 " (format "%s" (doi-utils-get-json-metadata doi)) "
872
873 * Bibtex
874
875 " (doi-utils-doi-to-bibtex-string doi) "
876
877 * PDF
878 " (doi-utils-get-pdf-url doi)))
879
880 ;; * Adding a bibtex entry from a crossref query
881 ;; 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.
882
883 (defun doi-utils-add-entry-from-crossref-query (query bibtex-file)
884   (interactive (list
885                 (read-input
886                  "Query: "
887                  ;; now set initial input
888                  (cond
889                   ;; If region is active assume we want it
890                   ((region-active-p)
891                    (replace-regexp-in-string
892                     "\n" " "
893                     (buffer-substring (region-beginning) (region-end))))
894                   ;; type or paste it in
895                   (t
896                    nil)))
897                 (ido-completing-read
898                  "Bibfile: "
899                  (append (f-entries "." (lambda (f) (f-ext? f "bib")))
900                          org-ref-default-bibliography))))
901   (let* ((json-string)
902          (json-data)
903          (doi))
904
905     (with-current-buffer
906         (url-retrieve-synchronously
907          (concat
908           "http://search.crossref.org/dois?q="
909           (url-hexify-string query)))
910       (setq json-string (buffer-substring url-http-end-of-headers (point-max)))
911       (setq json-data (json-read-from-string json-string)))
912
913     (let* ((name (format "Crossref hits for %s"
914                          ;; remove carriage returns. they cause problems in helm.
915                          (replace-regexp-in-string "\n" " " query)))
916            (helm-candidates (mapcar (lambda (x)
917                                       (cons
918                                        (concat
919                                         (cdr (assoc 'fullCitation x))
920                                         " "
921                                         (cdr (assoc 'doi x)))
922                                        (cdr (assoc 'doi x))))
923                                       json-data))
924            (source `((name . ,name)
925                      (candidates . ,helm-candidates)
926                      ;; just return the candidate
927                      (action . (("Insert bibtex entry" . (lambda (doi)
928                                                            (doi-utils-add-bibtex-entry-from-doi
929                                                             (replace-regexp-in-string "^http://dx.doi.org/" "" doi) ,bibtex-file)))
930                                 ("Open url" . (lambda (doi)
931                                                 (browse-url doi))))))))
932       (helm :sources '(source)))))
933
934 ;; * The end
935 (provide 'doi-utils)
936 ;;; doi-utils.el ends here