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