]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.org
fix bug where clicking on cite: gives an error
[org-ref.git] / org-ref.org
1 #+TITLE: Org-ref - The best reference handling for org-mode
2 #+AUTHOR: John Kitchin
3 #+DATE: April 29, 2014
4
5 * Introduction
6
7 This document is an experiment at creating a literate program to provide similar features as reftex for org-mode referencing. These features include:
8
9 1. using completion to create links
10 2. storing links to places, 
11 3. Clickable links that do useful things
12 4. Exportable links to LaTeX
13 5. Utility functions for dealing with bibtex files and org-files
14
15 ** Header
16 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
17 ;;; org-ref.el --- setup bibliography, cite, ref and label org-mode links.
18
19 ;; Copyright(C) 2014 John Kitchin
20
21 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
22 ;; This file is not currently part of GNU Emacs.
23
24 ;; This program is free software; you can redistribute it and/or
25 ;; modify it under the terms of the GNU General Public License as
26 ;; published by the Free Software Foundation; either version 2, or (at
27 ;; your option) any later version.
28
29 ;; This program is distributed in the hope that it will be useful, but
30 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
31 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
32 ;; General Public License for more details.
33
34 ;; You should have received a copy of the GNU General Public License
35 ;; along with this program ; see the file COPYING.  If not, write to
36 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
37 ;; Boston, MA 02111-1307, USA.
38
39 ;;; Commentary:
40 ;;
41 ;; Lisp code to setup bibliography cite, ref and label org-mode links.
42 ;; also sets up reftex for org-mode. The links are clickable and do
43 ;; things that are useful. You should really read org-ref.org for details.
44 ;;
45 ;; Package-Requires: ((dash))
46 #+END_SRC
47
48 ** requires
49 The only external require is reftex-cite
50
51 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
52 (require 'reftex-cite)
53 (require 'dash)
54 #+END_SRC
55
56 ** Custom variables
57 There are some variables needed later to tell this library where you store your pdf files, where your notes file is, and your default bibliography. This variable is similar to the reftex-default-bibliography. I do not remember why I made it separate.
58
59 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
60 (defgroup org-ref nil
61   "customization group for org-ref")
62
63 (defcustom org-ref-bibliography-notes
64   nil
65   "filename to where you will put all your notes about an entry in
66   the default bibliography."
67   :type 'file
68   :group 'org-ref)
69
70 (defcustom org-ref-default-bibliography
71   nil
72   "list of bibtex files to search for. You should use full-paths for each file."
73   :type '(repeat :tag "List of bibtex files" file)
74   :group 'org-ref)
75
76 (defcustom org-ref-pdf-directory
77   nil
78   "directory where pdfs are stored by key. put a trailing / in"
79   :type 'directory
80   :group 'org-ref)
81
82 (defcustom org-ref-default-citation-link
83   "cite"
84   "The default type of citation link to use"
85   :type 'string
86   :group 'org-ref)
87
88 (defcustom org-ref-insert-cite-key
89   "C-c ]"
90   "Keyboard shortcut to insert a citation."
91   :type 'string
92   :group 'org-ref)
93
94 (defcustom org-ref-bibliography-entry-format
95   '(("article" . "%a, %t, <i>%j</i>, <b>%v(%n)</b>, %p (%y). <a href=\"%U\">link</a>. <a href=\"http://dx.doi.org/%D\">doi</a>.")
96
97     ("book" . "%a, %t, %u (%y).")
98
99     ("proceedings" . "%e, %t in %S, %u (%y).")
100
101     ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
102
103   "string to format an entry. Just the reference, no numbering at the beginning, etc... see the `org-ref-reftex-format-citation' docstring for the escape codes."
104   :type 'string
105   :group 'org-ref)
106 #+END_SRC
107
108 This next variable determines the citation types that are available in org-ref. Links for each one are automatically generated, and completion functions are automatically generated. Users may add to this list in their own init files.
109
110 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
111 (defcustom org-ref-cite-types
112   '("cite" "nocite" ;; the default latex cite commands
113     ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
114     "citet" "citet*" "citep" "citep*"
115     "citealt" "citealt*" "citealp" "citealp*"
116     "citenum" "citetext"
117     "citeauthor" "citeauthor*"
118     "citeyear" "citeyear*"
119     "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
120     ;; biblatex commands
121     ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
122     "Cite"
123     "parencite" "Parencite"
124     "footcite" "footcitetext"
125     "textcite" "Textcite"
126     "smartcite" "Smartcite"
127     "cite*" "parencite*" "supercite"
128     "autocite" "Autocite" "autocite*" "Autocite*"
129     "Citeauthor*"
130     "citetitle" "citetitle*"
131     "citedate" "citedate*"
132     "citeurl"
133     "fullcite" "footfullcite"
134     ;; "volcite" "Volcite" cannot support the syntax
135     "notecite" "Notecite"
136     "pnotecite" "Pnotecite"
137     "fnotecite"
138     ;; multicites. Very limited support for these.
139     "cites" "Cites" "parencites" "Parencites"
140     "footcites" "footcitetexts"
141     "smartcites" "Smartcites" "textcites" "Textcites"
142     "supercites" "autocites" "Autocites"
143     )
144   "List of citation types known in org-ref"
145   :type '(repeat :tag "List of citation types" string)
146   :group 'org-ref)
147 #+END_SRC
148
149 We need a hook variable to store user-defined bibtex entry cleaning functions
150 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
151 (defcustom org-ref-clean-bibtex-entry-hook nil
152   "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
153   :group 'org-ref
154   :type 'hook)
155 #+END_SRC
156
157 ** Program variables
158 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
159 (defvar org-ref-bibliography-files
160   nil
161   "variable to hold bibliography files to be searched")
162 #+END_SRC
163
164 ** org-mode / reftex setup
165
166 We setup reftex here. We use a custom insert cite link function defined here: [[*org-ref-insert-cite-link][org-ref-insert-cite-link]]. We setup reftex to use our org citation format.
167
168 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
169 (defun org-mode-reftex-setup ()
170     (load-library "reftex")
171     (and (buffer-file-name)
172          (file-exists-p (buffer-file-name))
173          (global-auto-revert-mode t)
174          (reftex-parse-all))
175     (make-local-variable 'reftex-cite-format)
176     (setq reftex-cite-format 'org)
177     (define-key org-mode-map (kbd org-ref-insert-cite-key) 'org-ref-insert-cite-link))
178
179 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
180
181 (eval-after-load 'reftex-vars
182   '(progn
183       (add-to-list 'reftex-cite-format-builtin
184                    '(org "Org-mode citation"
185                          ((?\C-m . "cite:%l")     ; default
186                           (?d . ",%l")            ; for appending
187                           (?a . "autocite:%l")
188                           (?t . "citet:%l")
189                           (?T . "citet*:%l")
190                           (?p . "citep:%l")
191                           (?P . "citep*:%l")
192                           (?h . "citeauthor:%l")
193                           (?H . "citeauthor*:%l")
194                           (?y . "citeyear:%l")
195                           (?x . "citetext:%l")
196                           (?n . "nocite:%l")
197                           )))))
198 #+END_SRC
199
200 You may want to add new formats to the reftex-cite-format-builtin variable. Here is an example of adding two new formats. Note that this does not create the links. 
201
202 #+BEGIN_SRC emacs-lisp :tangle no
203 ;; add new format
204 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
205       (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W  . "textcite:%l")
206             (?z  . "newcite:%l"))))
207 #+END_SRC
208
209 You can define a new citation link like this:
210 #+BEGIN_SRC emacs-lisp :tangle no
211 (org-ref-define-citation-link "citez" ?z)
212 #+END_SRC
213
214 * Links
215 Most of this library is the creation of functional links to help with references and citations.
216 ** General utilities
217 We need several general utilities for this module. They are organized here. We frequently need to remove white space from the front and back of a string. Here we do that for a string.
218
219 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
220 (defun org-ref-strip-string (string)
221   "strip leading and trailing whitespace from the string"
222   (replace-regexp-in-string
223    (concat search-whitespace-regexp "$" ) ""
224    (replace-regexp-in-string
225     (concat "^" search-whitespace-regexp ) "" string)))
226 #+END_SRC
227
228 It is helpful to make the previous function operate on a list of strings here.
229
230 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
231 (defun org-ref-split-and-strip-string (string)
232   "split key-string and strip keys. Assumes the key-string is comma delimited"
233   (mapcar 'org-ref-strip-string (split-string string ",")))
234 #+END_SRC
235
236 ** bibliography and bibliographystyle
237 *** An html bibliography
238
239 Reftex is no longer being developed. I want a url and doi option for formatting, so I am modifying this [[file:emacs-24.3/lisp/textmodes/reftex-cite.el::(defun%20reftex-format-citation%20(entry%20format)][function]] from reftex-cite to provide that. We need to modify the reftex-get-bib-field code a bit to remove enclosing braces and quotes so we can make nice looking links.
240
241 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
242 (defun org-ref-reftex-get-bib-field (field entry &optional format)
243   "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
244   (let ((result))
245     (setq result (reftex-get-bib-field field entry format))
246     (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
247       (setq result (substring result 1 -1)))
248     (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
249       (setq result (substring result 1 -1)))    
250       result))
251
252 (defun org-ref-reftex-format-citation (entry format)
253   "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
254 to the format argument. The format is a string with these percent escapes.
255
256 In the format, the following percent escapes will be expanded.
257
258 %l   The BibTeX label of the citation.
259 %a   List of author names, see also `reftex-cite-punctuation'.
260 %2a  Like %a, but abbreviate more than 2 authors like Jones et al.
261 %A   First author name only.
262 %e   Works like %a, but on list of editor names. (%2e and %E work a well)
263
264 It is also possible to access all other BibTeX database fields:
265 %b booktitle     %c chapter        %d edition    %h howpublished
266 %i institution   %j journal        %k key        %m month
267 %n number        %o organization   %p pages      %P first page
268 %r address       %s school         %u publisher  %t title
269 %v volume        %y year
270 %B booktitle, abbreviated          %T title, abbreviated
271 %U url
272 %D doi
273 %S series
274
275 Usually, only %l is needed.  The other stuff is mainly for the echo area
276 display, and for (setq reftex-comment-citations t).
277
278 %< as a special operator kills punctuation and space around it after the
279 string has been formatted.
280
281 A pair of square brackets indicates an optional argument, and RefTeX
282 will prompt for the values of these arguments.
283
284 Beware that all this only works with BibTeX database files.  When
285 citations are made from the \bibitems in an explicit thebibliography
286 environment, only %l is available."
287   ;; Format a citation from the info in the BibTeX ENTRY
288
289   (unless (stringp format) (setq format "\\cite{%l}"))
290
291   (if (and reftex-comment-citations
292            (string-match "%l" reftex-cite-comment-format))
293       (error "reftex-cite-comment-format contains invalid %%l"))
294
295   (while (string-match
296           "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
297           format)
298     (let ((n (string-to-number (match-string 4 format)))
299           (l (string-to-char (match-string 5 format)))
300           rpl b e)
301       (save-match-data
302         (setq rpl
303               (cond
304                ((= l ?l) (concat
305                           (org-ref-reftex-get-bib-field "&key" entry)
306                           (if reftex-comment-citations
307                               reftex-cite-comment-format
308                             "")))
309                ((= l ?a) (reftex-format-names
310                           (reftex-get-bib-names "author" entry)
311                           (or n 2)))
312                ((= l ?A) (car (reftex-get-bib-names "author" entry)))
313                ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
314                ((= l ?B) (reftex-abbreviate-title
315                           (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
316                ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
317                ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
318                ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
319                ((= l ?e) (reftex-format-names
320                           (reftex-get-bib-names "editor" entry)
321                           (or n 2)))
322                ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
323                ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
324                ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
325                ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
326                ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
327                ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
328                ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
329                ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
330                ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
331                ((= l ?P) (car (split-string
332                                (org-ref-reftex-get-bib-field "pages" entry)
333                                "[- .]+")))
334                ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
335                ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
336                ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
337                ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
338                ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
339                ;; strip enclosing brackets from title if they are there
340                ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
341                ((= l ?T) (reftex-abbreviate-title
342                           (org-ref-reftex-get-bib-field "title" entry)))
343                ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
344                ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
345
346       (if (string= rpl "")
347           (setq b (match-beginning 2) e (match-end 2))
348         (setq b (match-beginning 3) e (match-end 3)))
349       (setq format (concat (substring format 0 b) rpl (substring format e)))))
350   (while (string-match "%%" format)
351     (setq format (replace-match "%" t t format)))
352   (while (string-match "[ ,.;:]*%<" format)
353     (setq format (replace-match "" t t format)))
354   ;; also replace carriage returns, tabs, and multiple whitespaces
355   (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
356   format)
357
358 (defun org-ref-get-bibtex-entry-citation (key)
359   "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
360
361   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
362         (file) (entry) (bibtex-entry) (entry-type) (format))
363
364     (setq file (catch 'result
365                  (loop for file in org-ref-bibliography-files do
366                        (if (org-ref-key-in-file-p key (file-truename file)) 
367                            (throw 'result file)
368                          (message "%s not found in %s" key (file-truename file))))))
369
370     (with-temp-buffer
371       (insert-file-contents file)
372       (bibtex-search-entry key nil 0)
373       (setq bibtex-entry (bibtex-parse-entry))
374       (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
375       (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
376       (if format
377           (setq entry  (org-ref-reftex-format-citation bibtex-entry format))
378         (save-restriction
379           (bibtex-narrow-to-entry)
380           (setq entry (buffer-string)))))      
381     entry))
382 #+END_SRC
383
384 #+RESULTS:
385 : org-ref-reftex-format-citation
386
387 Here is how to use the function. You call it with point in an entry in a bibtex file.
388
389 #+BEGIN_SRC emacs-lisp :tangle no
390 (let((org-ref-bibliography-entry-format   "%a, %t, <i>%j</i>, <b>%v(%n)</b>, %p (%y). <a href=\"%U\">link</a>. <a href=\"http://dx.doi.org/%D\">doi</a>."))
391   (org-ref-get-bibtex-entry-citation  "armiento-2014-high"))
392 #+END_SRC
393 #+RESULTS:
394 : Armiento, Kozinsky, Hautier, , Fornari \& Ceder, High-throughput screening of perovskite alloys for  piezoelectric performance and thermodynamic  stability, <i>Phys. Rev. B</i>, <b>89()</b>, 134103 (2014). <a href="http://link.aps.org/doi/10.1103/PhysRevB.89.134103">link</a>. <a href="http://dx.doi.org/10.1103/PhysRevB.89.134103">doi</a>.
395
396 I am not sure why full author names are not used.
397
398 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
399
400 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
401 (defun org-ref-get-bibtex-keys ()
402   "return a list of unique keys in the buffer."
403   (let ((keys '()))
404     (org-element-map (org-element-parse-buffer) 'link
405       (lambda (link)       
406         (let ((plist (nth 1 link)))                          
407           (when (-contains? org-ref-cite-types (plist-get plist ':type))
408             (dolist 
409                 (key 
410                  (org-ref-split-and-strip-string (plist-get plist ':path)))
411               (when (not (-contains? keys key))
412                 (setq keys (append keys (list key)))))))))
413     ;; Sort keys alphabetically
414     (setq keys (cl-sort keys 'string-lessp :key 'downcase))
415     keys))
416 #+END_SRC
417
418 This function gets the html for one entry.
419
420 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
421 (defun org-ref-get-bibtex-entry-html (key)
422   "returns an html string for the bibliography entry corresponding to key"
423
424   (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
425 #+END_SRC
426
427 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
428
429 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
430 (defun org-ref-get-html-bibliography ()
431   "Create an html bibliography when there are keys"
432   (let ((keys (org-ref-get-bibtex-keys)))
433     (when keys
434       (concat "<h1>Bibliography</h1>
435 <ul>"
436               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
437               "\n</ul>"))))
438 #+END_SRC
439
440 I do not have plans to make a numbered bibliography with numbered citations anytime soon. This will require changing the way the citation links are exported, and keeping track of the numbers.
441
442 *** An org bibliography
443 You can export an org-file to an org-file or org-buffer (org-org-epxort-as-org). In this case, it would be useful convert the cite links to links to custom_ids, and the bibliography link to a first-level heading Bibliography with org-bibtex like headings for each entry. This code should enable this. Right now, it does not appear to work for org export though.
444
445 First, we get the string for a single entry.
446 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
447 (defun org-ref-get-bibtex-entry-org (key)
448   "returns an org string for the bibliography entry corresponding to key"
449   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
450         (file) (entry) (bibtex-entry) (entry-type) (format))
451
452     (setq file (catch 'result
453                  (loop for file in org-ref-bibliography-files do
454                        (if (org-ref-key-in-file-p key (file-truename file)) 
455                            (throw 'result file)
456                          (message "%s not found in %s" key (file-truename file))))))
457
458     (with-temp-buffer
459       (insert-file-contents file)
460       (bibtex-search-entry key nil 0)
461       (setq entry (bibtex-parse-entry))
462       (format "** %s - %s
463   :PROPERTIES:
464   %s
465   :END:
466 " (org-ref-reftex-get-bib-field "author" entry)
467 (org-ref-reftex-get-bib-field "title" entry)
468 (concat "   :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
469         (mapconcat (lambda (element) (format "   :%s: %s"
470                                              (upcase (car element))
471                                              (cdr element)))
472                    entry
473                    "\n"))))))
474 #+END_SRC
475
476 Now, we loop over the keys, and combine all the entries into a bibliography.
477 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
478 (defun org-ref-get-org-bibliography ()
479   "Create an org bibliography when there are keys"
480   (let ((keys (org-ref-get-bibtex-keys)))
481     (when keys
482       (concat "* Bibliography
483 "
484               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
485               "\n"))))
486 #+END_SRC
487
488 *** An ascii bibliography
489
490 This function gets the html for one entry.
491
492 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
493 (defun org-ref-get-bibtex-entry-ascii (key)
494   "returns an ascii string for the bibliography entry corresponding to key"
495
496   (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
497 #+END_SRC
498
499 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
500
501 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
502 (defun org-ref-get-ascii-bibliography ()
503   "Create an html bibliography when there are keys"
504   (let ((keys (org-ref-get-bibtex-keys)))
505     (when keys
506       (concat 
507 "Bibliography
508 =============
509 "
510               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
511               "\n"))))
512 #+END_SRC
513
514
515 *** the links
516 We use a link for the bibliography so that we can click on it to open the bibliography file. The link may have more than one bibliography file in it, separated by commas. Clicking opens the file under the cursor. The bibliographies should be full filenames with the bib extension. Clicking on this link makes reftex-default-bibliography local and sets it to the list of files in the link. We need this to use reftex's searching capability.
517
518 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
519 (org-add-link-type "bibliography"
520                    ;; this code is run on clicking. The bibliography
521                    ;; may contain multiple files. this code finds the
522                    ;; one you clicked on and opens it.
523                    (lambda (link-string)        
524                        ;; get link-string boundaries
525                        ;; we have to go to the beginning of the line, and then search forward
526                        
527                      (let* ((bibfile)
528                             ;; object is the link you clicked on
529                             (object (org-element-context))
530  
531                             (link-string-beginning) 
532                             (link-string-end))
533
534                      (save-excursion
535                        (goto-char (org-element-property :begin object))
536                        (search-forward link-string nil nil 1)
537                        (setq link-string-beginning (match-beginning 0))
538                        (setq link-string-end (match-end 0)))
539
540                        ;; We set the reftex-default-bibliography
541                        ;; here. it should be a local variable only in
542                        ;; the current buffer. We need this for using
543                        ;; reftex to do citations.
544                        (set (make-local-variable 'reftex-default-bibliography) 
545                             (split-string (org-element-property :path object) ","))
546
547                        ;; now if we have comma separated bibliographies
548                        ;; we find the one clicked on. we want to
549                        ;; search forward to next comma from point
550                        (save-excursion
551                          (if (search-forward "," link-string-end 1 1)
552                              (setq key-end (- (match-end 0) 1)) ; we found a match
553                            (setq key-end (point)))) ; no comma found so take the point
554                        ;; and backward to previous comma from point
555                        (save-excursion
556                          (if (search-backward "," link-string-beginning 1 1)
557                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
558                            (setq key-beginning (point)))) ; no match found
559                        ;; save the key we clicked on.
560                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
561                        (find-file bibfile))) ; open file on click
562
563                      ;; formatting code
564                    (lambda (keyword desc format)
565                      (cond
566                       ((eq format 'org) (org-ref-get-org-bibliography))
567                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
568                       ((eq format 'html) (org-ref-get-html-bibliography))
569                       ((eq format 'latex)
570                          ;; write out the latex bibliography command
571                        (format "\\bibliography{%s}" (replace-regexp-in-string  "\\.bib" "" (expand-file-name keyword)))))))
572 #+END_SRC
573
574 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
575 (org-add-link-type "printbibliography"
576                    (lambda (arg) (message "Nothing implemented for clicking here."))
577                    (lambda (keyword desc format)
578                      (cond
579                       ((eq format 'org) (org-ref-get-org-bibliography))
580                       ((eq format 'html) (org-ref-get-html-bibliography))
581                       ((eq format 'latex)
582                        ;; write out the biblatex bibliography command
583                        "\\printbibliography"))
584 ))
585 #+END_SRC
586
587 We also create a bibliographystyle link. There is nothing to do on clicking here, and we create it for consistency. This sets the style for latex export, so use something appropriate there, e.g. unsrt, plain, plainnat, ...
588
589 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
590 (org-add-link-type "bibliographystyle"
591                    (lambda (arg) (message "Nothing implemented for clicking here."))
592                    (lambda (keyword desc format)
593                      (cond
594                       ((eq format 'latex)
595                        ;; write out the latex bibliography command
596                        (format "\\bibliographystyle{%s}" keyword)))))
597 #+END_SRC
598
599 *** Completion for bibliography link
600 It would be nice 
601
602 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
603 (defun org-bibliography-complete-link (&optional arg)
604  (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
605
606 (defun org-ref-insert-bibliography-link ()
607   "insert a bibliography with completion"
608   (interactive)
609   (insert (org-bibliography-complete-link)))
610 #+END_SRC
611
612 ** addbibresource
613 This is apparently used for biblatex.
614 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
615 (org-add-link-type "addbibresource"
616                    ;; this code is run on clicking. The addbibresource
617                    ;; may contain multiple files. this code finds the
618                    ;; one you clicked on and opens it.
619                    (lambda (link-string)        
620                        ;; get link-string boundaries
621                        ;; we have to go to the beginning of the line, and then search forward
622                        
623                      (let* ((bibfile)
624                             ;; object is the link you clicked on
625                             (object (org-element-context))
626  
627                             (link-string-beginning) 
628                             (link-string-end))
629
630                      (save-excursion
631                        (goto-char (org-element-property :begin object))
632                        (search-forward link-string nil nil 1)
633                        (setq link-string-beginning (match-beginning 0))
634                        (setq link-string-end (match-end 0)))
635
636                        ;; We set the reftex-default-addbibresource
637                        ;; here. it should be a local variable only in
638                        ;; the current buffer. We need this for using
639                        ;; reftex to do citations.
640                        (set (make-local-variable 'reftex-default-addbibresource) 
641                             (split-string (org-element-property :path object) ","))
642
643                        ;; now if we have comma separated bibliographies
644                        ;; we find the one clicked on. we want to
645                        ;; search forward to next comma from point
646                        (save-excursion
647                          (if (search-forward "," link-string-end 1 1)
648                              (setq key-end (- (match-end 0) 1)) ; we found a match
649                            (setq key-end (point)))) ; no comma found so take the point
650                        ;; and backward to previous comma from point
651                        (save-excursion
652                          (if (search-backward "," link-string-beginning 1 1)
653                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
654                            (setq key-beginning (point)))) ; no match found
655                        ;; save the key we clicked on.
656                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
657                        (find-file bibfile))) ; open file on click
658
659                      ;; formatting code
660                    (lambda (keyword desc format)
661                      (cond
662                       ((eq format 'html) (format "")); no output for html
663                       ((eq format 'latex)
664                          ;; write out the latex addbibresource command
665                        (format "\\addbibresource{%s}" keyword)))))
666 #+END_SRC
667
668 ** List of Figures
669
670 In long documents, a list of figures is not uncommon. Here we create a clickable link that generates a temporary buffer containing a list of figures in the document, and their captions. We make a function that can be called interactively, and define a link type that is rendered in LaTeX to create the list of figures.
671
672 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
673 (defun org-ref-list-of-figures (&optional arg)
674   "Generate buffer with list of figures in them"
675   (interactive)
676   (save-excursion (widen)
677   (let* ((c-b (buffer-name))
678          (counter 0)
679          (list-of-figures 
680           (org-element-map (org-element-parse-buffer) 'link
681             (lambda (link) 
682               "create a link for to the figure"
683               (when 
684                   (and (string= (org-element-property :type link) "file")
685                        (string-match-p  
686                         "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
687                         (org-element-property :path link)))                   
688                 (incf counter)
689                 
690                 (let* ((start (org-element-property :begin link))
691                        (parent (car (cdr (org-element-property :parent link))))
692                        (caption (caaar (plist-get parent :caption)))
693                        (name (plist-get parent :name)))
694                   (if caption 
695                       (format 
696                        "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n" 
697                        c-b start counter (or name "") caption)
698                     (format 
699                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n" 
700                      c-b start counter (or name "")))))))))
701     (switch-to-buffer "*List of Figures*")
702     (setq buffer-read-only nil)
703     (org-mode)
704     (erase-buffer)
705     (insert (mapconcat 'identity list-of-figures ""))
706     (setq buffer-read-only t)
707     (use-local-map (copy-keymap org-mode-map))
708     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
709
710 (org-add-link-type 
711  "list-of-figures"
712  'org-ref-list-of-figures ; on click
713  (lambda (keyword desc format)
714    (cond
715     ((eq format 'latex)
716      (format "\\listoffigures")))))
717 #+END_SRC
718
719 ** List of Tables
720
721 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
722 (defun org-ref-list-of-tables (&optional arg)
723   "Generate a buffer with a list of tables"
724   (interactive)
725   (save-excursion
726   (widen)
727   (let* ((c-b (buffer-name))
728          (counter 0)
729          (list-of-tables 
730           (org-element-map (org-element-parse-buffer 'element) 'table
731             (lambda (table) 
732               "create a link for to the table"
733               (incf counter)
734               (let ((start (org-element-property :begin table))
735                     (name  (org-element-property :name table))
736                     (caption (caaar (org-element-property :caption table))))
737                 (if caption 
738                     (format 
739                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n" 
740                      c-b start counter (or name "") caption)
741                   (format 
742                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n" 
743                    c-b start counter (or name ""))))))))
744     (switch-to-buffer "*List of Tables*")
745     (setq buffer-read-only nil)
746     (org-mode)
747     (erase-buffer)
748     (insert (mapconcat 'identity list-of-tables ""))
749     (setq buffer-read-only t)
750     (use-local-map (copy-keymap org-mode-map))
751     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
752
753 (org-add-link-type 
754  "list-of-tables"
755  'org-ref-list-of-tables
756  (lambda (keyword desc format)
757    (cond
758     ((eq format 'latex)
759      (format "\\listoftables")))))
760 #+END_SRC
761 ** label
762
763 The label link provides a way to create labels in org-mode. We make it clickable because we want to make sure labels are unique. This code will tell you how many instances of a label are found.  We search for label links, LaTeX labels, and the org-mode format for labels. We probably should search for tblnames too.
764 *************** TODO search tblnames, custom_ids and check for case sensitivity
765 *************** END
766
767 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
768 (org-add-link-type
769  "label"
770  (lambda (label)
771    "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
772    (message (format "%s occurences"
773                     (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
774                        ;; for tblname, it is not enough to get word boundary
775                        ;; tab-little and tab-little-2 match then.
776                        (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
777                        (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
778                        ;; this is the org-format #+label:
779                        (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))))
780  (lambda (keyword desc format)
781    (cond
782     ((eq format 'html) (format "(<label>%s</label>)" path))
783     ((eq format 'latex)
784      (format "\\label{%s}" keyword)))))
785 #+END_SRC
786
787 We want to store links on labels, so you can put the cursor on the label, press C-c l, and later use C-c C-l to insert a link to the label. We also want to store links to tables with a table name, and for sections with CUSTOM_ID.
788
789 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
790 (defun org-label-store-link ()
791   "store a link to a label. The output will be a ref to that label"
792   ;; First we have to make sure we are on a label link. 
793   (let* ((object (org-element-context)))
794     (when (and (equal (org-element-type object) 'link) 
795                (equal (org-element-property :type object) "label"))
796       (org-store-link-props
797        :type "ref"
798        :link (concat "ref:" (org-element-property :path object))))
799
800     ;; Store link on table
801     (when (equal (org-element-type object) 'table)
802       (org-store-link-props
803        :type "ref"
804        :link (concat "ref:" (org-element-property :name object))))
805
806 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
807     ;; store link on heading with custom_id
808 ;    (when (and (equal (org-element-type object) 'headline)
809 ;              (org-entry-get (point) "CUSTOM_ID"))
810 ;      (org-store-link-props
811 ;       :type "ref"
812 ;       :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
813
814     ;; and to #+label: lines
815     (when (and (equal (org-element-type object) 'paragraph)
816                (org-element-property :name object))
817       (org-store-link-props
818        :type "ref"
819        :link (concat "ref:" (org-element-property :name object))))
820 ))
821
822 (add-hook 'org-store-link-functions 'org-label-store-link)
823 #+END_SRC
824 ** ref
825
826 The ref link allows you make links to labels. Clicking on the link takes you to the label, and provides a mark to go back to. 
827
828 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
829
830 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
831 (org-add-link-type
832  "ref"
833  (lambda (label)
834    "on clicking goto the label. Navigate back with C-c &"
835    (org-mark-ring-push)
836    ;; next search from beginning of the buffer
837
838    ;; it is possible you would not find the label if narrowing is in effect
839    (widen)
840
841    (unless
842        (or
843         ;; our label links
844         (progn 
845           (goto-char (point-min))
846           (re-search-forward (format "label:%s\\b" label) nil t))
847
848         ;; a latex label
849         (progn
850           (goto-char (point-min))
851           (re-search-forward (format "\\label{%s}" label) nil t))
852
853         ;; #+label: name  org-definition
854         (progn
855           (goto-char (point-min))
856           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
857         
858         ;; org tblname
859         (progn
860           (goto-char (point-min))
861           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
862
863 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
864 ;; you need [[#label]] links.
865         ;; CUSTOM_ID
866 ;       (progn
867 ;         (goto-char (point-min))
868 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
869         )
870      ;; we did not find anything, so go back to where we came
871      (org-mark-ring-goto)
872      (error "%s not found" label))
873    (message "go back with (org-mark-ring-goto) `C-c &`"))
874  ;formatting
875  (lambda (keyword desc format)
876    (cond
877     ((eq format 'html) (format "(<ref>%s</ref>)" path))
878     ((eq format 'latex)
879      (format "\\ref{%s}" keyword)))))
880 #+END_SRC
881
882 It would be nice to use completion to enter a ref link, where a list of labels is provided. The following code searches the buffer for labels, custom_ids, and table names as potential items to make a ref link to.
883
884 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
885 (defun org-ref-get-custom-ids ()
886  "return a list of custom_id properties in the buffer"
887  (let ((results '()) custom_id)
888    (org-map-entries 
889     (lambda () 
890       (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
891         (when (not (null custom_id))
892           (setq results (append results (list custom_id)))))))
893 results))
894 #+END_SRC
895
896 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
897 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
898 (defun org-ref-get-latex-labels ()
899 (save-excursion
900     (goto-char (point-min))
901     (let ((matches '()))
902       (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
903         (add-to-list 'matches (match-string-no-properties 1) t))
904 matches)))
905 #+END_SRC
906
907 Finally, we get the table names.
908
909 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
910 (defun org-ref-get-tblnames ()
911   (org-element-map (org-element-parse-buffer 'element) 'table
912     (lambda (table) 
913       (org-element-property :name table))))
914 #+END_SRC
915
916 Now, we can put all the labels together which will give us a list of candidates.
917
918 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
919 (defun org-ref-get-labels ()
920   "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
921   (save-excursion
922     (save-restriction
923       (widen)
924       (goto-char (point-min))
925       (let ((matches '()))
926         (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
927           (add-to-list 'matches (match-string-no-properties 1) t))
928         (append matches (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
929 #+END_SRC
930
931 Now we create the completion function. This works from the org-machinery, e.g. if you type C-c C-l to insert a link, and use completion by pressing tab.
932
933 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
934 (defun org-ref-complete-link (&optional arg)
935   "Completion function for ref links"
936   (let ((label))
937     (setq label (completing-read "label: " (org-ref-get-labels)))
938     (format "ref:%s" label)))
939 #+END_SRC
940
941 Alternatively, you may want to just call a function that inserts a link with completion:
942
943 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
944 (defun org-ref-insert-ref-link ()
945  (interactive)
946  (insert (org-ref-complete-link)))
947 #+END_SRC
948
949 ** pageref
950
951 This refers to the page of a label in LaTeX.
952
953 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
954 (org-add-link-type
955  "pageref"
956  (lambda (label)
957    "on clicking goto the label. Navigate back with C-c &"
958    (org-mark-ring-push)
959    ;; next search from beginning of the buffer
960    (widen)
961    (unless
962        (or
963         ;; our label links
964         (progn 
965           (goto-char (point-min))
966           (re-search-forward (format "label:%s\\b" label) nil t))
967
968         ;; a latex label
969         (progn
970           (goto-char (point-min))
971           (re-search-forward (format "\\label{%s}" label) nil t))
972
973         ;; #+label: name  org-definition
974         (progn
975           (goto-char (point-min))
976           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
977         
978         ;; org tblname
979         (progn
980           (goto-char (point-min))
981           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
982
983 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
984 ;; you need [[#label]] links.
985         ;; CUSTOM_ID
986 ;       (progn
987 ;         (goto-char (point-min))
988 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
989         )
990      ;; we did not find anything, so go back to where we came
991      (org-mark-ring-goto)
992      (error "%s not found" label))
993    (message "go back with (org-mark-ring-goto) `C-c &`"))
994  ;formatting
995  (lambda (keyword desc format)
996    (cond
997     ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
998     ((eq format 'latex)
999      (format "\\pageref{%s}" keyword)))))
1000 #+END_SRC
1001
1002 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1003 (defun org-pageref-complete-link (&optional arg)
1004   "Completion function for ref links"
1005   (let ((label))
1006     (setq label (completing-read "label: " (org-ref-get-labels)))
1007     (format "ref:%s" label)))
1008 #+END_SRC
1009
1010 Alternatively, you may want to just call a function that inserts a link with completion:
1011
1012 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1013 (defun org-pageref-insert-ref-link ()
1014  (interactive)
1015  (insert (org-pageref-complete-link)))
1016 #+END_SRC
1017
1018 ** nameref
1019
1020 The nameref link allows you make links to the text of a section with a label. Clicking on the link takes you to the label, and provides a mark to go back to. This only works if you put a raw latex label in the headline.
1021
1022 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1023 (org-add-link-type
1024  "nameref"
1025  (lambda (label)
1026    "on clicking goto the label. Navigate back with C-c &"
1027    (org-mark-ring-push)
1028    ;; next search from beginning of the buffer
1029    (widen)
1030    (unless
1031        (or
1032         ;; a latex label
1033         (progn
1034           (goto-char (point-min))
1035           (re-search-forward (format "\\label{%s}" label) nil t))
1036         )
1037      ;; we did not find anything, so go back to where we came
1038      (org-mark-ring-goto)
1039      (error "%s not found" label))
1040    (message "go back with (org-mark-ring-goto) `C-c &`"))
1041  ;formatting
1042  (lambda (keyword desc format)
1043    (cond
1044     ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1045     ((eq format 'latex)
1046      (format "\\nameref{%s}" keyword)))))
1047 #+END_SRC
1048
1049 ** eqref
1050 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1051  
1052 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1053 (org-add-link-type
1054  "eqref"
1055  (lambda (label)
1056    "on clicking goto the label. Navigate back with C-c &"
1057    (org-mark-ring-push)
1058    ;; next search from beginning of the buffer
1059    (widen)
1060    (goto-char (point-min))
1061    (unless
1062        (or
1063         ;; search forward for the first match
1064         ;; our label links
1065         (re-search-forward (format "label:%s" label) nil t)
1066         ;; a latex label
1067         (re-search-forward (format "\\label{%s}" label) nil t)
1068         ;; #+label: name  org-definition
1069         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1070      (org-mark-ring-goto)
1071      (error "%s not found" label))
1072    (message "go back with (org-mark-ring-goto) `C-c &`"))
1073  ;formatting
1074  (lambda (keyword desc format)
1075    (cond
1076     ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1077     ((eq format 'latex)
1078      (format "\\eqref{%s}" keyword)))))
1079 #+END_SRC
1080
1081
1082 ** cite
1083 This is the main reason this library exists. We want the following behavior. A cite link should be able to contain multiple bibtex keys. You should be able to click on the link, and get a brief citation of the entry for that key, and a menu of options to open the bibtex file, open a pdf if you have it, open your notes on the entry, or open a url if it exists. You should be able to insert new references onto an existing cite link, or create new ones easily. The following code implements these features.
1084
1085 *** Implementing the click actions of cite
1086
1087 **** Getting the key we clicked on
1088 The first thing we need is to get the bibtex key we clicked on.
1089
1090 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1091 (defun org-ref-get-bibtex-key-under-cursor ()
1092   "returns key under the bibtex cursor. We search forward from
1093 point to get a comma, or the end of the link, and then backwards
1094 to get a comma, or the beginning of the link. that delimits the
1095 keyword we clicked on. We also strip the text properties."
1096   (interactive)
1097   (let* ((object (org-element-context))  
1098          (link-string (org-element-property :path object)))
1099     (message "%s" object)
1100
1101     ;; you may click on the part before the citations. here we make
1102     ;; sure to move to the beginning so you get the first citation.
1103     (let ((cp (point)))
1104       (goto-char (org-element-property :begin object))
1105       (search-forward link-string (org-element-property :end object))
1106       (goto-char (match-beginning 0))
1107       ;; check if we clicked before the path and move as needed.
1108       (unless (< cp (point))
1109         (goto-char cp)))
1110         
1111     (if (not (org-element-property :contents-begin object))
1112         ;; this means no description in the link
1113         (progn    
1114           ;; we need the link path start and end
1115           (save-excursion
1116             (goto-char (org-element-property :begin object))
1117             (search-forward link-string nil nil 1)
1118             (setq link-string-beginning (match-beginning 0))
1119             (setq link-string-end (match-end 0)))
1120
1121           ;; The key is the text between commas, or the link boundaries
1122           (save-excursion
1123             (if (search-forward "," link-string-end t 1)
1124                 (setq key-end (- (match-end 0) 1)) ; we found a match
1125               (setq key-end link-string-end))) ; no comma found so take the end
1126           ;; and backward to previous comma from point which defines the start character
1127           (save-excursion
1128             (if (search-backward "," link-string-beginning 1 1)
1129                 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1130               (setq key-beginning link-string-beginning))) ; no match found
1131           ;; save the key we clicked on.
1132           (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1133           (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1134           bibtex-key)
1135       ;; link with description. assume only one key
1136       link-string)))
1137 #+END_SRC
1138
1139 We also need to find which bibliography file that key is in. For that, we need to know which bibliography files are referred to in the file. If none are specified with a bibliography link, we use the default bibliography. This function searches for a bibliography link, and then the LaTeX bibliography link. We also consider the addbibresource link which is used with biblatex.
1140
1141 **** Getting the bibliographies
1142 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1143 (defun org-ref-find-bibliography ()
1144   "find the bibliography in the buffer.
1145 This function sets and returns cite-bibliography-files, which is a list of files
1146 either from bibliography:f1.bib,f2.bib
1147 \bibliography{f1,f2}
1148 internal bibliographies
1149
1150 falling back to what the user has set in org-ref-default-bibliography
1151 "
1152   (interactive)
1153   (catch 'result
1154     (save-excursion
1155       (goto-char (point-min))
1156       ;;  look for a bibliography link
1157       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1158         (setq org-ref-bibliography-files
1159               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1160         (throw 'result org-ref-bibliography-files))
1161
1162       
1163       ;; we did not find a bibliography link. now look for \bibliography
1164       (goto-char (point-min))
1165       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1166         ;; split, and add .bib to each file
1167         (setq org-ref-bibliography-files
1168               (mapcar (lambda (x) (concat x ".bib"))
1169                       (mapcar 'org-ref-strip-string 
1170                               (split-string (match-string 1) ","))))
1171         (throw 'result org-ref-bibliography-files))
1172
1173       ;; no bibliography found. maybe we need a biblatex addbibresource
1174       (goto-char (point-min))
1175       ;;  look for a bibliography link
1176       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1177         (setq org-ref-bibliography-files
1178               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1179         (throw 'result org-ref-bibliography-files))
1180           
1181       ;; we did not find anything. use defaults
1182       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1183
1184     ;; set reftex-default-bibliography so we can search
1185     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1186     org-ref-bibliography-files)
1187 #+END_SRC
1188
1189 **** Finding the bibliography file a key is in
1190 Now, we can see if an entry is in a file. 
1191
1192 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1193 (defun org-ref-key-in-file-p (key filename)
1194   "determine if the key is in the file"
1195   (interactive "skey: \nsFile: ")
1196   (save-current-buffer
1197     (let ((bibtex-files (list filename)))
1198       (bibtex-search-entry key t))))
1199 #+END_SRC
1200
1201 Finally, we want to know which file the key is in.
1202
1203 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1204 (defun org-ref-get-bibtex-key-and-file (&optional key)
1205   "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1206  (interactive)
1207  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1208        (file))
1209    (unless key
1210      (setq key (org-ref-get-bibtex-key-under-cursor)))
1211    (setq file     (catch 'result
1212                     (loop for file in org-ref-bibliography-files do
1213                           (if (org-ref-key-in-file-p key (file-truename file)) 
1214                               (throw 'result file)))))
1215    (cons key file)))
1216 #+END_SRC
1217
1218 **** Creating the menu for when we click on a key
1219      :PROPERTIES:
1220      :ID:       d7b7530b-802f-42b1-b61e-1e77da33e278
1221      :END:
1222 When we click on a cite link, we want to get a menu in the minibuffer. We need to create a string for this. We want a citation, and some options that depend on the key. We want to know if the key is found, if there is a pdf, if etc... Here we create that string.
1223
1224 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1225 (defun org-ref-get-menu-options ()
1226   "returns a dynamically determined string of options for the citation under point.
1227
1228 we check to see if there is pdf, and if the key actually exists in the bibliography"
1229   (interactive)
1230   (let* ((results (org-ref-get-bibtex-key-and-file))
1231          (key (car results))
1232          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1233          (bibfile (cdr results))
1234          m1 m2 m3 m4 m5 menu-string)
1235     (setq m1 (if bibfile                 
1236                  "(o)pen"
1237                "(No key found)"))
1238
1239     (setq m3 (if (file-exists-p pdf-file)
1240                  "(p)df"
1241                      "(No pdf found)"))
1242
1243     (setq m4 (if (not
1244                   (and bibfile
1245                        (string= (catch 'url
1246                                   (progn
1247
1248                                     (with-temp-buffer
1249                                       (insert-file-contents bibfile)
1250                                       (bibtex-search-entry key)
1251                                       (when (not
1252                                              (string= (setq url (bibtex-autokey-get-field "url")) ""))
1253                                         (throw 'url url))
1254
1255                                       (when (not
1256                                              (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1257                                         (throw 'url url))))) "")))
1258                "(u)rl" "(no url found)"))
1259     (setq m5 "(n)otes")
1260     (setq m2 (if bibfile
1261                  (progn
1262                    (setq citation (progn
1263                                     (with-temp-buffer
1264                                       (insert-file-contents bibfile)
1265                                       (bibtex-search-entry key)
1266                                       (org-ref-bib-citation))))
1267                    citation)
1268                "no key found"))
1269
1270     (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") "  "))
1271     menu-string))
1272 #+END_SRC
1273
1274 **** convenience functions to act on citation at point
1275      :PROPERTIES:
1276      :ID:       af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1277      :END:
1278 We need some convenience functions to open act on the citation at point. These will get the pdf, open the url, or open the notes.
1279
1280 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1281 (defun org-ref-open-pdf-at-point ()
1282   "open the pdf for bibtex key under point if it exists"
1283   (interactive)
1284   (let* ((results (org-ref-get-bibtex-key-and-file))
1285          (key (car results))
1286          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1287     (if (file-exists-p pdf-file)
1288         (org-open-file pdf-file)
1289 (message "no pdf found for %s" key))))
1290
1291
1292 (defun org-ref-open-url-at-point ()
1293   "open the url for bibtex key under point."
1294   (interactive)
1295   (let* ((results (org-ref-get-bibtex-key-and-file))
1296          (key (car results))
1297          (bibfile (cdr results)))
1298     (save-excursion
1299       (with-temp-buffer
1300         (insert-file-contents bibfile)
1301         (bibtex-search-entry key)
1302         ;; I like this better than bibtex-url which does not always find
1303         ;; the urls
1304         (catch 'done
1305           (let ((url (bibtex-autokey-get-field "url")))
1306             (when  url
1307               (browse-url url)
1308               (throw 'done nil)))
1309
1310           (let ((doi (bibtex-autokey-get-field "doi")))
1311             (when doi
1312               (if (string-match "^http" doi)
1313                   (browse-url doi)
1314                 (browse-url (format "http://dx.doi.org/%s" doi)))
1315               (throw 'done nil))))))))
1316
1317 (defun org-ref-open-notes-at-point ()
1318   "open the notes for bibtex key under point."
1319   (interactive)
1320   (let* ((results (org-ref-get-bibtex-key-and-file))
1321          (key (car results))
1322          (bibfile (cdr results)))
1323     (save-excursion
1324       (with-temp-buffer
1325         (insert-file-contents bibfile)
1326         (bibtex-search-entry key)
1327         (org-ref-open-bibtex-notes)))))
1328
1329 (defun org-ref-citation-at-point ()
1330   "give message of current citation at point"
1331   (interactive)
1332   (let* ((cb (current-buffer))
1333         (results (org-ref-get-bibtex-key-and-file))
1334         (key (car results))
1335         (bibfile (cdr results)))        
1336     (message "%s" (progn
1337                     (with-temp-buffer
1338                       (insert-file-contents bibfile)
1339                       (bibtex-search-entry key)
1340                       (org-ref-bib-citation))))))
1341
1342 (defun org-ref-open-citation-at-point ()
1343   "open bibtex file to key at point"
1344   (interactive)
1345   (let* ((cb (current-buffer))
1346         (results (org-ref-get-bibtex-key-and-file))
1347         (key (car results))
1348         (bibfile (cdr results)))
1349     (find-file bibfile)
1350     (bibtex-search-entry key)))
1351 #+END_SRC
1352
1353 **** the actual minibuffer menu
1354 Now, we create the menu.
1355
1356 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1357 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1358   "use a minibuffer to select options for the citation under point.
1359
1360 you select your option with a single key press."
1361   (interactive)
1362   (let* ((choice (read-char (org-ref-get-menu-options)))
1363          (results (org-ref-get-bibtex-key-and-file))
1364          (key (car results))
1365          (cb (current-buffer))
1366          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1367          (bibfile (cdr results)))
1368
1369     (cond
1370      ;; open
1371      ((= choice ?o)
1372       (find-file bibfile)
1373        (bibtex-search-entry key))
1374
1375      ;; cite
1376      ((= choice ?c)
1377       (org-ref-citation-at-point))
1378       
1379
1380      ;; quit
1381      ((or 
1382       (= choice ?q) ; q
1383       (= choice ?\ )) ; space
1384       ;; this clears the minibuffer
1385       (message ""))
1386
1387      ;; pdf
1388      ((= choice ?p)
1389       (org-ref-open-pdf-at-point))
1390
1391      ;; notes
1392      ((= choice ?n)
1393       (org-ref-open-notes-at-point))
1394
1395      ;; url
1396      ((= choice ?u)
1397       (org-ref-open-url-at-point))
1398
1399      ;; anything else we just quit.
1400      (t (message "")))))
1401     
1402 #+END_SRC
1403
1404 *** A function to format a cite link
1405
1406 Next, we define a formatting function for the cite link. This is done so that the cite link definition is very short, and easy to change. You just need to specify the functions in the definition. This function is deprecated. The formatting is defined later automatically.
1407
1408 #+BEGIN_SRC emacs-lisp  :tangle no
1409 ;(defun org-ref-cite-link-format (keyword desc format)
1410 ;   (cond
1411 ;    ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1412 ;    ((eq format 'latex)
1413 ;     (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1414 ;            (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1415 ;            "}"))))
1416 #+END_SRC
1417
1418 *** The actual cite link
1419 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1420
1421 #+BEGIN_SRC emacs-lisp :tangle no
1422 ;(org-add-link-type
1423 ; "cite"
1424 ; 'org-ref-cite-onclick-minibuffer-menu
1425 ; 'org-ref-cite-link-format)
1426 #+END_SRC
1427
1428 *** Automatic definition of the cite links
1429 There are many different kinds of citations in LaTeX, but they are all variants of a basic syntax of \citetype[optional text]{label1,label2}. Here we use lisp to generate the link definitions. We define a function that creates the code to create the link, and then we evaluate it. We also create the completion function for the new link, and add it to the list of known links. 
1430
1431 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1432 (defmacro org-ref-make-completion-function (type)
1433   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1434      (interactive)
1435      (format "%s:%s" 
1436              ,type
1437              (completing-read 
1438               "bibtex key: " 
1439               (let ((bibtex-files (org-ref-find-bibliography)))
1440                 (bibtex-global-key-alist))))))
1441 #+END_SRC
1442
1443 We will want to generate formatting functions for each citation type. The reason for doing this is so we can on the fly change the formatting later.
1444
1445 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1446 (defmacro org-ref-make-format-function (type)
1447   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1448      (cond
1449       ((eq format 'org)
1450        (mapconcat
1451         (lambda (key)
1452           (format "[[#%s][%s]]" key key))
1453         (org-ref-split-and-strip-string keyword) ","))
1454
1455       ((eq format 'ascii)
1456        (concat "["
1457                (mapconcat
1458                 (lambda (key)
1459                   (format "%s" key))
1460                 (org-ref-split-and-strip-string keyword) ",") "]"))
1461         
1462       ((eq format 'html) 
1463        (mapconcat 
1464         (lambda (key) 
1465           (format "<a href=\"#%s\">%s</a>" key key))
1466         (org-ref-split-and-strip-string keyword) ","))
1467
1468       ((eq format 'latex)
1469        (if (string= (substring type -1) "s")
1470            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1471            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1472                                          (org-ref-split-and-strip-string keyword) ""))
1473          ;; bibtex format
1474        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1475                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1476                "}"))))))
1477 #+END_SRC
1478
1479
1480
1481 We create the links by mapping the function onto the list of defined link types. 
1482
1483 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1484 (defun org-ref-format-citation-description (desc)
1485   "return formatted citation description. if the cite link has a description, it is optional text for the citation command. You can specify pre and post text by separating these with ::."
1486   (interactive)
1487   (cond
1488    ((string-match "::" desc)
1489     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1490    (t (format "[%s]" desc))))
1491
1492 (defun org-ref-define-citation-link (type &optional key)
1493   "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1494 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z, 
1495 and the completion function."
1496   (interactive "sCitation Type: \ncKey: ")
1497
1498   ;; create the formatting function
1499   (eval `(org-ref-make-format-function ,type))
1500
1501   (eval-expression 
1502    `(org-add-link-type 
1503      ,type
1504      'org-ref-cite-onclick-minibuffer-menu
1505      (quote ,(intern (format "org-ref-format-%s" type)))))
1506
1507   ;; create the completion function
1508   (eval `(org-ref-make-completion-function ,type))
1509   
1510   ;; store new type so it works with adding citations, which checks
1511   ;; for existence in this list
1512   (add-to-list 'org-ref-cite-types type)
1513
1514   ;; and finally if a key is specified, we modify the reftex menu
1515   (when key
1516     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1517           (append (nth 2 (assoc 'org reftex-cite-format-builtin)) 
1518                   `((,key  . ,(concat type ":%l")))))))
1519
1520 ;; create all the link types and their completion functions
1521 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1522 #+END_SRC
1523
1524 *** org-ref-insert-cite-link
1525 We need a convenient method to insert links. In reftex you use the keystroke C-c ], which gives you a minibuffer to search the bibtex files from. This function is bound to that same keystroke here [[*org-mode%20/%20reftex%20setup][org-mode / reftex setup]]. This function will append to a cite link if you call it while on a link.
1526
1527 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1528 (defun org-ref-insert-cite-link (alternative-cite)
1529   "Insert a default citation link using reftex. If you are on a link, it
1530 appends to the end of the link, otherwise, a new link is
1531 inserted. Use a prefix arg to get a menu of citation types."
1532   (interactive "P")
1533   (org-ref-find-bibliography)
1534   (let* ((object (org-element-context))
1535          (link-string-beginning (org-element-property :begin object))
1536          (link-string-end (org-element-property :end object))
1537          (path (org-element-property :path object)))  
1538
1539     (if (not alternative-cite)
1540         
1541         (cond
1542          ;; case where we are in a link
1543          ((and (equal (org-element-type object) 'link) 
1544                (-contains? org-ref-cite-types (org-element-property :type object)))
1545           (goto-char link-string-end)
1546           ;; sometimes there are spaces at the end of the link
1547           ;; this code moves point pack until no spaces are there
1548           (while (looking-back " ") (backward-char))  
1549           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1550
1551          ;; We are next to a link, and we want to append
1552          ((save-excursion 
1553             (backward-char)
1554             (and (equal (org-element-type (org-element-context)) 'link) 
1555                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1556           (while (looking-back " ") (backward-char))  
1557           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1558
1559          ;; insert fresh link
1560          (t 
1561           (insert 
1562            (concat org-ref-default-citation-link 
1563                    ":" 
1564                    (mapconcat 'identity (reftex-citation t) ",")))))
1565
1566       ;; you pressed a C-u so we run this code
1567       (reftex-citation)))
1568   )
1569 #+END_SRC
1570
1571 #+RESULTS:
1572 : org-ref-insert-cite-link
1573
1574 *** Completion in cite links
1575 If you know the specific bibtex key, you may like to use completion directly. You use this with the org-mode machinery and tab completion. Here is the prototypical completion function. These are now all created when the links are created.
1576
1577 #+BEGIN_SRC emacs-lisp  :tangle no
1578 (defun org-cite-complete-link (&optional arg)
1579   "Completion function for cite links"
1580   (format "%s:%s" 
1581           org-ref-default-citation-link
1582           (completing-read 
1583            "bibtex key: " 
1584            (let ((bibtex-files (org-ref-find-bibliography)))
1585              (bibtex-global-key-alist)))))
1586 #+END_SRC
1587
1588 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1589
1590 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1591 (defun org-ref-insert-cite-with-completion (type)
1592   "Insert a cite link with completion"
1593   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1594   (insert (funcall (intern (format "org-%s-complete-link" type)))))
1595 #+END_SRC
1596
1597 ** Storing links to a bibtex entry
1598 org-mode already defines a store link function for bibtex entries. It does not store the link I want though, it only stores a brief citation of the entry. I want a citation link. Here is a function to do that.
1599
1600 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1601 (defun org-ref-store-bibtex-entry-link ()
1602   "Save a citation link to the current bibtex entry. Saves in the default link type."
1603   (interactive)
1604   (let ((link (concat org-ref-default-citation-link 
1605                  ":"   
1606                  (save-excursion
1607                    (bibtex-beginning-of-entry)
1608                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1609     (message "saved %s" link)
1610     (push (list link) org-stored-links)
1611     (car org-stored-links)))
1612 #+END_SRC
1613
1614
1615 * Utilities
1616 ** create simple text citation from bibtex entry
1617
1618 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1619 (defun org-ref-bib-citation ()
1620   "from a bibtex entry, create and return a simple citation string."
1621
1622   (bibtex-beginning-of-entry)
1623   (let* ((cb (current-buffer))
1624          (bibtex-expand-strings t)
1625          (entry (loop for (key . value) in (bibtex-parse-entry t)
1626                       collect (cons (downcase key) value)))
1627          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1628          (year  (reftex-get-bib-field "year" entry))
1629          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1630          (key (reftex-get-bib-field "=key=" entry))
1631          (journal (reftex-get-bib-field "journal" entry))
1632          (volume (reftex-get-bib-field "volume" entry))
1633          (pages (reftex-get-bib-field "pages" entry))
1634          (doi (reftex-get-bib-field "doi" entry))
1635          (url (reftex-get-bib-field "url" entry))
1636          )
1637     ;;authors, "title", Journal, vol(iss):pages (year).
1638     (format "%s, \"%s\", %s, %s:%s (%s)"
1639             author title journal  volume pages year)))
1640 #+END_SRC
1641
1642 #+RESULTS:
1643 : org-ref-bib-citation
1644
1645
1646 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1647 (defun org-ref-bib-html-citation ()
1648   "from a bibtex entry, create and return a simple citation with html links."
1649
1650   (bibtex-beginning-of-entry)
1651   (let* ((cb (current-buffer))
1652          (bibtex-expand-strings t)
1653          (entry (loop for (key . value) in (bibtex-parse-entry t)
1654                       collect (cons (downcase key) value)))
1655          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1656          (year  (reftex-get-bib-field "year" entry))
1657          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1658          (key (reftex-get-bib-field "=key=" entry))
1659          (journal (reftex-get-bib-field "journal" entry))
1660          (volume (reftex-get-bib-field "volume" entry))
1661          (pages (reftex-get-bib-field "pages" entry))
1662          (doi (reftex-get-bib-field "doi" entry))
1663          (url (reftex-get-bib-field "url" entry))
1664          )
1665     ;;authors, "title", Journal, vol(iss):pages (year).
1666     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1667                     author title journal  volume pages year)
1668             (when url (format " <a href=\"%s\">link</a>" url))
1669             (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1670     ))
1671 #+END_SRC
1672
1673 ** open pdf from bibtex
1674 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1675 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1676 (defun org-ref-open-bibtex-pdf ()
1677   "open pdf for a bibtex entry, if it exists. assumes point is in
1678 the entry of interest in the bibfile. but does not check that."
1679   (interactive)
1680   (save-excursion
1681     (bibtex-beginning-of-entry)
1682     (let* ((bibtex-expand-strings t)
1683            (entry (bibtex-parse-entry t))
1684            (key (reftex-get-bib-field "=key=" entry))
1685            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1686       (message "%s" pdf)
1687       (if (file-exists-p pdf)
1688           (org-open-link-from-string (format "[[file:%s]]" pdf))
1689         (ding)))))
1690 #+END_SRC
1691
1692 ** open notes from bibtex
1693 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1694
1695 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1696 (defun org-ref-open-bibtex-notes ()
1697   "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1698
1699 I never did figure out how to use reftex to make this happen
1700 non-interactively. the reftex-format-citation function did not
1701 work perfectly; there were carriage returns in the strings, and
1702 it did not put the key where it needed to be. so, below I replace
1703 the carriage returns and extra spaces with a single space and
1704 construct the heading by hand."
1705   (interactive)
1706
1707   (bibtex-beginning-of-entry)
1708   (let* ((cb (current-buffer))
1709          (bibtex-expand-strings t)
1710          (entry (loop for (key . value) in (bibtex-parse-entry t)
1711                       collect (cons (downcase key) value)))
1712          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1713          (year  (reftex-get-bib-field "year" entry))
1714          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1715          (key (reftex-get-bib-field "=key=" entry))
1716          (journal (reftex-get-bib-field "journal" entry))
1717          (volume (reftex-get-bib-field "volume" entry))
1718          (pages (reftex-get-bib-field "pages" entry))
1719          (doi (reftex-get-bib-field "doi" entry))
1720          (url (reftex-get-bib-field "url" entry))
1721          )
1722
1723     ;; save key to clipboard to make saving pdf later easier by pasting.
1724     (with-temp-buffer
1725       (insert key)
1726       (kill-ring-save (point-min) (point-max)))
1727     
1728     ;; now look for entry in the notes file
1729     (if  org-ref-bibliography-notes
1730         (find-file org-ref-bibliography-notes)
1731       (error "org-ref-bib-bibliography-notes is not set to anything"))
1732     
1733     (goto-char (point-min))
1734     ;; put new entry in notes if we don't find it.
1735     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1736         (progn
1737           (org-show-entry)
1738           (outline-previous-visible-heading 1)
1739           (recenter-top-bottom 0))
1740       ;; no entry found, so add one     
1741       (insert (format "\n** TODO %s - %s" year title))
1742       (insert (format"
1743  :PROPERTIES:
1744   :Custom_ID: %s
1745   :AUTHOR: %s
1746   :JOURNAL: %s
1747   :YEAR: %s
1748   :VOLUME: %s
1749   :PAGES: %s
1750   :DOI: %s
1751   :URL: %s
1752  :END:
1753 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1754 key author journal year volume pages doi url key org-ref-pdf-directory key))
1755 (save-buffer))))
1756 #+END_SRC
1757
1758 ** open url in browser from bibtex
1759
1760 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1761
1762 + This function may be duplicative of bibtex-url. But I think my function is better unless you do some complicated customization of bibtex-generate-url-list.
1763
1764 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1765 (defun org-ref-open-in-browser ()
1766   "Open the bibtex entry at point in a browser using the url field or doi field"
1767 (interactive)
1768 (save-excursion
1769   (bibtex-beginning-of-entry)
1770   (catch 'done
1771     (let ((url (bibtex-autokey-get-field "url")))
1772       (when  url
1773         (browse-url url)
1774         (throw 'done nil)))
1775
1776     (let ((doi (bibtex-autokey-get-field "doi")))
1777       (when doi
1778         (if (string-match "^http" doi)
1779             (browse-url doi)
1780           (browse-url (format "http://dx.doi.org/%s" doi)))
1781         (throw 'done nil)))
1782     (message "No url or doi found"))))
1783 #+END_SRC
1784
1785 ** citeulike
1786    I discovered you could upload a bibtex entry to citeulike using http requests. The upload is actually done by a [[*The%20upload%20script][python script]], because it was easy to write. Here is the emacs command to do this. It is not a fast operation, and  do not use it frequently.
1787
1788 *** function to upload bibtex to citeulike
1789
1790 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1791 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1792   "with point in  a bibtex entry get bibtex string and submit to citeulike.
1793
1794 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1795   (interactive)
1796   (message "uploading to citeulike")
1797   (save-restriction
1798     (bibtex-narrow-to-entry)
1799     (let ((startpos (point-min))
1800           (endpos (point-max))
1801           (bibtex-string (buffer-string))
1802           (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1803       (with-temp-buffer (insert bibtex-string)
1804                         (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1805 #+END_SRC
1806
1807 *** The upload script
1808 Here is the python script for uploading. 
1809
1810 *************** TODO document how to get the cookies
1811 *************** END
1812
1813
1814 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1815 #!python
1816 import pickle, requests, sys
1817
1818 # reload cookies
1819 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1820     cookies = pickle.load(f)
1821
1822 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1823
1824 bibtex = sys.stdin.read()
1825
1826 data = {'pasted':bibtex,
1827         'to_read':2,
1828         'tag_parsing':'simple',
1829         'strip_brackets':'no',
1830         'update_id':'bib-key',
1831         'btn_bibtex':'Import BibTeX file ...'}
1832
1833 headers = {'content-type': 'multipart/form-data',
1834            'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1835
1836 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1837 print r
1838 #+END_SRC
1839
1840 ** Build a pdf from a bibtex file
1841    It is useful to have a pdf version of an entire bibliography to check it for formatting, spelling, or to share it. This function creates a pdf from a bibtex file. I only include the packages  I commonly use in my bitex files.
1842
1843 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1844 (defun org-ref-build-full-bibliography ()
1845   "build pdf of all bibtex entries, and open it."
1846   (interactive)
1847   (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1848         (bib-base (file-name-sans-extension bibfile))
1849         (texfile (concat bib-base ".tex"))
1850         (pdffile (concat bib-base ".pdf")))
1851     (find-file texfile)
1852     (erase-buffer)
1853     (insert (format "\\documentclass[12pt]{article}
1854 \\usepackage[version=3]{mhchem}
1855 \\usepackage{url}
1856 \\usepackage[numbers]{natbib}
1857 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1858 \\usepackage{doi}
1859 \\begin{document}
1860 \\nocite{*}
1861 \\bibliographystyle{unsrtnat}
1862 \\bibliography{%s}
1863 \\end{document}" bib-base))
1864     (save-buffer)
1865     (shell-command (concat "pdflatex " bib-base))
1866     (shell-command (concat "bibtex " bib-base))
1867     (shell-command (concat "pdflatex " bib-base))
1868     (shell-command (concat "pdflatex " bib-base))
1869     (kill-buffer texfile)
1870     (org-open-file pdffile)
1871     )) 
1872 #+END_SRC
1873
1874 ** Extract bibtex entries cited in an org-file
1875 When you use your default bibliography file, and you want to send an org-file to a collaborator, you may need to include bibtex entries so the other person can see them. This function does that and puts the entries in a section at the end of the document that can be tangled to a bib-file.
1876
1877 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1878 (defun org-ref-extract-bibtex-entries ()
1879   "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1880
1881 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1882   (interactive)
1883   (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1884          (tempname (make-temp-file "extract-bib"))
1885          (contents (buffer-string))
1886          (cb (current-buffer))
1887          basename texfile bibfile results)
1888     
1889     ;; open tempfile and insert org-buffer contents
1890     (find-file tempname)
1891     (insert contents)
1892     (setq basename (file-name-sans-extension 
1893                     (file-name-nondirectory buffer-file-name))
1894           texfile (concat tempname ".tex")
1895           bibfile (concat tempname ".bib"))
1896     
1897     ;; see if we have a bibliography, and insert the default one if not.
1898     (save-excursion
1899       (goto-char (point-min))
1900       (unless (re-search-forward "^bibliography:" (point-max) 'end)
1901         (insert (format "\nbibliography:%s" 
1902                         (mapconcat 'identity reftex-default-bibliography ",")))))
1903     (save-buffer)
1904
1905     ;; get a latex file and extract the references
1906     (org-latex-export-to-latex)
1907     (find-file texfile)
1908     (reftex-parse-all)
1909     (reftex-create-bibtex-file bibfile)
1910     (save-buffer)
1911     ;; save results of the references
1912     (setq results (buffer-string))
1913
1914     ;; kill buffers. these are named by basename, not full path
1915     (kill-buffer (concat basename ".bib"))
1916     (kill-buffer (concat basename ".tex"))
1917     (kill-buffer basename)
1918
1919     (delete-file bibfile)
1920     (delete-file texfile)
1921     (delete-file tempname)
1922
1923     ;; Now back to the original org buffer and insert the results
1924     (switch-to-buffer cb)
1925     (when (not (string= "" results))
1926       (save-excursion
1927         (goto-char (point-max))
1928         (insert "\n\n")
1929         (org-insert-heading)
1930         (insert (format " Bibtex entries
1931
1932 ,#+BEGIN_SRC text :tangle %s
1933 %s
1934 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
1935 #+END_SRC
1936
1937 ** Find bad cite links
1938 Depending on how you enter citations, you may have citations with no corresponding bibtex entry. This function finds them and gives you a clickable table to navigate to them.
1939
1940 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1941 (require 'cl)
1942
1943 (defun index (substring list)
1944   "return the index of string in a list of strings"
1945   (let ((i 0)
1946         (found nil))
1947     (dolist (arg list i)
1948       (if (string-match (concat "^" substring "$") arg)
1949           (progn 
1950             (setq found t)
1951             (return i)))
1952       (setq i (+ i 1)))
1953     ;; return counter if found, otherwise return nil
1954     (if found i nil)))
1955
1956
1957 (defun org-ref-find-bad-citations ()
1958   "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
1959
1960 Makes a new buffer with clickable links."
1961   (interactive)
1962   ;; generate the list of bibtex-keys and cited keys
1963   (let* ((bibtex-files (org-ref-find-bibliography))
1964          (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
1965          (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
1966          (bad-citations '()))
1967
1968     (org-element-map (org-element-parse-buffer) 'link
1969       (lambda (link)       
1970         (let ((plist (nth 1 link)))                          
1971           (when (equal (plist-get plist ':type) "cite")
1972             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
1973               (when (not (index key bibtex-keys))
1974                 (setq bad-citations (append bad-citations
1975                                             `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
1976                                                        key (buffer-name)(plist-get plist ':begin)))))
1977                 ))))))
1978
1979     (if bad-citations
1980       (progn
1981         (switch-to-buffer-other-window "*Missing citations*")
1982         (org-mode)
1983         (erase-buffer)
1984         (insert "* List of bad cite links\n")
1985         (insert (mapconcat 'identity bad-citations ""))
1986                                         ;(setq buffer-read-only t)
1987         (use-local-map (copy-keymap org-mode-map))
1988         (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
1989
1990       (when (get-buffer "*Missing citations*")
1991           (kill-buffer "*Missing citations*"))
1992       (message "No bad cite links found"))))
1993 #+END_SRC
1994
1995 ** Finding non-ascii characters
1996 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them. 
1997
1998 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1999 (defun org-ref-find-non-ascii-characters ()
2000   "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2001   (interactive)
2002   (occur "[^[:ascii:]]"))
2003 #+END_SRC
2004
2005 ** Resort a bibtex entry
2006 I like neat and orderly bibtex entries.That means the fields are in a standard order that I like. This function reorders the fields in an entry for articles, and makes sure the fields are in lowercase.
2007
2008 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2009 (defun org-ref-sort-bibtex-entry ()
2010   "sort fields of entry in standard order and downcase them"
2011   (interactive)
2012   (bibtex-beginning-of-entry)
2013   (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2014          (entry (bibtex-parse-entry))
2015          (entry-fields)
2016          (other-fields)
2017          (type (cdr (assoc "=type=" entry)))
2018          (key (cdr (assoc "=key=" entry))))
2019
2020     ;; these are the fields we want to order that are in this entry
2021     (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2022     ;; we do not want to reenter these fields
2023     (setq entry-fields (remove "=key=" entry-fields))
2024     (setq entry-fields (remove "=type=" entry-fields))
2025
2026     ;;these are the other fields in the entry
2027     (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2028
2029     (cond
2030      ;; right now we only resort articles
2031      ((string= (downcase type) "article") 
2032       (bibtex-kill-entry)
2033       (insert
2034        (concat "@article{" key ",\n" 
2035                (mapconcat  
2036                 (lambda (field) 
2037                   (when (member field entry-fields)
2038                     (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2039                (mapconcat 
2040                 (lambda (field) 
2041                   (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2042                "\n}\n\n"))
2043       (bibtex-find-entry key)
2044       (bibtex-fill-entry)
2045       (bibtex-clean-entry)
2046        ))))
2047 #+END_SRC
2048
2049 ** Clean a bibtex entry
2050    I like neat and orderly bibtex entries. This code will eventually replace the key with my style key, clean the entry, and sort the fields in the order I like them.
2051 see [[file:emacs-24.3/lisp/textmodes/bibtex.el::bibtex-autokey-before-presentation-function]] for how to set a function that checks for uniqueness of the key.
2052 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2053 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2054   "clean and replace the key in a bibtex function. When keep-key is t, do not replace it. You can use a prefix to specify the key should be kept"
2055   (interactive "P")
2056   (bibtex-beginning-of-entry) 
2057 (end-of-line)
2058   ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2059   (unless (string-match ",$" (thing-at-point 'line))
2060     (end-of-line)
2061     (insert ","))
2062
2063   ;; check for empty pages, and put eid or article id in its place
2064   (let ((entry (bibtex-parse-entry))
2065         (pages (bibtex-autokey-get-field "pages"))
2066         (year (bibtex-autokey-get-field "year"))
2067         (doi  (bibtex-autokey-get-field "doi"))
2068         ;; The Journal of Chemical Physics uses eid
2069         (eid (bibtex-autokey-get-field "eid")))
2070
2071     ;; replace http://dx.doi.org/ in doi. some journals put that in,
2072     ;; but we only want the doi.
2073     (when (string-match "^http://dx.doi.org/" doi)
2074       (bibtex-beginning-of-entry)
2075       (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2076       (bibtex-kill-field)
2077       (bibtex-make-field "doi")
2078       (backward-char)
2079       (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2080
2081     ;; asap articles often set year to 0, which messes up key
2082     ;; generation. fix that.
2083     (when (string= "0" year)  
2084       (bibtex-beginning-of-entry)
2085       (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2086       (bibtex-kill-field)
2087       (bibtex-make-field "year")
2088       (backward-char)
2089       (insert (read-string "Enter year: ")))
2090
2091     ;; fix pages if they are empty if there is an eid to put there.
2092     (when (string= "-" pages)
2093       (when eid   
2094         (bibtex-beginning-of-entry)
2095         ;; this seems like a clunky way to set the pages field.But I
2096         ;; cannot find a better way.
2097         (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2098         (bibtex-kill-field)
2099         (bibtex-make-field "pages")
2100         (backward-char)
2101         (insert eid)))
2102
2103     ;; replace naked & with \&
2104     (save-restriction
2105       (bibtex-narrow-to-entry)
2106       (bibtex-beginning-of-entry)
2107       (message "checking &")
2108       (replace-regexp " & " " \\\\& ")
2109       (widen))
2110
2111     ;; generate a key, and if it duplicates an existing key, edit it.
2112     (unless keep-key
2113       (let ((key (bibtex-generate-autokey)))
2114
2115         ;; first we delete the existing key
2116         (bibtex-beginning-of-entry)
2117         (re-search-forward bibtex-entry-maybe-empty-head)
2118         (if (match-beginning bibtex-key-in-head)
2119             (delete-region (match-beginning bibtex-key-in-head)
2120                            (match-end bibtex-key-in-head)))
2121         ;; check if the key is in the buffer
2122         (when (save-excursion
2123                 (bibtex-search-entry key))
2124           (save-excursion
2125             (bibtex-search-entry key)
2126             (bibtex-copy-entry-as-kill)
2127             (switch-to-buffer-other-window "*duplicate entry*")
2128             (bibtex-yank))
2129           (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2130
2131         (insert key)
2132         (kill-new key))) ;; save key for pasting            
2133
2134     ;; run hooks. each of these operates on the entry with no arguments.
2135     ;; this did not work like  i thought, it gives a symbolp error.
2136     ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2137     (mapcar (lambda (x)
2138               (save-restriction
2139                 (save-excursion
2140                   (funcall x))))
2141             org-ref-clean-bibtex-entry-hook)
2142     
2143     ;; sort fields within entry
2144     (org-ref-sort-bibtex-entry)
2145     ;; check for non-ascii characters
2146     (occur "[^[:ascii:]]")
2147     ))
2148 #+END_SRC
2149
2150 #+RESULTS:
2151 : org-ref-clean-bibtex-entry
2152
2153 ** Sort the entries in a citation link by year
2154 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2155
2156 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2157 (defun org-ref-get-citation-year (key)
2158   "get the year of an entry with key. Returns year as a string."
2159   (interactive)
2160   (let* ((results (org-ref-get-bibtex-key-and-file key))
2161          (bibfile (cdr results)))
2162     (with-temp-buffer
2163       (insert-file-contents bibfile)
2164       (bibtex-search-entry key nil 0)
2165       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2166         ))))
2167
2168 (defun org-ref-sort-citation-link ()
2169  "replace link at point with sorted link by year"
2170  (interactive)
2171  (let* ((object (org-element-context))   
2172         (type (org-element-property :type object))
2173         (begin (org-element-property :begin object))
2174         (end (org-element-property :end object))
2175         (link-string (org-element-property :path object))
2176         keys years data)
2177   (setq keys (org-ref-split-and-strip-string link-string))
2178   (setq years (mapcar 'org-ref-get-citation-year keys)) 
2179   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2180   (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2181   ;; now get the keys separated by commas
2182   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2183   ;; and replace the link with the sorted keys
2184   (cl--set-buffer-substring begin end (concat type ":" keys))))
2185 #+END_SRC
2186
2187 ** Sort entries in citation links with shift-arrow keys
2188 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2189 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2190 (defun org-ref-swap-keys (i j keys)
2191  "swap the keys in a list with index i and j"
2192  (let ((tempi (nth i keys)))
2193    (setf (nth i keys) (nth j keys))
2194    (setf (nth j keys) tempi))
2195   keys)
2196
2197 (defun org-ref-swap-citation-link (direction)
2198  "move citation at point in direction +1 is to the right, -1 to the left"
2199  (interactive)
2200  (let* ((object (org-element-context))   
2201         (type (org-element-property :type object))
2202         (begin (org-element-property :begin object))
2203         (end (org-element-property :end object))
2204         (link-string (org-element-property :path object))
2205         key keys i)
2206    ;;   We only want this to work on citation links
2207    (when (-contains? org-ref-cite-types type)
2208         (setq key (org-ref-get-bibtex-key-under-cursor))
2209         (setq keys (org-ref-split-and-strip-string link-string))
2210         (setq i (index key keys))  ;; defined in org-ref
2211         (if (> direction 0) ;; shift right
2212             (org-ref-swap-keys i (+ i 1) keys)
2213           (org-ref-swap-keys i (- i 1) keys))   
2214         (setq keys (mapconcat 'identity keys ","))
2215         ;; and replace the link with the sorted keys
2216         (cl--set-buffer-substring begin end (concat type ":" keys))
2217         ;; now go forward to key so we can move with the key
2218         (re-search-forward key) 
2219         (goto-char (match-beginning 0)))))
2220
2221 ;; add hooks to make it work
2222 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2223 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2224 #+END_SRC
2225 * Aliases
2226 I like convenience. Here are some aliases for faster typing.
2227
2228 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2229 (defalias 'oro 'org-ref-open-citation-at-point)
2230 (defalias 'orc 'org-ref-citation-at-point)
2231 (defalias 'orp 'org-ref-open-pdf-at-point)
2232 (defalias 'oru 'org-ref-open-url-at-point)
2233 (defalias 'orn 'org-ref-open-notes-at-point)
2234
2235 (defalias 'orib 'org-ref-insert-bibliography-link)
2236 (defalias 'oric 'org-ref-insert-cite-link)
2237 (defalias 'orir 'org-ref-insert-ref-link)
2238 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2239
2240 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2241 #+END_SRC
2242 * End of code
2243 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2244 (provide 'org-ref)
2245 #+END_SRC
2246
2247
2248 * Build                                                            :noexport:
2249
2250 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2251
2252 [[elisp:(org-babel-load-file "org-ref.org")]]
2253
2254
2255