]> git.donarmstrong.com Git - org-ref.git/blob - doi-utils.el
added new journal abbreviations, and a helm function to set journal strings
[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-string "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     (with-current-buffer
559       (find-file-noselect bibfile)
560       ;; Check if the doi already exists
561       (goto-char (point-min))
562       (if (search-forward doi nil t)
563           (message "%s is already in this file" doi)
564         (end-of-buffer)
565         (insert "\n\n")
566         (doi-utils-insert-bibtex-entry-from-doi doi)
567         (save-buffer)))))
568
569
570 ;; * Updating bibtex entries
571 ;; 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.
572
573 ;; There is not bibtex set field function, so I wrote this one.
574
575
576 (defun bibtex-set-field (field value &optional nodelim)
577   "Set FIELD to VALUE in bibtex file.  create field if it does not exist.
578 Optional argument NODELIM see `bibtex-make-field'."
579   (interactive "sfield: \nsvalue: ")
580   (bibtex-beginning-of-entry)
581   (let ((found))
582     (if (setq found (bibtex-search-forward-field field t))
583         ;; we found a field
584         (progn
585           (goto-char (car (cdr found)))
586           (when value
587             (bibtex-kill-field)
588             (bibtex-make-field field nil nil nodelim)
589             (backward-char)
590             (insert value)))
591       ;; make a new field
592       (message "new field being made")
593       (bibtex-beginning-of-entry)
594       (forward-line) (beginning-of-line)
595       (bibtex-next-field nil)
596       (forward-char)
597       (bibtex-make-field field nil nil nodelim)
598       (backward-char)
599       (insert value))))
600
601
602 ;; 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.
603
604
605 (defun plist-get-keys (plist)
606    "Return keys in a PLIST."
607   (cl-loop
608    for key in results by #'cddr collect key))
609
610 (defun doi-utils-update-bibtex-entry-from-doi (doi)
611   "Update fields in a bibtex entry from the DOI.  Every field will be updated, so previous change will be lost."
612   (interactive (list
613                 (or (replace-regexp-in-string "http://dx.doi.org/" "" (bibtex-autokey-get-field "doi"))
614                     (read-string "DOI: "))))
615   (let* ((results (doi-utils-get-json-metadata doi))
616          (type (plist-get results :type))
617          (author (mapconcat
618                   (lambda (x) (concat (plist-get x :given)
619                                     " " (plist-get x :family)))
620                   (plist-get results :author) " and "))
621          (title (plist-get results :title))
622          (journal (plist-get results :container-title))
623          (year (format "%s"
624                        (elt
625                         (elt
626                          (plist-get
627                           (plist-get results :issued) :date-parts) 0) 0)))
628         (volume (plist-get results :volume))
629         (number (or (plist-get results :issue) ""))
630         (pages (or (plist-get results :page) ""))
631         (url (or (plist-get results :URL) ""))
632         (doi (plist-get results :DOI)))
633
634     ;; map the json fields to bibtex fields. The code each field is mapped to is evaluated.
635     (setq mapping '((:author . (bibtex-set-field "author" author))
636                     (:title . (bibtex-set-field "title" title))
637                     (:container-title . (bibtex-set-field "journal" journal))
638                     (:issued . (bibtex-set-field "year" year))
639                     (:volume . (bibtex-set-field "volume" volume))
640                     (:issue . (bibtex-set-field "number" number))
641                     (:page . (bibtex-set-field "pages" pages))
642                     (:DOI . (bibtex-set-field "doi" doi))
643                     (:URL . (bibtex-set-field "url" url))))
644
645     ;; now we have code to run for each entry. we map over them and evaluate the code
646     (mapcar
647      (lambda (key)
648        (eval (cdr (assoc key mapping))))
649      (plist-get-keys results)))
650
651   ; reclean entry, but keep key if it exists.
652   (if (bibtex-key-in-head)
653       (org-ref-clean-bibtex-entry t)
654     (org-ref-clean-bibtex-entry)))
655
656
657 ;; 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.
658
659
660 (defun doi-utils-update-field ()
661   "Update the field at point in the bibtex entry.
662 Data is retrieved from the doi in the entry."
663   (interactive)
664   (let* ((doi (bibtex-autokey-get-field "doi"))
665          (results (doi-utils-get-json-metadata doi))
666          (field (car (bibtex-find-text-internal nil nil ","))))
667     (cond
668      ((string= field "volume")
669       (bibtex-set-field field (plist-get results :volume)))
670      ((string= field "number")
671       (bibtex-set-field field (plist-get results :issue)))
672      ((string= field "pages")
673       (bibtex-set-field field (plist-get results :page)))
674      ((string= field "year")
675       (bibtex-set-field field (plist-get results :year)))
676      (t
677       (message "%s not supported yet." field)))))
678
679
680
681 ;; * DOI functions for WOS
682 ;; 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.
683
684
685 ;; 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
686 ;; 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
687 ;; 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
688
689 ;; 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.
690
691 (defun doi-utils-wos (doi)
692   "Open Web of Science entry for DOI."
693   (interactive "sDOI: ")
694   (browse-url
695    (format
696     "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info:doi/%s" doi)))
697
698 (defun doi-utils-wos-citing (doi)
699   "Open Web of Science citing articles entry for DOI.
700 May be empty if none are found."
701   (interactive "sDOI: ")
702   (browse-url
703    (concat
704     "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
705     doi
706     "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.citing=yes")))
707
708 (defun doi-utils-wos-related (doi)
709   "Open Web of Science related articles page for DOI."
710   (interactive "sDOI: ")
711   (browse-url
712    (concat "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
713            doi
714            "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.related=yes")))
715
716
717
718
719 ;; * A new doi link for org-mode
720 ;; 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.
721 ;; 1. open doi
722 ;; 2. open in wos
723 ;; 3. open citing articles
724 ;; 4. open related articles
725 ;; 5. open bibtex entry
726 ;; 6. get bibtex entry
727
728
729 (defun doi-utils-open (doi)
730   "Open DOI in browser."
731  (interactive "sDOI: ")
732  (browse-url (concat "http://dx.doi.org/" doi)))
733
734
735 (defun doi-utils-open-bibtex (doi)
736   "Search through variable `reftex-default-bibliography' for DOI."
737   (interactive "sDOI: ")
738   (catch 'file
739     (dolist (f reftex-default-bibliography)
740       (find-file f)
741       (when (search-forward doi (point-max) t)
742         (bibtex-beginning-of-entry)
743         (throw 'file t)))))
744
745
746 (defun doi-utils-crossref (doi)
747   "Search DOI in CrossRef."
748   (interactive "sDOI: ")
749   (browse-url
750    (format
751     "http://search.crossref.org/?q=%s" doi)))
752
753
754 (defun doi-utils-google-scholar (doi)
755   "Google scholar the DOI."
756   (interactive "sDOI: ")
757   (browse-url
758    (format
759     "http://scholar.google.com/scholar?q=%s" doi)))
760
761
762 (defun doi-utils-pubmed (doi)
763   "Search Pubmed for the DOI."
764   (interactive "sDOI: ")
765   (browse-url
766    (format
767     "http://www.ncbi.nlm.nih.gov/pubmed/?term=%s"
768     (url-hexify-string doi))))
769
770
771 (defvar doi-link-menu-funcs '()
772  "Functions to run in doi menu.
773 Each entry is a list of (key menu-name function).  The function
774 must take one argument, the doi.")
775
776 (setq doi-link-menu-funcs
777       '(("o" "pen" doi-utils-open)
778         ("w" "os" doi-utils-wos)
779         ("c" "iting articles" doi-utils-wos-citing)
780         ("r" "elated articles" doi-utils-wos-related)
781         ("s" "Google Scholar" doi-utils-google-scholar)
782         ("f" "CrossRef" doi-utils-crossref)
783         ("p" "ubmed" doi-utils-pubmed)
784         ("b" "open in bibtex" doi-utils-open-bibtex)
785         ("g" "et bibtex entry" doi-utils-add-bibtex-entry-from-doi)))
786
787
788 (defun doi-link-menu (link-string)
789    "Generate the link menu message, get choice and execute it.
790 Options are stored in `doi-link-menu-funcs'.
791 Argument LINK-STRING Passed in on link click."
792    (interactive)
793    (message
794    (concat
795     (mapconcat
796      (lambda (tup)
797        (concat "[" (elt tup 0) "]"
798                (elt tup 1) " "))
799      doi-link-menu-funcs "") ": "))
800    (let* ((input (read-char-exclusive))
801           (choice (assoc
802                    (char-to-string input) doi-link-menu-funcs)))
803      (when choice
804        (funcall
805         (elt
806          choice
807          2)
808         link-string))))
809
810 (org-add-link-type
811  "doi"
812  'doi-link-menu)
813
814
815 ;; * Getting a doi for a bibtex entry missing one
816 ;; 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.
817
818 ;; Here is our example bibtex entry.
819 ;; #+BEGIN_SRC bibtex
820 ;; @article{deml-2014-oxide,
821 ;;   author =    {Ann M. Deml and Vladan Stevanovi{\'c} and
822 ;;                   Christopher L. Muhich and Charles B. Musgrave and
823 ;;                   Ryan O'Hayre},
824 ;;   title =     {Oxide Enthalpy of Formation and Band Gap Energy As
825 ;;                   Accurate Descriptors of Oxygen Vacancy Formation
826 ;;                   Energetics},
827 ;;   journal =   {Energy Environ. Sci.},
828 ;;   volume =    7,
829 ;;   number =    6,
830 ;;   pages =     1996,
831 ;;   year =      2014,
832 ;;   doi =               {10.1039/c3ee43874k,
833 ;;   url =               {http://dx.doi.org/10.1039/c3ee43874k}},
834
835 ;; }
836
837
838 ;; The idea is to query Crossref in a way that is likely to give us a hit relevant to the entry.
839
840 ;; 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.
841
842
843
844 (defun doi-utils-crossref-citation-query ()
845   "Query Crossref with the title of the bibtex entry at point to
846 get a list of possible matches. This opens a helm buffer to
847 select an entry. The default action inserts a doi and url field
848 in the bibtex entry at point. The second action opens the doi
849 url. If there is already a doi field, the function raises an
850 error."
851   (interactive)
852   (bibtex-beginning-of-entry)
853   (let* ((entry (bibtex-parse-entry))
854          (json-string)
855          (json-data)
856          (doi))
857     (unless (string= ""(reftex-get-bib-field "doi" entry))
858       (error "Entry already has a doi field"))
859
860     (with-current-buffer
861         (url-retrieve-synchronously
862          (concat
863           "http://search.crossref.org/dois?q="
864           (url-hexify-string (org-ref-bib-citation))))
865       (setq json-string (buffer-substring url-http-end-of-headers (point-max)))
866       (setq json-data (json-read-from-string json-string)))
867
868     (let* ((name (format "Crossref hits for %s" (org-ref-bib-citation)))
869            (helm-candidates (mapcar (lambda (x)
870                                       (cons
871                                        (concat
872                                         (cdr (assoc 'fullCitation x))
873                                         " "
874                                         (cdr (assoc 'doi x)))
875                                        (cdr (assoc 'doi x))))
876                                       json-data))
877            (source `((name . ,name)
878                      (candidates . ,helm-candidates)
879                      ;; just return the candidate
880                      (action . (("Insert doi and url field" . (lambda (doi)
881                                                                 (bibtex-make-field "doi")
882                                                                 (backward-char)
883                                                                 ;; crossref returns doi url, but I prefer only a doi for the doi field
884                                                                 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi))
885                                                                 (when (string= ""(reftex-get-bib-field "url" entry))
886                                                                   (bibtex-make-field "url")
887                                                                   (backward-char)
888                                                                   (insert doi))))
889                                 ("Open url" . (lambda (doi)
890                                                 (browse-url doi))))))))
891       (helm :sources '(source)))))
892
893
894
895 ;; * Debugging a DOI
896 ;; 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.
897
898 (defun doi-utils-debug (doi)
899   "Generate an org-buffer showing data about DOI."
900   (interactive "sDOI: ")
901   (switch-to-buffer "*debug-doi*")
902   (erase-buffer)
903   (org-mode)
904   (insert (concat "doi:" doi) "\n\n")
905   (insert "* JSON
906 " (format "%s" (doi-utils-get-json-metadata doi)) "
907
908 * Bibtex
909
910 " (doi-utils-doi-to-bibtex-string doi) "
911
912 * PDF
913 " (doi-utils-get-pdf-url doi)))
914
915 ;; * Adding a bibtex entry from a crossref query
916 ;; 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.
917
918 (defun doi-utils-add-entry-from-crossref-query (query bibtex-file)
919   "Search Crossref with QUERY and use helm to select an entry to add to BIBTEX-FILE."
920   (interactive (list
921                 (read-string
922                  "Query: "
923                  ;; now set initial input
924                  (cond
925                   ;; If region is active assume we want it
926                   ((region-active-p)
927                    (replace-regexp-in-string
928                     "\n" " "
929                     (buffer-substring (region-beginning) (region-end))))
930                   ;; type or paste it in
931                   (t
932                    nil)))
933                 (ido-completing-read
934                  "Bibfile: "
935                  (append (f-entries "." (lambda (f) (f-ext? f "bib")))
936                          org-ref-default-bibliography))))
937   (let* ((json-string)
938          (json-data)
939          (doi))
940
941     (with-current-buffer
942         (url-retrieve-synchronously
943          (concat
944           "http://search.crossref.org/dois?q="
945           (url-hexify-string query)))
946       (setq json-string (buffer-substring url-http-end-of-headers (point-max)))
947       (setq json-data (json-read-from-string json-string)))
948
949     (let* ((name (format "Crossref hits for %s"
950                          ;; remove carriage returns. they cause problems in helm.
951                          (replace-regexp-in-string "\n" " " query)))
952            (helm-candidates (mapcar (lambda (x)
953                                       (cons
954                                        (concat
955                                         (cdr (assoc 'fullCitation x))
956                                         " "
957                                         (cdr (assoc 'doi x)))
958                                        (cdr (assoc 'doi x))))
959                                       json-data))
960            (source `((name . ,name)
961                      (candidates . ,helm-candidates)
962                      ;; just return the candidate
963                      (action . (("Insert bibtex entry" . (lambda (doi)
964                                                            (doi-utils-add-bibtex-entry-from-doi
965                                                             (replace-regexp-in-string "^http://dx.doi.org/" "" doi) ,bibtex-file)))
966                                 ("Open url" . (lambda (doi)
967                                                 (browse-url doi))))))))
968       (helm :sources '(source)))))
969
970 ;; * The end
971 (provide 'doi-utils)
972 ;;; doi-utils.el ends here