]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.org
show children in notes.
[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     ;; you may click on the part before the citations. here we make
1100     ;; sure to move to the beginning so you get the first citation.
1101     (let ((cp (point)))
1102       (goto-char (org-element-property :begin object))
1103       (search-forward link-string (org-element-property :end object))
1104       (goto-char (match-beginning 0))
1105       ;; check if we clicked before the path and move as needed.
1106       (unless (< cp (point))
1107         (goto-char cp)))
1108         
1109     (if (not (org-element-property :contents-begin object))
1110         ;; this means no description in the link
1111         (progn    
1112           ;; we need the link path start and end
1113           (save-excursion
1114             (goto-char (org-element-property :begin object))
1115             (search-forward link-string nil nil 1)
1116             (setq link-string-beginning (match-beginning 0))
1117             (setq link-string-end (match-end 0)))
1118
1119           ;; The key is the text between commas, or the link boundaries
1120           (save-excursion
1121             (if (search-forward "," link-string-end t 1)
1122                 (setq key-end (- (match-end 0) 1)) ; we found a match
1123               (setq key-end link-string-end))) ; no comma found so take the end
1124           ;; and backward to previous comma from point which defines the start character
1125           (save-excursion
1126             (if (search-backward "," link-string-beginning 1 1)
1127                 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1128               (setq key-beginning link-string-beginning))) ; no match found
1129           ;; save the key we clicked on.
1130           (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1131           (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1132           bibtex-key)
1133       ;; link with description. assume only one key
1134       link-string)))
1135 #+END_SRC
1136
1137 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.
1138
1139 **** Getting the bibliographies
1140 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1141 (defun org-ref-find-bibliography ()
1142   "find the bibliography in the buffer.
1143 This function sets and returns cite-bibliography-files, which is a list of files
1144 either from bibliography:f1.bib,f2.bib
1145 \bibliography{f1,f2}
1146 internal bibliographies
1147
1148 falling back to what the user has set in org-ref-default-bibliography
1149 "
1150   (interactive)
1151   (catch 'result
1152     (save-excursion
1153       (goto-char (point-min))
1154       ;;  look for a bibliography link
1155       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1156         (setq org-ref-bibliography-files
1157               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1158         (throw 'result org-ref-bibliography-files))
1159
1160       
1161       ;; we did not find a bibliography link. now look for \bibliography
1162       (goto-char (point-min))
1163       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1164         ;; split, and add .bib to each file
1165         (setq org-ref-bibliography-files
1166               (mapcar (lambda (x) (concat x ".bib"))
1167                       (mapcar 'org-ref-strip-string 
1168                               (split-string (match-string 1) ","))))
1169         (throw 'result org-ref-bibliography-files))
1170
1171       ;; no bibliography found. maybe we need a biblatex addbibresource
1172       (goto-char (point-min))
1173       ;;  look for a bibliography link
1174       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1175         (setq org-ref-bibliography-files
1176               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1177         (throw 'result org-ref-bibliography-files))
1178           
1179       ;; we did not find anything. use defaults
1180       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1181
1182     ;; set reftex-default-bibliography so we can search
1183     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1184     org-ref-bibliography-files)
1185 #+END_SRC
1186
1187 **** Finding the bibliography file a key is in
1188 Now, we can see if an entry is in a file. 
1189
1190 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1191 (defun org-ref-key-in-file-p (key filename)
1192   "determine if the key is in the file"
1193   (interactive "skey: \nsFile: ")
1194   (save-current-buffer
1195     (let ((bibtex-files (list filename)))
1196       (bibtex-search-entry key t))))
1197 #+END_SRC
1198
1199 Finally, we want to know which file the key is in.
1200
1201 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1202 (defun org-ref-get-bibtex-key-and-file (&optional key)
1203   "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1204  (interactive)
1205  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1206        (file))
1207    (unless key
1208      (setq key (org-ref-get-bibtex-key-under-cursor)))
1209    (setq file     (catch 'result
1210                     (loop for file in org-ref-bibliography-files do
1211                           (if (org-ref-key-in-file-p key (file-truename file)) 
1212                               (throw 'result file)))))
1213    (cons key file)))
1214 #+END_SRC
1215
1216 **** Creating the menu for when we click on a key
1217      :PROPERTIES:
1218      :ID:       d7b7530b-802f-42b1-b61e-1e77da33e278
1219      :END:
1220 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.
1221
1222 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1223 (defun org-ref-get-menu-options ()
1224   "returns a dynamically determined string of options for the citation under point.
1225
1226 we check to see if there is pdf, and if the key actually exists in the bibliography"
1227   (interactive)
1228   (let* ((results (org-ref-get-bibtex-key-and-file))
1229          (key (car results))
1230          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1231          (bibfile (cdr results))
1232          m1 m2 m3 m4 m5 menu-string)
1233     (setq m1 (if bibfile                 
1234                  "(o)pen"
1235                "(No key found)"))
1236
1237     (setq m3 (if (file-exists-p pdf-file)
1238                  "(p)df"
1239                      "(No pdf found)"))
1240
1241     (setq m4 (if (not
1242                   (and bibfile
1243                        (string= (catch 'url
1244                                   (progn
1245
1246                                     (with-temp-buffer
1247                                       (insert-file-contents bibfile)
1248                                       (bibtex-search-entry key)
1249                                       (when (not
1250                                              (string= (setq url (bibtex-autokey-get-field "url")) ""))
1251                                         (throw 'url url))
1252
1253                                       (when (not
1254                                              (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1255                                         (throw 'url url))))) "")))
1256                "(u)rl" "(no url found)"))
1257     (setq m5 "(n)otes")
1258     (setq m2 (if bibfile
1259                  (progn
1260                    (setq citation (progn
1261                                     (with-temp-buffer
1262                                       (insert-file-contents bibfile)
1263                                       (bibtex-search-entry key)
1264                                       (org-ref-bib-citation))))
1265                    citation)
1266                "no key found"))
1267
1268     (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") "  "))
1269     menu-string))
1270 #+END_SRC
1271
1272 **** convenience functions to act on citation at point
1273      :PROPERTIES:
1274      :ID:       af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1275      :END:
1276 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.
1277
1278 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1279 (defun org-ref-open-pdf-at-point ()
1280   "open the pdf for bibtex key under point if it exists"
1281   (interactive)
1282   (let* ((results (org-ref-get-bibtex-key-and-file))
1283          (key (car results))
1284          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1285     (if (file-exists-p pdf-file)
1286         (org-open-file pdf-file)
1287 (message "no pdf found for %s" key))))
1288
1289
1290 (defun org-ref-open-url-at-point ()
1291   "open the url for bibtex key under point."
1292   (interactive)
1293   (let* ((results (org-ref-get-bibtex-key-and-file))
1294          (key (car results))
1295          (bibfile (cdr results)))
1296     (save-excursion
1297       (with-temp-buffer
1298         (insert-file-contents bibfile)
1299         (bibtex-search-entry key)
1300         ;; I like this better than bibtex-url which does not always find
1301         ;; the urls
1302         (catch 'done
1303           (let ((url (bibtex-autokey-get-field "url")))
1304             (when  url
1305               (browse-url url)
1306               (throw 'done nil)))
1307
1308           (let ((doi (bibtex-autokey-get-field "doi")))
1309             (when doi
1310               (if (string-match "^http" doi)
1311                   (browse-url doi)
1312                 (browse-url (format "http://dx.doi.org/%s" doi)))
1313               (throw 'done nil))))))))
1314
1315 (defun org-ref-open-notes-at-point ()
1316   "open the notes for bibtex key under point."
1317   (interactive)
1318   (let* ((results (org-ref-get-bibtex-key-and-file))
1319          (key (car results))
1320          (bibfile (cdr results)))
1321     (save-excursion
1322       (with-temp-buffer
1323         (insert-file-contents bibfile)
1324         (bibtex-search-entry key)
1325         (org-ref-open-bibtex-notes)))))
1326
1327 (defun org-ref-citation-at-point ()
1328   "give message of current citation at point"
1329   (interactive)
1330   (let* ((cb (current-buffer))
1331         (results (org-ref-get-bibtex-key-and-file))
1332         (key (car results))
1333         (bibfile (cdr results)))        
1334     (message "%s" (progn
1335                     (with-temp-buffer
1336                       (insert-file-contents bibfile)
1337                       (bibtex-search-entry key)
1338                       (org-ref-bib-citation))))))
1339
1340 (defun org-ref-open-citation-at-point ()
1341   "open bibtex file to key at point"
1342   (interactive)
1343   (let* ((cb (current-buffer))
1344         (results (org-ref-get-bibtex-key-and-file))
1345         (key (car results))
1346         (bibfile (cdr results)))
1347     (find-file bibfile)
1348     (bibtex-search-entry key)))
1349 #+END_SRC
1350
1351 **** the actual minibuffer menu
1352 Now, we create the menu.
1353
1354 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1355 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1356   "use a minibuffer to select options for the citation under point.
1357
1358 you select your option with a single key press."
1359   (interactive)
1360   (let* ((choice (read-char (org-ref-get-menu-options)))
1361          (results (org-ref-get-bibtex-key-and-file))
1362          (key (car results))
1363          (cb (current-buffer))
1364          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1365          (bibfile (cdr results)))
1366
1367     (cond
1368      ;; open
1369      ((= choice ?o)
1370       (find-file bibfile)
1371        (bibtex-search-entry key))
1372
1373      ;; cite
1374      ((= choice ?c)
1375       (org-ref-citation-at-point))
1376       
1377
1378      ;; quit
1379      ((or 
1380       (= choice ?q) ; q
1381       (= choice ?\ )) ; space
1382       ;; this clears the minibuffer
1383       (message ""))
1384
1385      ;; pdf
1386      ((= choice ?p)
1387       (org-ref-open-pdf-at-point))
1388
1389      ;; notes
1390      ((= choice ?n)
1391       (org-ref-open-notes-at-point))
1392
1393      ;; url
1394      ((= choice ?u)
1395       (org-ref-open-url-at-point))
1396
1397      ;; anything else we just quit.
1398      (t (message "")))))
1399     
1400 #+END_SRC
1401
1402 *** A function to format a cite link
1403
1404 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.
1405
1406 #+BEGIN_SRC emacs-lisp  :tangle no
1407 ;(defun org-ref-cite-link-format (keyword desc format)
1408 ;   (cond
1409 ;    ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1410 ;    ((eq format 'latex)
1411 ;     (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1412 ;            (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1413 ;            "}"))))
1414 #+END_SRC
1415
1416 *** The actual cite link
1417 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1418
1419 #+BEGIN_SRC emacs-lisp :tangle no
1420 ;(org-add-link-type
1421 ; "cite"
1422 ; 'org-ref-cite-onclick-minibuffer-menu
1423 ; 'org-ref-cite-link-format)
1424 #+END_SRC
1425
1426 *** Automatic definition of the cite links
1427 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. 
1428
1429 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1430 (defmacro org-ref-make-completion-function (type)
1431   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1432      (interactive)
1433      (format "%s:%s" 
1434              ,type
1435              (completing-read 
1436               "bibtex key: " 
1437               (let ((bibtex-files (org-ref-find-bibliography)))
1438                 (bibtex-global-key-alist))))))
1439 #+END_SRC
1440
1441 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.
1442
1443 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1444 (defmacro org-ref-make-format-function (type)
1445   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1446      (cond
1447       ((eq format 'org)
1448        (mapconcat
1449         (lambda (key)
1450           (format "[[#%s][%s]]" key key))
1451         (org-ref-split-and-strip-string keyword) ","))
1452
1453       ((eq format 'ascii)
1454        (concat "["
1455                (mapconcat
1456                 (lambda (key)
1457                   (format "%s" key))
1458                 (org-ref-split-and-strip-string keyword) ",") "]"))
1459         
1460       ((eq format 'html) 
1461        (mapconcat 
1462         (lambda (key) 
1463           (format "<a href=\"#%s\">%s</a>" key key))
1464         (org-ref-split-and-strip-string keyword) ","))
1465
1466       ((eq format 'latex)
1467        (if (string= (substring type -1) "s")
1468            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1469            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1470                                          (org-ref-split-and-strip-string keyword) ""))
1471          ;; bibtex format
1472        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1473                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1474                "}"))))))
1475 #+END_SRC
1476
1477
1478
1479 We create the links by mapping the function onto the list of defined link types. 
1480
1481 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1482 (defun org-ref-format-citation-description (desc)
1483   "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 ::."
1484   (interactive)
1485   (cond
1486    ((string-match "::" desc)
1487     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1488    (t (format "[%s]" desc))))
1489
1490 (defun org-ref-define-citation-link (type &optional key)
1491   "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1492 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z, 
1493 and the completion function."
1494   (interactive "sCitation Type: \ncKey: ")
1495
1496   ;; create the formatting function
1497   (eval `(org-ref-make-format-function ,type))
1498
1499   (eval-expression 
1500    `(org-add-link-type 
1501      ,type
1502      'org-ref-cite-onclick-minibuffer-menu
1503      (quote ,(intern (format "org-ref-format-%s" type)))))
1504
1505   ;; create the completion function
1506   (eval `(org-ref-make-completion-function ,type))
1507   
1508   ;; store new type so it works with adding citations, which checks
1509   ;; for existence in this list
1510   (add-to-list 'org-ref-cite-types type)
1511
1512   ;; and finally if a key is specified, we modify the reftex menu
1513   (when key
1514     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1515           (append (nth 2 (assoc 'org reftex-cite-format-builtin)) 
1516                   `((,key  . ,(concat type ":%l")))))))
1517
1518 ;; create all the link types and their completion functions
1519 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1520 #+END_SRC
1521
1522 *** org-ref-insert-cite-link
1523 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.
1524
1525 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1526 (defun org-ref-insert-cite-link (alternative-cite)
1527   "Insert a default citation link using reftex. If you are on a link, it
1528 appends to the end of the link, otherwise, a new link is
1529 inserted. Use a prefix arg to get a menu of citation types."
1530   (interactive "P")
1531   (org-ref-find-bibliography)
1532   (let* ((object (org-element-context))
1533          (link-string-beginning (org-element-property :begin object))
1534          (link-string-end (org-element-property :end object))
1535          (path (org-element-property :path object)))  
1536
1537     (if (not alternative-cite)
1538         
1539         (cond
1540          ;; case where we are in a link
1541          ((and (equal (org-element-type object) 'link) 
1542                (-contains? org-ref-cite-types (org-element-property :type object)))
1543           (goto-char link-string-end)
1544           ;; sometimes there are spaces at the end of the link
1545           ;; this code moves point pack until no spaces are there
1546           (while (looking-back " ") (backward-char))  
1547           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1548
1549          ;; We are next to a link, and we want to append
1550          ((save-excursion 
1551             (backward-char)
1552             (and (equal (org-element-type (org-element-context)) 'link) 
1553                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1554           (while (looking-back " ") (backward-char))  
1555           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1556
1557          ;; insert fresh link
1558          (t 
1559           (insert 
1560            (concat org-ref-default-citation-link 
1561                    ":" 
1562                    (mapconcat 'identity (reftex-citation t) ",")))))
1563
1564       ;; you pressed a C-u so we run this code
1565       (reftex-citation)))
1566   )
1567 #+END_SRC
1568
1569 #+RESULTS:
1570 : org-ref-insert-cite-link
1571
1572 *** Completion in cite links
1573 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.
1574
1575 #+BEGIN_SRC emacs-lisp  :tangle no
1576 (defun org-cite-complete-link (&optional arg)
1577   "Completion function for cite links"
1578   (format "%s:%s" 
1579           org-ref-default-citation-link
1580           (completing-read 
1581            "bibtex key: " 
1582            (let ((bibtex-files (org-ref-find-bibliography)))
1583              (bibtex-global-key-alist)))))
1584 #+END_SRC
1585
1586 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1587
1588 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1589 (defun org-ref-insert-cite-with-completion (type)
1590   "Insert a cite link with completion"
1591   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1592   (insert (funcall (intern (format "org-%s-complete-link" type)))))
1593 #+END_SRC
1594
1595 ** Storing links to a bibtex entry
1596 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.
1597
1598 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1599 (defun org-ref-store-bibtex-entry-link ()
1600   "Save a citation link to the current bibtex entry. Saves in the default link type."
1601   (interactive)
1602   (let ((link (concat org-ref-default-citation-link 
1603                  ":"   
1604                  (save-excursion
1605                    (bibtex-beginning-of-entry)
1606                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1607     (message "saved %s" link)
1608     (push (list link) org-stored-links)
1609     (car org-stored-links)))
1610 #+END_SRC
1611
1612
1613 * Utilities
1614 ** create simple text citation from bibtex entry
1615
1616 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1617 (defun org-ref-bib-citation ()
1618   "from a bibtex entry, create and return a simple citation string."
1619
1620   (bibtex-beginning-of-entry)
1621   (let* ((cb (current-buffer))
1622          (bibtex-expand-strings t)
1623          (entry (loop for (key . value) in (bibtex-parse-entry t)
1624                       collect (cons (downcase key) value)))
1625          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1626          (year  (reftex-get-bib-field "year" entry))
1627          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1628          (key (reftex-get-bib-field "=key=" entry))
1629          (journal (reftex-get-bib-field "journal" entry))
1630          (volume (reftex-get-bib-field "volume" entry))
1631          (pages (reftex-get-bib-field "pages" entry))
1632          (doi (reftex-get-bib-field "doi" entry))
1633          (url (reftex-get-bib-field "url" entry))
1634          )
1635     ;;authors, "title", Journal, vol(iss):pages (year).
1636     (format "%s, \"%s\", %s, %s:%s (%s)"
1637             author title journal  volume pages year)))
1638 #+END_SRC
1639
1640 #+RESULTS:
1641 : org-ref-bib-citation
1642
1643
1644 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1645 (defun org-ref-bib-html-citation ()
1646   "from a bibtex entry, create and return a simple citation with html links."
1647
1648   (bibtex-beginning-of-entry)
1649   (let* ((cb (current-buffer))
1650          (bibtex-expand-strings t)
1651          (entry (loop for (key . value) in (bibtex-parse-entry t)
1652                       collect (cons (downcase key) value)))
1653          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1654          (year  (reftex-get-bib-field "year" entry))
1655          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1656          (key (reftex-get-bib-field "=key=" entry))
1657          (journal (reftex-get-bib-field "journal" entry))
1658          (volume (reftex-get-bib-field "volume" entry))
1659          (pages (reftex-get-bib-field "pages" entry))
1660          (doi (reftex-get-bib-field "doi" entry))
1661          (url (reftex-get-bib-field "url" entry))
1662          )
1663     ;;authors, "title", Journal, vol(iss):pages (year).
1664     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1665                     author title journal  volume pages year)
1666             (when url (format " <a href=\"%s\">link</a>" url))
1667             (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1668     ))
1669 #+END_SRC
1670
1671 ** open pdf from bibtex
1672 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1673 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1674 (defun org-ref-open-bibtex-pdf ()
1675   "open pdf for a bibtex entry, if it exists. assumes point is in
1676 the entry of interest in the bibfile. but does not check that."
1677   (interactive)
1678   (save-excursion
1679     (bibtex-beginning-of-entry)
1680     (let* ((bibtex-expand-strings t)
1681            (entry (bibtex-parse-entry t))
1682            (key (reftex-get-bib-field "=key=" entry))
1683            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1684       (message "%s" pdf)
1685       (if (file-exists-p pdf)
1686           (org-open-link-from-string (format "[[file:%s]]" pdf))
1687         (ding)))))
1688 #+END_SRC
1689
1690 ** open notes from bibtex
1691 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1692
1693 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1694 (defun org-ref-open-bibtex-notes ()
1695   "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1696
1697 I never did figure out how to use reftex to make this happen
1698 non-interactively. the reftex-format-citation function did not
1699 work perfectly; there were carriage returns in the strings, and
1700 it did not put the key where it needed to be. so, below I replace
1701 the carriage returns and extra spaces with a single space and
1702 construct the heading by hand."
1703   (interactive)
1704
1705   (bibtex-beginning-of-entry)
1706   (let* ((cb (current-buffer))
1707          (bibtex-expand-strings t)
1708          (entry (loop for (key . value) in (bibtex-parse-entry t)
1709                       collect (cons (downcase key) value)))
1710          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1711          (year  (reftex-get-bib-field "year" entry))
1712          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1713          (key (reftex-get-bib-field "=key=" entry))
1714          (journal (reftex-get-bib-field "journal" entry))
1715          (volume (reftex-get-bib-field "volume" entry))
1716          (pages (reftex-get-bib-field "pages" entry))
1717          (doi (reftex-get-bib-field "doi" entry))
1718          (url (reftex-get-bib-field "url" entry))
1719          )
1720
1721     ;; save key to clipboard to make saving pdf later easier by pasting.
1722     (with-temp-buffer
1723       (insert key)
1724       (kill-ring-save (point-min) (point-max)))
1725     
1726     ;; now look for entry in the notes file
1727     (if  org-ref-bibliography-notes
1728         (find-file org-ref-bibliography-notes)
1729       (error "org-ref-bib-bibliography-notes is not set to anything"))
1730     
1731     (goto-char (point-min))
1732     ;; put new entry in notes if we don't find it.
1733     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1734         (progn
1735           (org-show-entry)
1736           (show-children)
1737           (outline-previous-visible-heading 1)
1738           (recenter-top-bottom 0))
1739       ;; no entry found, so add one     
1740       (insert (format "\n** TODO %s - %s" year title))
1741       (insert (format"
1742  :PROPERTIES:
1743   :Custom_ID: %s
1744   :AUTHOR: %s
1745   :JOURNAL: %s
1746   :YEAR: %s
1747   :VOLUME: %s
1748   :PAGES: %s
1749   :DOI: %s
1750   :URL: %s
1751  :END:
1752 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1753 key author journal year volume pages doi url key org-ref-pdf-directory key))
1754 (save-buffer))))
1755 #+END_SRC
1756
1757 ** open url in browser from bibtex
1758
1759 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1760
1761 + 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.
1762
1763 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1764 (defun org-ref-open-in-browser ()
1765   "Open the bibtex entry at point in a browser using the url field or doi field"
1766 (interactive)
1767 (save-excursion
1768   (bibtex-beginning-of-entry)
1769   (catch 'done
1770     (let ((url (bibtex-autokey-get-field "url")))
1771       (when  url
1772         (browse-url url)
1773         (throw 'done nil)))
1774
1775     (let ((doi (bibtex-autokey-get-field "doi")))
1776       (when doi
1777         (if (string-match "^http" doi)
1778             (browse-url doi)
1779           (browse-url (format "http://dx.doi.org/%s" doi)))
1780         (throw 'done nil)))
1781     (message "No url or doi found"))))
1782 #+END_SRC
1783
1784 ** citeulike
1785    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.
1786
1787 *** function to upload bibtex to citeulike
1788
1789 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1790 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1791   "with point in  a bibtex entry get bibtex string and submit to citeulike.
1792
1793 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1794   (interactive)
1795   (message "uploading to citeulike")
1796   (save-restriction
1797     (bibtex-narrow-to-entry)
1798     (let ((startpos (point-min))
1799           (endpos (point-max))
1800           (bibtex-string (buffer-string))
1801           (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1802       (with-temp-buffer (insert bibtex-string)
1803                         (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1804 #+END_SRC
1805
1806 *** The upload script
1807 Here is the python script for uploading. 
1808
1809 *************** TODO document how to get the cookies
1810 *************** END
1811
1812
1813 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1814 #!python
1815 import pickle, requests, sys
1816
1817 # reload cookies
1818 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1819     cookies = pickle.load(f)
1820
1821 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1822
1823 bibtex = sys.stdin.read()
1824
1825 data = {'pasted':bibtex,
1826         'to_read':2,
1827         'tag_parsing':'simple',
1828         'strip_brackets':'no',
1829         'update_id':'bib-key',
1830         'btn_bibtex':'Import BibTeX file ...'}
1831
1832 headers = {'content-type': 'multipart/form-data',
1833            'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1834
1835 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1836 print r
1837 #+END_SRC
1838
1839 ** Build a pdf from a bibtex file
1840    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.
1841
1842 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1843 (defun org-ref-build-full-bibliography ()
1844   "build pdf of all bibtex entries, and open it."
1845   (interactive)
1846   (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1847         (bib-base (file-name-sans-extension bibfile))
1848         (texfile (concat bib-base ".tex"))
1849         (pdffile (concat bib-base ".pdf")))
1850     (find-file texfile)
1851     (erase-buffer)
1852     (insert (format "\\documentclass[12pt]{article}
1853 \\usepackage[version=3]{mhchem}
1854 \\usepackage{url}
1855 \\usepackage[numbers]{natbib}
1856 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1857 \\usepackage{doi}
1858 \\begin{document}
1859 \\nocite{*}
1860 \\bibliographystyle{unsrtnat}
1861 \\bibliography{%s}
1862 \\end{document}" bib-base))
1863     (save-buffer)
1864     (shell-command (concat "pdflatex " bib-base))
1865     (shell-command (concat "bibtex " bib-base))
1866     (shell-command (concat "pdflatex " bib-base))
1867     (shell-command (concat "pdflatex " bib-base))
1868     (kill-buffer texfile)
1869     (org-open-file pdffile)
1870     )) 
1871 #+END_SRC
1872
1873 ** Extract bibtex entries cited in an org-file
1874 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.
1875
1876 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1877 (defun org-ref-extract-bibtex-entries ()
1878   "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1879
1880 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1881   (interactive)
1882   (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1883          (tempname (make-temp-file "extract-bib"))
1884          (contents (buffer-string))
1885          (cb (current-buffer))
1886          basename texfile bibfile results)
1887     
1888     ;; open tempfile and insert org-buffer contents
1889     (find-file tempname)
1890     (insert contents)
1891     (setq basename (file-name-sans-extension 
1892                     (file-name-nondirectory buffer-file-name))
1893           texfile (concat tempname ".tex")
1894           bibfile (concat tempname ".bib"))
1895     
1896     ;; see if we have a bibliography, and insert the default one if not.
1897     (save-excursion
1898       (goto-char (point-min))
1899       (unless (re-search-forward "^bibliography:" (point-max) 'end)
1900         (insert (format "\nbibliography:%s" 
1901                         (mapconcat 'identity reftex-default-bibliography ",")))))
1902     (save-buffer)
1903
1904     ;; get a latex file and extract the references
1905     (org-latex-export-to-latex)
1906     (find-file texfile)
1907     (reftex-parse-all)
1908     (reftex-create-bibtex-file bibfile)
1909     (save-buffer)
1910     ;; save results of the references
1911     (setq results (buffer-string))
1912
1913     ;; kill buffers. these are named by basename, not full path
1914     (kill-buffer (concat basename ".bib"))
1915     (kill-buffer (concat basename ".tex"))
1916     (kill-buffer basename)
1917
1918     (delete-file bibfile)
1919     (delete-file texfile)
1920     (delete-file tempname)
1921
1922     ;; Now back to the original org buffer and insert the results
1923     (switch-to-buffer cb)
1924     (when (not (string= "" results))
1925       (save-excursion
1926         (goto-char (point-max))
1927         (insert "\n\n")
1928         (org-insert-heading)
1929         (insert (format " Bibtex entries
1930
1931 ,#+BEGIN_SRC text :tangle %s
1932 %s
1933 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
1934 #+END_SRC
1935
1936 ** Find bad cite links
1937 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.
1938
1939 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1940 (require 'cl)
1941
1942 (defun index (substring list)
1943   "return the index of string in a list of strings"
1944   (let ((i 0)
1945         (found nil))
1946     (dolist (arg list i)
1947       (if (string-match (concat "^" substring "$") arg)
1948           (progn 
1949             (setq found t)
1950             (return i)))
1951       (setq i (+ i 1)))
1952     ;; return counter if found, otherwise return nil
1953     (if found i nil)))
1954
1955
1956 (defun org-ref-find-bad-citations ()
1957   "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
1958
1959 Makes a new buffer with clickable links."
1960   (interactive)
1961   ;; generate the list of bibtex-keys and cited keys
1962   (let* ((bibtex-files (org-ref-find-bibliography))
1963          (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
1964          (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
1965          (bad-citations '()))
1966
1967     (org-element-map (org-element-parse-buffer) 'link
1968       (lambda (link)       
1969         (let ((plist (nth 1 link)))                          
1970           (when (equal (plist-get plist ':type) "cite")
1971             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
1972               (when (not (index key bibtex-keys))
1973                 (setq bad-citations (append bad-citations
1974                                             `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
1975                                                        key (buffer-name)(plist-get plist ':begin)))))
1976                 ))))))
1977
1978     (if bad-citations
1979       (progn
1980         (switch-to-buffer-other-window "*Missing citations*")
1981         (org-mode)
1982         (erase-buffer)
1983         (insert "* List of bad cite links\n")
1984         (insert (mapconcat 'identity bad-citations ""))
1985                                         ;(setq buffer-read-only t)
1986         (use-local-map (copy-keymap org-mode-map))
1987         (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
1988
1989       (when (get-buffer "*Missing citations*")
1990           (kill-buffer "*Missing citations*"))
1991       (message "No bad cite links found"))))
1992 #+END_SRC
1993
1994 ** Finding non-ascii characters
1995 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them. 
1996
1997 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1998 (defun org-ref-find-non-ascii-characters ()
1999   "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2000   (interactive)
2001   (occur "[^[:ascii:]]"))
2002 #+END_SRC
2003
2004 ** Resort a bibtex entry
2005 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.
2006
2007 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2008 (defun org-ref-sort-bibtex-entry ()
2009   "sort fields of entry in standard order and downcase them"
2010   (interactive)
2011   (bibtex-beginning-of-entry)
2012   (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2013          (entry (bibtex-parse-entry))
2014          (entry-fields)
2015          (other-fields)
2016          (type (cdr (assoc "=type=" entry)))
2017          (key (cdr (assoc "=key=" entry))))
2018
2019     ;; these are the fields we want to order that are in this entry
2020     (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2021     ;; we do not want to reenter these fields
2022     (setq entry-fields (remove "=key=" entry-fields))
2023     (setq entry-fields (remove "=type=" entry-fields))
2024
2025     ;;these are the other fields in the entry
2026     (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2027
2028     (cond
2029      ;; right now we only resort articles
2030      ((string= (downcase type) "article") 
2031       (bibtex-kill-entry)
2032       (insert
2033        (concat "@article{" key ",\n" 
2034                (mapconcat  
2035                 (lambda (field) 
2036                   (when (member field entry-fields)
2037                     (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2038                (mapconcat 
2039                 (lambda (field) 
2040                   (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2041                "\n}\n\n"))
2042       (bibtex-find-entry key)
2043       (bibtex-fill-entry)
2044       (bibtex-clean-entry)
2045        ))))
2046 #+END_SRC
2047
2048 ** Clean a bibtex entry
2049    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.
2050 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.
2051 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2052 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2053   "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"
2054   (interactive "P")
2055   (bibtex-beginning-of-entry) 
2056 (end-of-line)
2057   ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2058   (unless (string-match ",$" (thing-at-point 'line))
2059     (end-of-line)
2060     (insert ","))
2061
2062   ;; check for empty pages, and put eid or article id in its place
2063   (let ((entry (bibtex-parse-entry))
2064         (pages (bibtex-autokey-get-field "pages"))
2065         (year (bibtex-autokey-get-field "year"))
2066         (doi  (bibtex-autokey-get-field "doi"))
2067         ;; The Journal of Chemical Physics uses eid
2068         (eid (bibtex-autokey-get-field "eid")))
2069
2070     ;; replace http://dx.doi.org/ in doi. some journals put that in,
2071     ;; but we only want the doi.
2072     (when (string-match "^http://dx.doi.org/" doi)
2073       (bibtex-beginning-of-entry)
2074       (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2075       (bibtex-kill-field)
2076       (bibtex-make-field "doi")
2077       (backward-char)
2078       (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2079
2080     ;; asap articles often set year to 0, which messes up key
2081     ;; generation. fix that.
2082     (when (string= "0" year)  
2083       (bibtex-beginning-of-entry)
2084       (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2085       (bibtex-kill-field)
2086       (bibtex-make-field "year")
2087       (backward-char)
2088       (insert (read-string "Enter year: ")))
2089
2090     ;; fix pages if they are empty if there is an eid to put there.
2091     (when (string= "-" pages)
2092       (when eid   
2093         (bibtex-beginning-of-entry)
2094         ;; this seems like a clunky way to set the pages field.But I
2095         ;; cannot find a better way.
2096         (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2097         (bibtex-kill-field)
2098         (bibtex-make-field "pages")
2099         (backward-char)
2100         (insert eid)))
2101
2102     ;; replace naked & with \&
2103     (save-restriction
2104       (bibtex-narrow-to-entry)
2105       (bibtex-beginning-of-entry)
2106       (message "checking &")
2107       (replace-regexp " & " " \\\\& ")
2108       (widen))
2109
2110     ;; generate a key, and if it duplicates an existing key, edit it.
2111     (unless keep-key
2112       (let ((key (bibtex-generate-autokey)))
2113
2114         ;; first we delete the existing key
2115         (bibtex-beginning-of-entry)
2116         (re-search-forward bibtex-entry-maybe-empty-head)
2117         (if (match-beginning bibtex-key-in-head)
2118             (delete-region (match-beginning bibtex-key-in-head)
2119                            (match-end bibtex-key-in-head)))
2120         ;; check if the key is in the buffer
2121         (when (save-excursion
2122                 (bibtex-search-entry key))
2123           (save-excursion
2124             (bibtex-search-entry key)
2125             (bibtex-copy-entry-as-kill)
2126             (switch-to-buffer-other-window "*duplicate entry*")
2127             (bibtex-yank))
2128           (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2129
2130         (insert key)
2131         (kill-new key))) ;; save key for pasting            
2132
2133     ;; run hooks. each of these operates on the entry with no arguments.
2134     ;; this did not work like  i thought, it gives a symbolp error.
2135     ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2136     (mapcar (lambda (x)
2137               (save-restriction
2138                 (save-excursion
2139                   (funcall x))))
2140             org-ref-clean-bibtex-entry-hook)
2141     
2142     ;; sort fields within entry
2143     (org-ref-sort-bibtex-entry)
2144     ;; check for non-ascii characters
2145     (occur "[^[:ascii:]]")
2146     ))
2147 #+END_SRC
2148
2149 #+RESULTS:
2150 : org-ref-clean-bibtex-entry
2151
2152 ** Sort the entries in a citation link by year
2153 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2154
2155 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2156 (defun org-ref-get-citation-year (key)
2157   "get the year of an entry with key. Returns year as a string."
2158   (interactive)
2159   (let* ((results (org-ref-get-bibtex-key-and-file key))
2160          (bibfile (cdr results)))
2161     (with-temp-buffer
2162       (insert-file-contents bibfile)
2163       (bibtex-search-entry key nil 0)
2164       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2165         ))))
2166
2167 (defun org-ref-sort-citation-link ()
2168  "replace link at point with sorted link by year"
2169  (interactive)
2170  (let* ((object (org-element-context))   
2171         (type (org-element-property :type object))
2172         (begin (org-element-property :begin object))
2173         (end (org-element-property :end object))
2174         (link-string (org-element-property :path object))
2175         keys years data)
2176   (setq keys (org-ref-split-and-strip-string link-string))
2177   (setq years (mapcar 'org-ref-get-citation-year keys)) 
2178   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2179   (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2180   ;; now get the keys separated by commas
2181   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2182   ;; and replace the link with the sorted keys
2183   (cl--set-buffer-substring begin end (concat type ":" keys))))
2184 #+END_SRC
2185
2186 ** Sort entries in citation links with shift-arrow keys
2187 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2188 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2189 (defun org-ref-swap-keys (i j keys)
2190  "swap the keys in a list with index i and j"
2191  (let ((tempi (nth i keys)))
2192    (setf (nth i keys) (nth j keys))
2193    (setf (nth j keys) tempi))
2194   keys)
2195
2196 (defun org-ref-swap-citation-link (direction)
2197  "move citation at point in direction +1 is to the right, -1 to the left"
2198  (interactive)
2199  (let* ((object (org-element-context))   
2200         (type (org-element-property :type object))
2201         (begin (org-element-property :begin object))
2202         (end (org-element-property :end object))
2203         (link-string (org-element-property :path object))
2204         key keys i)
2205    ;;   We only want this to work on citation links
2206    (when (-contains? org-ref-cite-types type)
2207         (setq key (org-ref-get-bibtex-key-under-cursor))
2208         (setq keys (org-ref-split-and-strip-string link-string))
2209         (setq i (index key keys))  ;; defined in org-ref
2210         (if (> direction 0) ;; shift right
2211             (org-ref-swap-keys i (+ i 1) keys)
2212           (org-ref-swap-keys i (- i 1) keys))   
2213         (setq keys (mapconcat 'identity keys ","))
2214         ;; and replace the link with the sorted keys
2215         (cl--set-buffer-substring begin end (concat type ":" keys))
2216         ;; now go forward to key so we can move with the key
2217         (re-search-forward key) 
2218         (goto-char (match-beginning 0)))))
2219
2220 ;; add hooks to make it work
2221 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2222 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2223 #+END_SRC
2224 * Aliases
2225 I like convenience. Here are some aliases for faster typing.
2226
2227 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2228 (defalias 'oro 'org-ref-open-citation-at-point)
2229 (defalias 'orc 'org-ref-citation-at-point)
2230 (defalias 'orp 'org-ref-open-pdf-at-point)
2231 (defalias 'oru 'org-ref-open-url-at-point)
2232 (defalias 'orn 'org-ref-open-notes-at-point)
2233
2234 (defalias 'orib 'org-ref-insert-bibliography-link)
2235 (defalias 'oric 'org-ref-insert-cite-link)
2236 (defalias 'orir 'org-ref-insert-ref-link)
2237 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2238
2239 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2240 #+END_SRC
2241 * End of code
2242 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2243 (provide 'org-ref)
2244 #+END_SRC
2245
2246
2247 * Build                                                            :noexport:
2248
2249 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2250
2251 [[elisp:(org-babel-load-file "org-ref.org")]]
2252
2253
2254