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 (when (plist-get status :error)
52 (signal (car (plist-get status :error)) (cdr(plist-get status :error))))
53 (when (plist-get status :redirect) ; is nil if there none
54 (message "redirects = %s" (plist-get status :redirect))
55 (message "*doi-utils-redirect* set to %s"
56 (setq *doi-utils-redirect* (plist-get status :redirect))))
57 ;; we have done our job, so we are not waiting any more.
58 (setq *doi-utils-waiting* nil))
60 ;; To actually get the redirect we use url-retrieve like this.
62 (defun doi-utils-get-redirect (doi)
63 "get redirect url from dx.doi.org/doi"
64 ;; we are going to wait until the url-retrieve is done
65 (setq *doi-utils-waiting* t)
66 ;; start with no redirect. it will be set in the callback.
67 (setq *doi-utils-redirect* nil)
69 (format "http://dx.doi.org/%s" doi)
70 'doi-utils-redirect-callback)
71 ; I suspect we need to wait here for the asynchronous process to
72 ; finish. we loop and sleep until the callback says it is done via
73 ; `*doi-utils-waiting*'. this works as far as i can tell. Before I
74 ; had to run this a few times to get it to work, which i suspect
75 ; just gave the first one enough time to finish.
76 (while *doi-utils-waiting* (sleep-for 0.1)))
78 ;; Once we have a redirect for a particular doi, we need to compute the url to the pdf. We do this with a series of functions. Each function takes a single argument, the redirect url. If it knows how to compute the pdf url it does, and returns it. We store the functions in a variable:
80 (defvar doi-utils-pdf-url-functions nil
81 "list of functions that return a url to a pdf from a redirect url. Each function takes one argument, the redirect url. The function must return a pdf-url, or nil.")
86 (defun aps-pdf-url (*doi-utils-redirect*)
87 (when (string-match "^http://journals.aps.org" *doi-utils-redirect*)
88 (replace-regexp-in-string "/abstract/" "/pdf/" *doi-utils-redirect*)))
93 (defun science-pdf-url (*doi-utils-redirect*)
94 (when (string-match "^http://www.sciencemag.org" *doi-utils-redirect*)
95 (concat *doi-utils-redirect* ".full.pdf")))
100 (defun nature-pdf-url (*doi-utils-redirect*)
101 (when (string-match "^http://www.nature.com" *doi-utils-redirect*)
102 (let ((result *doi-utils-redirect*))
103 (setq result (replace-regexp-in-string "/full/" "/pdf/" result))
104 (replace-regexp-in-string "\.html$" "\.pdf" result))))
108 ;; http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/abstract
109 ;; http://onlinelibrary.wiley.com/doi/10.1002/anie.201402680/pdf
111 ;; It appears that it is not enough to use the pdf url above. That takes you to an html page. The actual link to teh pdf is embedded in that page. This is how ScienceDirect does things too.
113 ;; This is where the link is hidden:
115 ;; <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>
118 (defun doi-utils-get-wiley-pdf-url (redirect-url)
119 "Wileyscience direct hides the pdf url in html.
120 We get it out here by parsing the html."
121 (setq *doi-utils-waiting* t)
122 (url-retrieve redirect-url
124 (goto-char (point-min))
125 (re-search-forward "<iframe id=\"pdfDocument\" src=\"\\([^\"]*\\)\"" nil)
126 (setq *doi-utils-pdf-url* (match-string 1)
127 *doi-utils-waiting* nil)))
128 (while *doi-utils-waiting* (sleep-for 0.1))
131 (defun wiley-pdf-url (*doi-utils-redirect*)
132 (when (string-match "^http://onlinelibrary.wiley.com" *doi-utils-redirect*)
133 (doi-utils-get-wiley-pdf-url
134 (replace-regexp-in-string "/abstract" "/pdf" *doi-utils-redirect*))
135 *doi-utils-pdf-url*))
140 (defun springer-pdf-url (*doi-utils-redirect*)
141 (when (string-match "^http://link.springer.com" *doi-utils-redirect*)
142 (replace-regexp-in-string "/article/" "/content/pdf/" (concat *doi-utils-redirect* ".pdf"))))
146 ;; here is a typical url http://pubs.acs.org/doi/abs/10.1021/nl500037x
147 ;; the pdf is found at http://pubs.acs.org/doi/pdf/10.1021/nl500037x
149 ;; we just change /abs/ to /pdf/.
151 (defun acs-pdf-url (*doi-utils-redirect*)
152 (when (string-match "^http://pubs.acs.org" *doi-utils-redirect*)
153 (replace-regexp-in-string "/abs/" "/pdf/" *doi-utils-redirect*)))
158 (defun iop-pdf-url (*doi-utils-redirect*)
159 (when (string-match "^http://iopscience.iop.org" *doi-utils-redirect*)
160 (let ((tail (replace-regexp-in-string
161 "^http://iopscience.iop.org" "" *doi-utils-redirect*)))
162 (concat "http://iopscience.iop.org" tail
163 "/pdf" (replace-regexp-in-string "/" "_" tail) ".pdf"))))
168 (defun jstor-pdf-url (*doi-utils-redirect*)
169 (when (string-match "^http://www.jstor.org" *doi-utils-redirect*)
170 (concat (replace-regexp-in-string "/stable/" "/stable/pdfplus/" *doi-utils-redirect*) ".pdf")))
175 (defun aip-pdf-url (*doi-utils-redirect*)
176 (when (string-match "^http://scitation.aip.org" *doi-utils-redirect*)
177 ;; get stuff after content
179 (setq p2 (replace-regexp-in-string "^http://scitation.aip.org/" "" *doi-utils-redirect*))
180 (setq s (split-string p2 "/"))
181 (setq p1 (mapconcat 'identity (-remove-at-indices '(0 6) s) "/"))
182 (setq p3 (concat "/" (nth 0 s) (nth 1 s) "/" (nth 2 s) "/" (nth 3 s)))
183 (format "http://scitation.aip.org/deliver/fulltext/%s.pdf?itemId=/%s&mimeType=pdf&containerItemId=%s"
186 ;; ** Taylor and Francis
188 (defun tandfonline-pdf-url (*doi-utils-redirect*)
189 (when (string-match "^http://www.tandfonline.com" *doi-utils-redirect*)
190 (replace-regexp-in-string "/abs/\\|/full/" "/pdf/" *doi-utils-redirect*)))
194 (defun ecs-pdf-url (*doi-utils-redirect*)
195 (when (string-match "^http://jes.ecsdl.org" *doi-utils-redirect*)
196 (replace-regexp-in-string "\.abstract$" ".full.pdf" *doi-utils-redirect*)))
198 ;; http://ecst.ecsdl.org/content/25/2/2769
199 ;; http://ecst.ecsdl.org/content/25/2/2769.full.pdf
202 (defun ecst-pdf-url (*doi-utils-redirect*)
203 (when (string-match "^http://ecst.ecsdl.org" *doi-utils-redirect*)
204 (concat *doi-utils-redirect* ".full.pdf")))
210 (defun rsc-pdf-url (*doi-utils-redirect*)
211 (when (string-match "^http://pubs.rsc.org" *doi-utils-redirect*)
212 (let ((url (downcase *doi-utils-redirect*)))
213 (setq url (replace-regexp-in-string "articlelanding" "articlepdf" url))
216 ;; ** Elsevier/ScienceDirect
217 ;; You cannot compute these pdf links; they are embedded in the redirected pages.
219 (defvar *doi-utils-pdf-url* nil
220 "stores url to pdf download from a callback function")
222 (defun doi-utils-get-science-direct-pdf-url (redirect-url)
223 "science direct hides the pdf url in html. we get it out here"
224 (setq *doi-utils-waiting* t)
225 (url-retrieve redirect-url
227 (beginning-of-buffer)
228 (re-search-forward "pdfurl=\"\\([^\"]*\\)\"" nil t)
229 (setq *doi-utils-pdf-url* (match-string 1)
230 ,*doi-utils-waiting* nil)))
231 (while *doi-utils-waiting* (sleep-for 0.1))
235 (defun science-direct-pdf-url (*doi-utils-redirect*)
236 (when (string-match "^http://www.sciencedirect.com" *doi-utils-redirect*)
237 (doi-utils-get-science-direct-pdf-url *doi-utils-redirect*)
238 *doi-utils-pdf-url*))
241 ;; http://linkinghub.elsevier.com/retrieve/pii/S0927025609004558
242 ;; which actually redirect to
243 ;; http://www.sciencedirect.com/science/article/pii/S0927025609004558
244 (defun linkinghub-elsevier-pdf-url (*doi-utils-redirect*)
245 (when (string-match "^http://linkinghub.elsevier.com/retrieve" *doi-utils-redirect*)
246 (let ((second-redirect (replace-regexp-in-string
247 "http://linkinghub.elsevier.com/retrieve"
248 "http://www.sciencedirect.com/science/article"
249 ,*doi-utils-redirect*)))
250 (message "getting pdf url from %s" second-redirect)
251 *doi-utils-pdf-url*)))
254 ;; http://www.pnas.org/content/early/2014/05/08/1319030111
255 ;; http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf
257 ;; with supporting info
258 ;; http://www.pnas.org/content/early/2014/05/08/1319030111.full.pdf+html?with-ds=yes
260 (defun pnas-pdf-url (*doi-utils-redirect*)
261 (when (string-match "^http://www.pnas.org" *doi-utils-redirect*)
262 (concat *doi-utils-redirect* ".full.pdf?with-ds=yes")))
265 ;; ** Add all functions
267 (setq doi-utils-pdf-url-functions
278 'science-direct-pdf-url
279 'linkinghub-elsevier-pdf-url
286 ;; ** Get the pdf url for a doi
288 (defun doi-utils-get-pdf-url (doi)
289 "returns a url to a pdf for the doi if one can be
290 calculated. Loops through the functions in `doi-utils-pdf-url-functions'
292 (doi-utils-get-redirect doi)
294 (unless *doi-utils-redirect*
295 (error "No redirect found for %s" doi))
296 (message "applying functions")
298 (dolist (func doi-utils-pdf-url-functions)
299 (message "calling %s" func)
300 (let ((this-pdf-url (funcall func *doi-utils-redirect*)))
301 (message "t: %s" this-pdf-url)
303 (message "found pdf url: %s" this-pdf-url)
304 (throw 'pdf-url this-pdf-url))))))
306 ;; ** Finally, download the pdf
308 (defun doi-utils-get-bibtex-entry-pdf ()
309 "download pdf for entry at point if the pdf does not already
310 exist locally. The entry must have a doi. The pdf will be saved
311 to `org-ref-pdf-directory', by the name %s.pdf where %s is the
312 bibtex label. Files will not be overwritten. The pdf will be
313 checked to make sure it is a pdf, and not some html failure
314 page. you must have permission to access the pdf. We open the pdf
318 (bibtex-beginning-of-entry)
319 (let (;; get doi, removing http://dx.doi.org/ if it is there.
320 (doi (replace-regexp-in-string
321 "http://dx.doi.org/" ""
322 (bibtex-autokey-get-field "doi")))
327 ;; get the key and build pdf filename.
328 (re-search-forward bibtex-entry-maybe-empty-head)
329 (setq key (match-string bibtex-key-in-head))
330 (setq pdf-file (concat org-ref-pdf-directory key ".pdf"))
332 ;; now get file if needed.
333 (when (and doi (not (file-exists-p pdf-file)))
334 (setq pdf-url (doi-utils-get-pdf-url doi))
337 (url-copy-file pdf-url pdf-file)
338 ;; now check if we got a pdf
340 (insert-file-contents pdf-file)
341 ;; PDFS start with %PDF-1.x as the first few characters.
342 (if (not (string= (buffer-substring 1 6) "%PDF-"))
344 (message "%s" (buffer-string))
345 (delete-file pdf-file))
346 (message "%s saved" pdf-file)))
348 (when (file-exists-p pdf-file)
349 (org-open-file pdf-file)))
350 (message "No pdf-url found for %s at %s" doi *doi-utils-redirect* ))
353 ;; * Getting bibtex entries from a DOI
355 ;; I [[http://homepages.see.leeds.ac.uk/~eeaol/notes/2013/02/doi-metadata/][found]] you can download metadata about a DOI from http://dx.doi.org. You just have to construct the right http request to get it. Here is a function that gets the metadata as a plist in emacs.
357 (defun doi-utils-get-json-metadata (doi)
358 "Try to get json metadata for DOI. Open the DOI in a browser if we do not get it."
359 (let ((url-request-method "GET")
360 (url-mime-accept-string "application/citeproc+json")
361 (json-object-type 'plist)
364 (url-retrieve-synchronously
365 (concat "http://dx.doi.org/" doi))
366 (setq json-data (buffer-substring url-http-end-of-headers (point-max)))
367 (if (string-match "Resource not found" json-data)
369 (browse-url (concat "http://dx.doi.org/" doi))
370 (error "Resource not found. Opening website."))
371 (json-read-from-string json-data)))))
373 ;; We can use that data to construct a bibtex entry. We do that by defining a template, and filling it in. I wrote this template expansion code which makes it easy to substitute values like %{} in emacs lisp.
376 (defun doi-utils-expand-template (s)
377 "expand a template containing %{} with the eval of its contents"
378 (replace-regexp-in-string "%{\\([^}]+\\)}"
380 (let ((sexp (substring arg 2 -1)))
381 (format "%s" (eval (read sexp))))) s))
384 ;; Now we define a function that fills in that template from the metadata.
386 ;; As different bibtex types share common keys, it is advantageous to separate data extraction from json, and the formatting of the bibtex entry.
389 (setq doi-utils-json-metadata-extract
390 '((type (plist-get results :type))
391 (author (mapconcat (lambda (x) (concat (plist-get x :given) " " (plist-get x :family)))
392 (plist-get results :author) " and "))
393 (title (plist-get results :title))
394 (subtitle (plist-get results :subtitle))
395 (journal (plist-get results :container-title))
396 (series (plist-get results :container-title))
397 (publisher (plist-get results :publisher))
398 (volume (plist-get results :volume))
399 (issue (plist-get results :issue))
400 (number (plist-get results :issue))
401 (year (elt (elt (plist-get (plist-get results :issued) :date-parts) 0) 0))
402 (month (elt (elt (plist-get (plist-get results :issued) :date-parts) 0) 1))
403 (pages (plist-get results :page))
404 (doi (plist-get results :DOI))
405 (url (plist-get results :URL))
406 (booktitle (plist-get results :container-title))))
408 ;; Next, we need to define the different bibtex types. Each type has a bibtex type (for output) and the type as provided in the doi record. Finally, we have to declare the fields we want to output.
410 (setq doi-utils-bibtex-type-generators nil)
412 (defun doi-utils-concat-prepare (lst &optional acc)
413 "Given a list `lst' of strings and other expressions, which are
414 intented to passed to `concat', concat any subsequent strings,
415 minimising the number of arguments being passed to `concat'
416 without changing the results."
417 (cond ((null lst) (nreverse acc))
418 ((and (stringp (car lst))
420 (doi-utils-concat-prepare (cdr lst) (cons (concat (car acc) (car lst))
422 (t (doi-utils-concat-prepare (cdr lst) (cons (car lst) acc)))))
424 (defmacro doi-utils-def-bibtex-type (name matching-types &rest fields)
425 "Define a BibTeX type identified by (symbol) `name' with
426 `fields' (given as symbols), matching to retrieval expressions in
427 `doi-utils-json-metadata-extract'. This type will only be used
428 when the `:type' parameter in the JSON metadata is contained in
429 `matching-types' - a list of strings."
430 `(push (lambda (type results)
431 (when (or ,@(mapcar (lambda (match-type) `(string= type ,match-type)) matching-types))
432 (let ,(mapcar (lambda (field)
433 (let ((field-expr (assoc field doi-utils-json-metadata-extract)))
435 ;; need to convert to string first
436 `(,(car field-expr) (format "%s" ,(cadr field-expr)))
437 (error "unknown bibtex field type %s" field))))
440 ,@(doi-utils-concat-prepare
442 (list (concat "@" (symbol-name name) "{,\n")
443 ;; there seems to be some bug with mapcan,
444 ;; so we fall back to flatten
445 (mapcar (lambda (field)
446 `(" " ,(symbol-name field) " = {" ,field "},\n"))
449 doi-utils-bibtex-type-generators))
451 (doi-utils-def-bibtex-type article ("journal-article" "article-journal")
452 author title journal year volume number pages doi url)
454 (doi-utils-def-bibtex-type inproceedings ("proceedings-article")
455 author title booktitle year month pages doi url)
457 (doi-utils-def-bibtex-type book ("book")
458 author title series publisher year pages doi url)
460 (doi-utils-def-bibtex-type inbook ("book-chapter")
461 author title booktitle series publisher year pages doi url)
465 ;; With the code generating the bibtex entry in place, we can glue it to the json retrieval code.
467 (defun doi-utils-doi-to-bibtex-string (doi)
468 "return a bibtex entry as a string for the doi. Not all types are supported yet."
469 (let* ((results (doi-utils-get-json-metadata doi))
470 (type (plist-get results :type)))
471 ;(format "%s" results) ; json-data
472 (or (some (lambda (g) (funcall g type results)) doi-utils-bibtex-type-generators)
473 (message "%s not supported yet\n%S." type results))))
475 ;; That is just the string for the entry. To be useful, we need a function that inserts the string into a buffer. This function will insert the string at the cursor, clean the entry, try to get the pdf, and create a notes entry for you.
478 (defun doi-utils-insert-bibtex-entry-from-doi (doi)
479 "insert bibtex entry from a doi. Also cleans entry using
480 org-ref, and tries to download the corresponding pdf."
481 (interactive "sDOI :")
482 (insert (doi-utils-doi-to-bibtex-string doi))
484 ;; set date added for the record
485 (bibtex-set-field "DATE_ADDED" (current-time-string))
486 (if (bibtex-key-in-head nil)
487 (org-ref-clean-bibtex-entry t)
488 (org-ref-clean-bibtex-entry))
490 (doi-utils-get-bibtex-entry-pdf)
491 (save-selected-window
492 (org-ref-open-bibtex-notes)))
495 ;; It may be you are in some other place when you want to add a bibtex entry. This next function will open the first entry in org-ref-default-bibliography go to the end, and add the entry. You can sort it later.
498 (defun doi-utils-add-bibtex-entry-from-doi (doi bibfile)
499 "Add entry to end of a file in in the current directory ending
500 with .bib or in `org-ref-default-bibliography'. If you have an
501 active region that starts like a DOI, that will be the initial
502 prompt. If no region is selected and the first entry of the
503 kill-ring starts like a DOI, then that is the intial
504 prompt. Otherwise, you have to type or pste in a DOI."
506 (list (read-input "DOI: "
507 ;; now set initial input
509 ;; If region is active and it starts like a doi we want it.
510 ((and (region-active-p)
511 (s-match "^10" (buffer-substring
514 (buffer-substring (region-beginning) (region-end)))
515 ;; if the first entry in the kill-ring looks
516 ;; like a DOI, let's use it.
517 ((if (s-match "^10" (car kill-ring))
519 ;; otherwise, we have no initial input. You
520 ;; will have to type it in.
523 ;; now get the bibfile to add it to
526 (append (f-entries "." (lambda (f) (f-ext? f "bib")))
527 org-ref-default-bibliography))))
528 ;; Wrap in save-window-excursion to restore your window arrangement after this
530 (save-window-excursion
532 ;; Check if the doi already exists
533 (goto-char (point-min))
534 (if (search-forward doi nil t)
535 (message "%s is already in this file" doi)
538 (doi-utils-insert-bibtex-entry-from-doi doi)
542 ;; * Updating bibtex entries
543 ;; I wrote this code because it is pretty common for me to copy bibtex entries from ASAP articles that are incomplete, e.g. no page numbers because it is not in print yet. I wanted a convenient way to update an entry from its DOI. Basically, we get the metadata, and update the fields in the entry.
545 ;; There is not bibtex set field function, so I wrote this one.
548 (defun bibtex-set-field (field value &optional nodelim)
549 "set field to value in bibtex file. create field if it does not exist"
550 (interactive "sfield: \nsvalue: ")
551 (bibtex-beginning-of-entry)
553 (if (setq found (bibtex-search-forward-field field t))
556 (goto-char (car (cdr found)))
559 (bibtex-make-field field nil nil nodelim)
563 (message "new field being made")
564 (bibtex-beginning-of-entry)
565 (forward-line) (beginning-of-line)
566 (bibtex-next-field nil)
568 (bibtex-make-field field nil nil nodelim)
573 ;; The updating function for a whole entry looks like this. We get all the keys from the json plist metadata, and update the fields if they exist.
576 (defun plist-get-keys (plist)
577 "return keys in a plist"
579 for key in results by #'cddr collect key))
581 (defun doi-utils-update-bibtex-entry-from-doi (doi)
582 "update fields in a bibtex entry from the doi. Every field will be updated, so previous changes will be lost."
584 (or (replace-regexp-in-string "http://dx.doi.org/" "" (bibtex-autokey-get-field "doi"))
585 (read-string "DOI: "))))
586 (let* ((results (doi-utils-get-json-metadata doi))
587 (type (plist-get results :type))
589 (lambda (x) (concat (plist-get x :given)
590 " " (plist-get x :family)))
591 (plist-get results :author) " and "))
592 (title (plist-get results :title))
593 (journal (plist-get results :container-title))
598 (plist-get results :issued) :date-parts) 0) 0)))
599 (volume (plist-get results :volume))
600 (number (or (plist-get results :issue) ""))
601 (pages (or (plist-get results :page) ""))
602 (url (or (plist-get results :URL) ""))
603 (doi (plist-get results :DOI)))
605 ;; map the json fields to bibtex fields. The code each field is mapped to is evaluated.
606 (setq mapping '((:author . (bibtex-set-field "author" author))
607 (:title . (bibtex-set-field "title" title))
608 (:container-title . (bibtex-set-field "journal" journal))
609 (:issued . (bibtex-set-field "year" year))
610 (:volume . (bibtex-set-field "volume" volume))
611 (:issue . (bibtex-set-field "number" number))
612 (:page . (bibtex-set-field "pages" pages))
613 (:DOI . (bibtex-set-field "doi" doi))
614 (:URL . (bibtex-set-field "url" url))))
616 ;; now we have code to run for each entry. we map over them and evaluate the code
619 (eval (cdr (assoc key mapping))))
620 (plist-get-keys results)))
622 ; reclean entry, but keep key if it exists.
623 (if (bibtex-key-in-head)
624 (org-ref-clean-bibtex-entry t)
625 (org-ref-clean-bibtex-entry)))
628 ;; A downside to updating an entry is it overwrites what you have already fixed. So, we next develop a function to update the field at point.
631 (defun doi-utils-update-field ()
633 (let* ((doi (bibtex-autokey-get-field "doi"))
634 (results (doi-utils-get-json-metadata doi))
635 (field (car (bibtex-find-text-internal nil nil ","))))
637 ((string= field "volume")
638 (bibtex-set-field field (plist-get results :volume)))
639 ((string= field "number")
640 (bibtex-set-field field (plist-get results :issue)))
641 ((string= field "pages")
642 (bibtex-set-field field (plist-get results :page)))
643 ((string= field "year")
644 (bibtex-set-field field (plist-get results :year)))
646 (message "%s not supported yet." field)))))
650 ;; * DOI functions for WOS
651 ;; I came across this API http://wokinfo.com/media/pdf/OpenURL-guide.pdf to make links to the things I am interested in here. Based on that document, here are three links based on a doi:10.1021/jp047349j that take you to different Web Of Science (WOS) pages.
654 ;; 1. go to article in WOS: http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info:doi/10.1021/jp047349j
655 ;; 2. citing articles: http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F10.1021/jp047349j&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.citing=yes
656 ;; 3. related articles: http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F10.1021/jp047349j&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.related=yes
658 ;; These are pretty easy to construct, so we can write functions that will create them and open the url in our browser. There are some other options that could be considered, but since we usually have a doi, it seems like the best way to go for creating the links. Here are the functions.
660 (defun doi-utils-wos (doi)
661 "Open Web of Science entry for DOI"
662 (interactive "sDOI: ")
665 "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info:doi/%s" doi)))
667 (defun doi-utils-wos-citing (doi)
668 "Open Web of Science citing articles entry. May be empty if none are found"
669 (interactive "sDOI: ")
672 "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
674 "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.citing=yes")))
676 (defun doi-utils-wos-related (doi)
677 "Open Web of Science related articles page."
678 (interactive "sDOI: ")
680 (concat "http://ws.isiknowledge.com/cps/openurl/service?url_ver=Z39.88-2004&rft_id=info%3Adoi%2F"
682 "&svc_val_fmt=info%3Aofi%2Ffmt%3Akev%3Amtx%3Asch_svc&svc.related=yes")))
687 ;; * A new doi link for org-mode
688 ;; The idea is to add a menu to the doi link, so rather than just clicking to open the article, you can do other things.
691 ;; 3. open citing articles
692 ;; 4. open related articles
693 ;; 5. open bibtex entry
694 ;; 6. get bibtex entry
697 (defun doi-utils-open (doi)
698 (interactive "sDOI: ")
699 (browse-url (concat "http://dx.doi.org/" doi)))
702 (defun doi-utils-open-bibtex (doi)
703 "Search through `reftex-default-bibliography' for DOI."
704 (interactive "sDOI: ")
706 (dolist (f reftex-default-bibliography)
708 (when (search-forward doi (point-max) t)
709 (bibtex-beginning-of-entry)
713 (defun doi-utils-crossref (doi)
714 "Search DOI in CrossRef."
715 (interactive "sDOI: ")
718 "http://search.crossref.org/?q=%s" doi)))
721 (defun doi-utils-google-scholar (doi)
722 "Google scholar the word at point or selection."
723 (interactive "sDOI: ")
726 "http://scholar.google.com/scholar?q=%s" doi)))
729 (defun doi-utils-pubmed (doi)
730 "Pubmed the word at point or selection."
731 (interactive "sDOI: ")
734 "http://www.ncbi.nlm.nih.gov/pubmed/?term=%s"
735 (url-hexify-string doi))))
738 (defvar doi-link-menu-funcs '()
739 "Functions to run in doi menu. Each entry is a list of (key menu-name function).
740 The function must take one argument, the doi.")
742 (setq doi-link-menu-funcs
743 '(("o" "pen" doi-utils-open)
744 ("w" "os" doi-utils-wos)
745 ("c" "iting articles" doi-utils-wos-citing)
746 ("r" "elated articles" doi-utils-wos-related)
747 ("s" "Google Scholar" doi-utils-google-scholar)
748 ("f" "CrossRef" doi-utils-crossref)
749 ("p" "ubmed" doi-utils-pubmed)
750 ("b" "open in bibtex" doi-utils-open-bibtex)
751 ("g" "et bibtex entry" doi-utils-add-bibtex-entry-from-doi)))
754 (defun doi-link-menu (link-string)
755 "Generate the link menu message, get choice and execute it.
756 Options are stored in `doi-link-menu-funcs'."
762 (concat "[" (elt tup 0) "]"
764 doi-link-menu-funcs "") ": "))
765 (let* ((input (read-char-exclusive))
767 (char-to-string input) doi-link-menu-funcs)))
780 ;; * Getting a doi for a bibtex entry missing one
781 ;; Some bibtex entries do not have a DOI, maybe because they were entered by hand, or copied from a source that did not have it available. Here we develop some functions to help you find the DOI using Crossref.
783 ;; Here is our example bibtex entry.
784 ;; #+BEGIN_SRC bibtex
785 ;; @article{deml-2014-oxide,
786 ;; author = {Ann M. Deml and Vladan Stevanovi{\'c} and
787 ;; Christopher L. Muhich and Charles B. Musgrave and
789 ;; title = {Oxide Enthalpy of Formation and Band Gap Energy As
790 ;; Accurate Descriptors of Oxygen Vacancy Formation
792 ;; journal = {Energy Environ. Sci.},
797 ;; doi = {10.1039/c3ee43874k,
798 ;; url = {http://dx.doi.org/10.1039/c3ee43874k}},
803 ;; The idea is to query Crossref in a way that is likely to give us a hit relevant to the entry.
805 ;; According to http://search.crossref.org/help/api we can send a query with a free form citation that may give us something back. We do this to get a list of candidates, and run a helm command to get the doi.
809 (defun doi-utils-crossref-citation-query ()
810 "Query Crossref with the title of the bibtex entry at point to
811 get a list of possible matches. This opens a helm buffer to
812 select an entry. The default action inserts a doi and url field
813 in the bibtex entry at point. The second action opens the doi
814 url. If there is already a doi field, the function raises an
817 (bibtex-beginning-of-entry)
818 (let* ((entry (bibtex-parse-entry))
822 (unless (string= ""(reftex-get-bib-field "doi" entry))
823 (error "Entry already has a doi field"))
826 (url-retrieve-synchronously
828 "http://search.crossref.org/dois?q="
829 (url-hexify-string (org-ref-bib-citation))))
830 (setq json-string (buffer-substring url-http-end-of-headers (point-max)))
831 (setq json-data (json-read-from-string json-string)))
833 (let* ((name (format "Crossref hits for %s" (org-ref-bib-citation)))
834 (helm-candidates (mapcar (lambda (x)
837 (cdr (assoc 'fullCitation x))
839 (cdr (assoc 'doi x)))
840 (cdr (assoc 'doi x))))
842 (source `((name . ,name)
843 (candidates . ,helm-candidates)
844 ;; just return the candidate
845 (action . (("Insert doi and url field" . (lambda (doi)
846 (bibtex-make-field "doi")
848 ;; crossref returns doi url, but I prefer only a doi for the doi field
849 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi))
850 (when (string= ""(reftex-get-bib-field "url" entry))
851 (bibtex-make-field "url")
854 ("Open url" . (lambda (doi)
855 (browse-url doi))))))))
856 (helm :sources '(source)))))
861 ;; I wrote this function to help debug a DOI. This function generates an org-buffer with the doi, gets the json metadata, shows the bibtex entry, and the pdf link for it.
863 (defun doi-utils-debug (doi)
864 "Generate an org-buffer showing data about DOI."
865 (interactive "sDOI: ")
866 (switch-to-buffer "*debug-doi*")
869 (insert (concat "doi:" doi) "\n\n")
871 " (format "%s" (doi-utils-get-json-metadata doi)) "
875 " (doi-utils-doi-to-bibtex-string doi) "
878 " (doi-utils-get-pdf-url doi)))
880 ;; * Adding a bibtex entry from a crossref query
881 ;; The idea here is to perform a query on Crossref, get a helm buffer of candidates, and select the entry(ies) you want to add to your bibtex file. You can select a region, e.g. a free form citation, or set of words, or you can type the query in by hand.
883 (defun doi-utils-add-entry-from-crossref-query (query bibtex-file)
887 ;; now set initial input
889 ;; If region is active assume we want it
891 (replace-regexp-in-string
893 (buffer-substring (region-beginning) (region-end))))
894 ;; type or paste it in
899 (append (f-entries "." (lambda (f) (f-ext? f "bib")))
900 org-ref-default-bibliography))))
906 (url-retrieve-synchronously
908 "http://search.crossref.org/dois?q="
909 (url-hexify-string query)))
910 (setq json-string (buffer-substring url-http-end-of-headers (point-max)))
911 (setq json-data (json-read-from-string json-string)))
913 (let* ((name (format "Crossref hits for %s"
914 ;; remove carriage returns. they cause problems in helm.
915 (replace-regexp-in-string "\n" " " query)))
916 (helm-candidates (mapcar (lambda (x)
919 (cdr (assoc 'fullCitation x))
921 (cdr (assoc 'doi x)))
922 (cdr (assoc 'doi x))))
924 (source `((name . ,name)
925 (candidates . ,helm-candidates)
926 ;; just return the candidate
927 (action . (("Insert bibtex entry" . (lambda (doi)
928 (doi-utils-add-bibtex-entry-from-doi
929 (replace-regexp-in-string "^http://dx.doi.org/" "" doi) ,bibtex-file)))
930 ("Open url" . (lambda (doi)
931 (browse-url doi))))))))
932 (helm :sources '(source)))))
936 ;;; doi-utils.el ends here