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