1 ;;; doi-utils.el --- DOI utilities for making bibtex entries
3 ;; Copyright (C) 2015 John Kitchin
5 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
6 ;; Keywords: convenience
8 ;; Package-Requires: ((org-ref))
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.
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.
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/>.
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.
27 ;; The principle commands you will use from here are:
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.
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.
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.
43 (defvar *doi-utils-waiting* t
44 "Stores waiting state for url retrieval.")
46 (defvar *doi-utils-redirect* nil
47 "Stores redirect url from a callback function.")
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))
61 ;; To actually get the redirect we use url-retrieve like this.
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)
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)))
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:
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.")
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*)))
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")))
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))))
112 ;; http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/abstract
113 ;; http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/pdf
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.
117 ;; This is where the link is hidden:
119 ;; <iframe id="pdfDocument" src="http://onlinelibrary.wiley.com/store/10.1002/anie.201402680/asset/6397_ftp.pdf?v=1&t=hwut2142&s=d4bb3cd4ad20eb733836717f42346ffb34017831" width="100%" height="675px"></iframe>
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
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))
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*))
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"))))
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
156 ;; we just change /abs/ to /pdf/.
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*)))
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"))))
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")))
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
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"
198 ;; ** Taylor and Francis
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*)))
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*)))
212 ;; http://ecst.ecsdl.org/content/25/2/2769
213 ;; http://ecst.ecsdl.org/content/25/2/2769.full.pdf
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")))
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))
232 ;; ** Elsevier/ScienceDirect
233 ;; You cannot compute these pdf links; they are embedded in the redirected pages.
235 (defvar *doi-utils-pdf-url* nil
236 "Stores url to pdf download from a callback function.")
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
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))
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*))
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*."
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*)))
274 ;; http://www.pnas.org/content/early/2014/05/08/1319030111
275 ;; http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf
277 ;; with supporting info
278 ;; http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf+html?with-ds=yes
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")))
286 ;; ** Add all functions
288 (setq doi-utils-pdf-url-functions
299 'science-direct-pdf-url
300 'linkinghub-elsevier-pdf-url
307 ;; ** Get the pdf url for a doi
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'
313 (doi-utils-get-redirect doi)
315 (unless *doi-utils-redirect*
316 (error "No redirect found for %s" doi))
317 (message "applying functions")
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)
324 (message "found pdf url: %s" this-pdf-url)
325 (throw 'pdf-url this-pdf-url))))))
327 ;; ** Finally, download the pdf
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
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")))
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"))
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))
358 (url-copy-file pdf-url pdf-file)
359 ;; now check if we got a pdf
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-"))
365 (message "%s" (buffer-string))
366 (delete-file pdf-file))
367 (message "%s saved" pdf-file)))
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* ))
374 ;; * Getting bibtex entries from a DOI
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.
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)
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)
390 (browse-url (concat "http://dx.doi.org/" doi))
391 (error "Resource not found. Opening website"))
392 (json-read-from-string json-data)))))
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.
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 "%{\\([^}]+\\)}"
401 (let ((sexp (substring arg 2 -1)))
402 (format "%s" (eval (read sexp))))) s))
405 ;; Now we define a function that fills in that template from the metadata.
407 ;; As different bibtex types share common keys, it is advantageous to separate data extraction from json, and the formatting of the bibtex entry.
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))))
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.
431 (setq doi-utils-bibtex-type-generators nil)
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
440 (cond ((null lst) (nreverse acc))
441 ((and (stringp (car lst))
443 (doi-utils-concat-prepare (cdr lst) (cons (concat (car acc) (car lst))
445 (t (doi-utils-concat-prepare (cdr lst) (cons (car lst) acc)))))
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)
457 `(string= type ,match-type)) matching-types))
458 (let ,(mapcar (lambda (field)
460 (assoc field doi-utils-json-metadata-extract)))
462 ;; need to convert to string first
463 `(,(car field-expr) (format "%s" ,(cadr field-expr)))
464 (error "Unknown bibtex field type %s" field))))
467 ,@(doi-utils-concat-prepare
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"))
476 doi-utils-bibtex-type-generators))
478 (doi-utils-def-bibtex-type article ("journal-article" "article-journal")
479 author title journal year volume number pages doi url)
481 (doi-utils-def-bibtex-type inproceedings ("proceedings-article")
482 author title booktitle year month pages doi url)
484 (doi-utils-def-bibtex-type book ("book")
485 author title series publisher year pages doi url)
487 (doi-utils-def-bibtex-type inbook ("book-chapter")
488 author title booktitle series publisher year pages doi url)
492 ;; With the code generating the bibtex entry in place, we can glue it to the json retrieval code.
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))))
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.
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))
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))
517 (doi-utils-get-bibtex-entry-pdf)
518 (save-selected-window
519 (org-ref-open-bibtex-notes)))
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.
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."
533 (list (read-string "DOI: "
534 ;; now set initial input
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
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))
546 ;; otherwise, we have no initial input. You
547 ;; will have to type it in.
550 ;; now get the bibfile to add it to
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
557 (save-window-excursion
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)
566 (doi-utils-insert-bibtex-entry-from-doi doi)
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.
573 ;; There is not bibtex set field function, so I wrote this one.
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)
582 (if (setq found (bibtex-search-forward-field field t))
585 (goto-char (car (cdr found)))
588 (bibtex-make-field field nil nil nodelim)
592 (message "new field being made")
593 (bibtex-beginning-of-entry)
594 (forward-line) (beginning-of-line)
595 (bibtex-next-field nil)
597 (bibtex-make-field field nil nil nodelim)
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.
605 (defun plist-get-keys (plist)
606 "Return keys in a PLIST."
608 for key in results by #'cddr collect key))
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."
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))
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))
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)))
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))))
645 ;; now we have code to run for each entry. we map over them and evaluate the code
648 (eval (cdr (assoc key mapping))))
649 (plist-get-keys results)))
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)))
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.
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."
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 ","))))
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)))
677 (message "%s not supported yet." field)))))
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.
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
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.
691 (defun doi-utils-wos (doi)
692 "Open Web of Science entry for DOI."
693 (interactive "sDOI: ")
696 "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info:doi/%s" doi)))
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: ")
704 "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
706 "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.citing=yes")))
708 (defun doi-utils-wos-related (doi)
709 "Open Web of Science related articles page for DOI."
710 (interactive "sDOI: ")
712 (concat "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
714 "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.related=yes")))
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.
723 ;; 3. open citing articles
724 ;; 4. open related articles
725 ;; 5. open bibtex entry
726 ;; 6. get bibtex entry
729 (defun doi-utils-open (doi)
730 "Open DOI in browser."
731 (interactive "sDOI: ")
732 (browse-url (concat "http://dx.doi.org/" doi)))
735 (defun doi-utils-open-bibtex (doi)
736 "Search through variable `reftex-default-bibliography' for DOI."
737 (interactive "sDOI: ")
739 (dolist (f reftex-default-bibliography)
741 (when (search-forward doi (point-max) t)
742 (bibtex-beginning-of-entry)
746 (defun doi-utils-crossref (doi)
747 "Search DOI in CrossRef."
748 (interactive "sDOI: ")
751 "http://search.crossref.org/?q=%s" doi)))
754 (defun doi-utils-google-scholar (doi)
755 "Google scholar the DOI."
756 (interactive "sDOI: ")
759 "http://scholar.google.com/scholar?q=%s" doi)))
762 (defun doi-utils-pubmed (doi)
763 "Search Pubmed for the DOI."
764 (interactive "sDOI: ")
767 "http://www.ncbi.nlm.nih.gov/pubmed/?term=%s"
768 (url-hexify-string doi))))
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.")
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)))
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."
797 (concat "[" (elt tup 0) "]"
799 doi-link-menu-funcs "") ": "))
800 (let* ((input (read-char-exclusive))
802 (char-to-string input) doi-link-menu-funcs)))
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.
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
824 ;; title = {Oxide Enthalpy of Formation and Band Gap Energy As
825 ;; Accurate Descriptors of Oxygen Vacancy Formation
827 ;; journal = {Energy Environ. Sci.},
832 ;; doi = {10.1039/c3ee43874k,
833 ;; url = {http://dx.doi.org/10.1039/c3ee43874k}},
838 ;; The idea is to query Crossref in a way that is likely to give us a hit relevant to the entry.
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.
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
852 (bibtex-beginning-of-entry)
853 (let* ((entry (bibtex-parse-entry))
857 (unless (string= ""(reftex-get-bib-field "doi" entry))
858 (error "Entry already has a doi field"))
861 (url-retrieve-synchronously
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)))
868 (let* ((name (format "Crossref hits for %s" (org-ref-bib-citation)))
869 (helm-candidates (mapcar (lambda (x)
872 (cdr (assoc 'fullCitation x))
874 (cdr (assoc 'doi x)))
875 (cdr (assoc 'doi x))))
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")
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")
889 ("Open url" . (lambda (doi)
890 (browse-url doi))))))))
891 (helm :sources '(source)))))
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.
898 (defun doi-utils-debug (doi)
899 "Generate an org-buffer showing data about DOI."
900 (interactive "sDOI: ")
901 (switch-to-buffer "*debug-doi*")
904 (insert (concat "doi:" doi) "\n\n")
906 " (format "%s" (doi-utils-get-json-metadata doi)) "
910 " (doi-utils-doi-to-bibtex-string doi) "
913 " (doi-utils-get-pdf-url doi)))
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.
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."
923 ;; now set initial input
925 ;; If region is active assume we want it
927 (replace-regexp-in-string
929 (buffer-substring (region-beginning) (region-end))))
930 ;; type or paste it in
935 (append (f-entries "." (lambda (f) (f-ext? f "bib")))
936 org-ref-default-bibliography))))
942 (url-retrieve-synchronously
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)))
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)
955 (cdr (assoc 'fullCitation x))
957 (cdr (assoc 'doi x)))
958 (cdr (assoc 'doi x))))
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)))))
972 ;;; doi-utils.el ends here