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