]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.org
add nobibliography link
[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 Believe it or not, sometimes it makes sense /not/ to include the bibliography in a document (e.g. when you are required to submit references as a separate file). To generate the references,  in another file, you must make a little tex file with these contents, and then compile it.
592
593 #+BEGIN_LaTeX
594   \input{project-description.bbl}
595 #+END_LaTeX
596
597 Here, we make a =nobibliography= link that acts like the bibliography, enables creation of the bbl file, but does not put an actual bibliography in the file.
598
599 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
600 (org-add-link-type "nobibliography"
601                    ;; this code is run on clicking. The bibliography
602                    ;; may contain multiple files. this code finds the
603                    ;; one you clicked on and opens it.
604                    (lambda (link-string)        
605                        ;; get link-string boundaries
606                        ;; we have to go to the beginning of the line, and then search forward
607                        
608                      (let* ((bibfile)
609                             ;; object is the link you clicked on
610                             (object (org-element-context))
611  
612                             (link-string-beginning) 
613                             (link-string-end))
614
615                      (save-excursion
616                        (goto-char (org-element-property :begin object))
617                        (search-forward link-string nil nil 1)
618                        (setq link-string-beginning (match-beginning 0))
619                        (setq link-string-end (match-end 0)))
620
621                        ;; We set the reftex-default-bibliography
622                        ;; here. it should be a local variable only in
623                        ;; the current buffer. We need this for using
624                        ;; reftex to do citations.
625                        (set (make-local-variable 'reftex-default-bibliography) 
626                             (split-string (org-element-property :path object) ","))
627
628                        ;; now if we have comma separated bibliographies
629                        ;; we find the one clicked on. we want to
630                        ;; search forward to next comma from point
631                        (save-excursion
632                          (if (search-forward "," link-string-end 1 1)
633                              (setq key-end (- (match-end 0) 1)) ; we found a match
634                            (setq key-end (point)))) ; no comma found so take the point
635                        ;; and backward to previous comma from point
636                        (save-excursion
637                          (if (search-backward "," link-string-beginning 1 1)
638                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
639                            (setq key-beginning (point)))) ; no match found
640                        ;; save the key we clicked on.
641                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
642                        (find-file bibfile))) ; open file on click
643
644                      ;; formatting code
645                    (lambda (keyword desc format)
646                      (cond
647                       ((eq format 'org) (org-ref-get-org-bibliography))
648                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
649                       ((eq format 'html) (org-ref-get-html-bibliography))
650                       ((eq format 'latex)
651                        ;; write out the latex bibliography command                     
652
653 ;                      (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
654 ;                              (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
655 ;                                                                                (mapcar 'expand-file-name
656 ;                                                                                        (split-string keyword ","))
657 ;                                                                                ",")))
658
659                        (format "\\nobibliography{%s}"
660                                (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
661                                                                                  (mapcar 'expand-file-name
662                                                                                          (split-string keyword ","))
663                                                                                  ",")))
664
665                        ))))                                                                            
666 #+END_SRC
667
668 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
669 (org-add-link-type "printbibliography"
670                    (lambda (arg) (message "Nothing implemented for clicking here."))
671                    (lambda (keyword desc format)
672                      (cond
673                       ((eq format 'org) (org-ref-get-org-bibliography))
674                       ((eq format 'html) (org-ref-get-html-bibliography))
675                       ((eq format 'latex)
676                        ;; write out the biblatex bibliography command
677                        "\\printbibliography"))
678 ))
679 #+END_SRC
680
681 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, ...
682
683 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
684 (org-add-link-type "bibliographystyle"
685                    (lambda (arg) (message "Nothing implemented for clicking here."))
686                    (lambda (keyword desc format)
687                      (cond
688                       ((eq format 'latex)
689                        ;; write out the latex bibliography command
690                        (format "\\bibliographystyle{%s}" keyword)))))
691 #+END_SRC
692
693 *** Completion for bibliography link
694 It would be nice 
695
696 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
697 (defun org-bibliography-complete-link (&optional arg)
698  (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
699
700 (defun org-ref-insert-bibliography-link ()
701   "insert a bibliography with completion"
702   (interactive)
703   (insert (org-bibliography-complete-link)))
704 #+END_SRC
705
706 ** addbibresource
707 This is apparently used for biblatex.
708 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
709 (org-add-link-type "addbibresource"
710                    ;; this code is run on clicking. The addbibresource
711                    ;; may contain multiple files. this code finds the
712                    ;; one you clicked on and opens it.
713                    (lambda (link-string)        
714                        ;; get link-string boundaries
715                        ;; we have to go to the beginning of the line, and then search forward
716                        
717                      (let* ((bibfile)
718                             ;; object is the link you clicked on
719                             (object (org-element-context))
720  
721                             (link-string-beginning) 
722                             (link-string-end))
723
724                      (save-excursion
725                        (goto-char (org-element-property :begin object))
726                        (search-forward link-string nil nil 1)
727                        (setq link-string-beginning (match-beginning 0))
728                        (setq link-string-end (match-end 0)))
729
730                        ;; We set the reftex-default-addbibresource
731                        ;; here. it should be a local variable only in
732                        ;; the current buffer. We need this for using
733                        ;; reftex to do citations.
734                        (set (make-local-variable 'reftex-default-addbibresource) 
735                             (split-string (org-element-property :path object) ","))
736
737                        ;; now if we have comma separated bibliographies
738                        ;; we find the one clicked on. we want to
739                        ;; search forward to next comma from point
740                        (save-excursion
741                          (if (search-forward "," link-string-end 1 1)
742                              (setq key-end (- (match-end 0) 1)) ; we found a match
743                            (setq key-end (point)))) ; no comma found so take the point
744                        ;; and backward to previous comma from point
745                        (save-excursion
746                          (if (search-backward "," link-string-beginning 1 1)
747                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
748                            (setq key-beginning (point)))) ; no match found
749                        ;; save the key we clicked on.
750                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
751                        (find-file bibfile))) ; open file on click
752
753                      ;; formatting code
754                    (lambda (keyword desc format)
755                      (cond
756                       ((eq format 'html) (format "")); no output for html
757                       ((eq format 'latex)
758                          ;; write out the latex addbibresource command
759                        (format "\\addbibresource{%s}" keyword)))))
760 #+END_SRC
761
762 ** List of Figures
763
764 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.
765
766 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
767 (defun org-ref-list-of-figures (&optional arg)
768   "Generate buffer with list of figures in them"
769   (interactive)
770   (save-excursion (widen)
771   (let* ((c-b (buffer-name))
772          (counter 0)
773          (list-of-figures 
774           (org-element-map (org-element-parse-buffer) 'link
775             (lambda (link) 
776               "create a link for to the figure"
777               (when 
778                   (and (string= (org-element-property :type link) "file")
779                        (string-match-p  
780                         "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
781                         (org-element-property :path link)))                   
782                 (incf counter)
783                 
784                 (let* ((start (org-element-property :begin link))
785                        (parent (car (cdr (org-element-property :parent link))))
786                        (caption (caaar (plist-get parent :caption)))
787                        (name (plist-get parent :name)))
788                   (if caption 
789                       (format 
790                        "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n" 
791                        c-b start counter (or name "") caption)
792                     (format 
793                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n" 
794                      c-b start counter (or name "")))))))))
795     (switch-to-buffer "*List of Figures*")
796     (setq buffer-read-only nil)
797     (org-mode)
798     (erase-buffer)
799     (insert (mapconcat 'identity list-of-figures ""))
800     (setq buffer-read-only t)
801     (use-local-map (copy-keymap org-mode-map))
802     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
803
804 (org-add-link-type 
805  "list-of-figures"
806  'org-ref-list-of-figures ; on click
807  (lambda (keyword desc format)
808    (cond
809     ((eq format 'latex)
810      (format "\\listoffigures")))))
811 #+END_SRC
812
813 ** List of Tables
814
815 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
816 (defun org-ref-list-of-tables (&optional arg)
817   "Generate a buffer with a list of tables"
818   (interactive)
819   (save-excursion
820   (widen)
821   (let* ((c-b (buffer-name))
822          (counter 0)
823          (list-of-tables 
824           (org-element-map (org-element-parse-buffer 'element) 'table
825             (lambda (table) 
826               "create a link for to the table"
827               (incf counter)
828               (let ((start (org-element-property :begin table))
829                     (name  (org-element-property :name table))
830                     (caption (caaar (org-element-property :caption table))))
831                 (if caption 
832                     (format 
833                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n" 
834                      c-b start counter (or name "") caption)
835                   (format 
836                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n" 
837                    c-b start counter (or name ""))))))))
838     (switch-to-buffer "*List of Tables*")
839     (setq buffer-read-only nil)
840     (org-mode)
841     (erase-buffer)
842     (insert (mapconcat 'identity list-of-tables ""))
843     (setq buffer-read-only t)
844     (use-local-map (copy-keymap org-mode-map))
845     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
846
847 (org-add-link-type 
848  "list-of-tables"
849  'org-ref-list-of-tables
850  (lambda (keyword desc format)
851    (cond
852     ((eq format 'latex)
853      (format "\\listoftables")))))
854 #+END_SRC
855 ** label
856
857 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.
858 *************** TODO search tblnames, custom_ids and check for case sensitivity
859 *************** END
860
861 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
862 (org-add-link-type
863  "label"
864  (lambda (label)
865    "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
866    (message (format "%s occurences"
867                     (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
868                        ;; for tblname, it is not enough to get word boundary
869                        ;; tab-little and tab-little-2 match then.
870                        (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
871                        (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
872                        ;; this is the org-format #+label:
873                        (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))))
874  (lambda (keyword desc format)
875    (cond
876     ((eq format 'html) (format "(<label>%s</label>)" path))
877     ((eq format 'latex)
878      (format "\\label{%s}" keyword)))))
879 #+END_SRC
880
881 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.
882
883 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
884 (defun org-label-store-link ()
885   "store a link to a label. The output will be a ref to that label"
886   ;; First we have to make sure we are on a label link. 
887   (let* ((object (org-element-context)))
888     (when (and (equal (org-element-type object) 'link) 
889                (equal (org-element-property :type object) "label"))
890       (org-store-link-props
891        :type "ref"
892        :link (concat "ref:" (org-element-property :path object))))
893
894     ;; Store link on table
895     (when (equal (org-element-type object) 'table)
896       (org-store-link-props
897        :type "ref"
898        :link (concat "ref:" (org-element-property :name object))))
899
900 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
901     ;; store link on heading with custom_id
902 ;    (when (and (equal (org-element-type object) 'headline)
903 ;              (org-entry-get (point) "CUSTOM_ID"))
904 ;      (org-store-link-props
905 ;       :type "ref"
906 ;       :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
907
908     ;; and to #+label: lines
909     (when (and (equal (org-element-type object) 'paragraph)
910                (org-element-property :name object))
911       (org-store-link-props
912        :type "ref"
913        :link (concat "ref:" (org-element-property :name object))))
914 ))
915
916 (add-hook 'org-store-link-functions 'org-label-store-link)
917 #+END_SRC
918 ** ref
919
920 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. 
921
922 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
923
924 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
925 (org-add-link-type
926  "ref"
927  (lambda (label)
928    "on clicking goto the label. Navigate back with C-c &"
929    (org-mark-ring-push)
930    ;; next search from beginning of the buffer
931
932    ;; it is possible you would not find the label if narrowing is in effect
933    (widen)
934
935    (unless
936        (or
937         ;; our label links
938         (progn 
939           (goto-char (point-min))
940           (re-search-forward (format "label:%s\\b" label) nil t))
941
942         ;; a latex label
943         (progn
944           (goto-char (point-min))
945           (re-search-forward (format "\\label{%s}" label) nil t))
946
947         ;; #+label: name  org-definition
948         (progn
949           (goto-char (point-min))
950           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
951         
952         ;; org tblname
953         (progn
954           (goto-char (point-min))
955           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
956
957 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
958 ;; you need [[#label]] links.
959         ;; CUSTOM_ID
960 ;       (progn
961 ;         (goto-char (point-min))
962 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
963         )
964      ;; we did not find anything, so go back to where we came
965      (org-mark-ring-goto)
966      (error "%s not found" label))
967    (org-show-entry)
968    (message "go back with (org-mark-ring-goto) `C-c &`"))
969  ;formatting
970  (lambda (keyword desc format)
971    (cond
972     ((eq format 'html) (format "(<ref>%s</ref>)" path))
973     ((eq format 'latex)
974      (format "\\ref{%s}" keyword)))))
975 #+END_SRC
976
977 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.
978
979 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
980 (defun org-ref-get-custom-ids ()
981  "return a list of custom_id properties in the buffer"
982  (let ((results '()) custom_id)
983    (org-map-entries 
984     (lambda () 
985       (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
986         (when (not (null custom_id))
987           (setq results (append results (list custom_id)))))))
988 results))
989 #+END_SRC
990
991 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
992 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
993 (defun org-ref-get-latex-labels ()
994 (save-excursion
995     (goto-char (point-min))
996     (let ((matches '()))
997       (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
998         (add-to-list 'matches (match-string-no-properties 1) t))
999 matches)))
1000 #+END_SRC
1001
1002 Finally, we get the table names.
1003
1004 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1005 (defun org-ref-get-tblnames ()
1006   (org-element-map (org-element-parse-buffer 'element) 'table
1007     (lambda (table) 
1008       (org-element-property :name table))))
1009 #+END_SRC
1010
1011 Now, we can put all the labels together which will give us a list of candidates.
1012
1013 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1014 (defun org-ref-get-labels ()
1015   "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
1016   (save-excursion
1017     (save-restriction
1018       (widen)
1019       (goto-char (point-min))
1020       (let ((matches '()))
1021         (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1022           (add-to-list 'matches (match-string-no-properties 1) t))
1023         (append matches (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
1024 #+END_SRC
1025
1026 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.
1027
1028 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1029 (defun org-ref-complete-link (&optional arg)
1030   "Completion function for ref links"
1031   (let ((label))
1032     (setq label (completing-read "label: " (org-ref-get-labels)))
1033     (format "ref:%s" label)))
1034 #+END_SRC
1035
1036 Alternatively, you may want to just call a function that inserts a link with completion:
1037
1038 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1039 (defun org-ref-insert-ref-link ()
1040  (interactive)
1041  (insert (org-ref-complete-link)))
1042 #+END_SRC
1043
1044 ** pageref
1045
1046 This refers to the page of a label in LaTeX.
1047
1048 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1049 (org-add-link-type
1050  "pageref"
1051  (lambda (label)
1052    "on clicking goto the label. Navigate back with C-c &"
1053    (org-mark-ring-push)
1054    ;; next search from beginning of the buffer
1055    (widen)
1056    (unless
1057        (or
1058         ;; our label links
1059         (progn 
1060           (goto-char (point-min))
1061           (re-search-forward (format "label:%s\\b" label) nil t))
1062
1063         ;; a latex label
1064         (progn
1065           (goto-char (point-min))
1066           (re-search-forward (format "\\label{%s}" label) nil t))
1067
1068         ;; #+label: name  org-definition
1069         (progn
1070           (goto-char (point-min))
1071           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1072         
1073         ;; org tblname
1074         (progn
1075           (goto-char (point-min))
1076           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1077
1078 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1079 ;; you need [[#label]] links.
1080         ;; CUSTOM_ID
1081 ;       (progn
1082 ;         (goto-char (point-min))
1083 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1084         )
1085      ;; we did not find anything, so go back to where we came
1086      (org-mark-ring-goto)
1087      (error "%s not found" label))
1088    (message "go back with (org-mark-ring-goto) `C-c &`"))
1089  ;formatting
1090  (lambda (keyword desc format)
1091    (cond
1092     ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1093     ((eq format 'latex)
1094      (format "\\pageref{%s}" keyword)))))
1095 #+END_SRC
1096
1097 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1098 (defun org-pageref-complete-link (&optional arg)
1099   "Completion function for ref links"
1100   (let ((label))
1101     (setq label (completing-read "label: " (org-ref-get-labels)))
1102     (format "ref:%s" label)))
1103 #+END_SRC
1104
1105 Alternatively, you may want to just call a function that inserts a link with completion:
1106
1107 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1108 (defun org-pageref-insert-ref-link ()
1109  (interactive)
1110  (insert (org-pageref-complete-link)))
1111 #+END_SRC
1112
1113 ** nameref
1114
1115 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.
1116
1117 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1118 (org-add-link-type
1119  "nameref"
1120  (lambda (label)
1121    "on clicking goto the label. Navigate back with C-c &"
1122    (org-mark-ring-push)
1123    ;; next search from beginning of the buffer
1124    (widen)
1125    (unless
1126        (or
1127         ;; a latex label
1128         (progn
1129           (goto-char (point-min))
1130           (re-search-forward (format "\\label{%s}" label) nil t))
1131         )
1132      ;; we did not find anything, so go back to where we came
1133      (org-mark-ring-goto)
1134      (error "%s not found" label))
1135    (message "go back with (org-mark-ring-goto) `C-c &`"))
1136  ;formatting
1137  (lambda (keyword desc format)
1138    (cond
1139     ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1140     ((eq format 'latex)
1141      (format "\\nameref{%s}" keyword)))))
1142 #+END_SRC
1143
1144 ** eqref
1145 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1146  
1147 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1148 (org-add-link-type
1149  "eqref"
1150  (lambda (label)
1151    "on clicking goto the label. Navigate back with C-c &"
1152    (org-mark-ring-push)
1153    ;; next search from beginning of the buffer
1154    (widen)
1155    (goto-char (point-min))
1156    (unless
1157        (or
1158         ;; search forward for the first match
1159         ;; our label links
1160         (re-search-forward (format "label:%s" label) nil t)
1161         ;; a latex label
1162         (re-search-forward (format "\\label{%s}" label) nil t)
1163         ;; #+label: name  org-definition
1164         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1165      (org-mark-ring-goto)
1166      (error "%s not found" label))
1167    (message "go back with (org-mark-ring-goto) `C-c &`"))
1168  ;formatting
1169  (lambda (keyword desc format)
1170    (cond
1171     ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1172     ((eq format 'latex)
1173      (format "\\eqref{%s}" keyword)))))
1174 #+END_SRC
1175
1176
1177 ** cite
1178 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.
1179
1180 *** Implementing the click actions of cite
1181
1182 **** Getting the key we clicked on
1183 The first thing we need is to get the bibtex key we clicked on.
1184
1185 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1186 (defun org-ref-get-bibtex-key-under-cursor ()
1187   "returns key under the bibtex cursor. We search forward from
1188 point to get a comma, or the end of the link, and then backwards
1189 to get a comma, or the beginning of the link. that delimits the
1190 keyword we clicked on. We also strip the text properties."
1191   (interactive)
1192   (let* ((object (org-element-context))  
1193          (link-string (org-element-property :path object)))
1194     ;; you may click on the part before the citations. here we make
1195     ;; sure to move to the beginning so you get the first citation.
1196     (let ((cp (point)))
1197       (goto-char (org-element-property :begin object))
1198       (search-forward link-string (org-element-property :end object))
1199       (goto-char (match-beginning 0))
1200       ;; check if we clicked before the path and move as needed.
1201       (unless (< cp (point))
1202         (goto-char cp)))
1203         
1204     (if (not (org-element-property :contents-begin object))
1205         ;; this means no description in the link
1206         (progn    
1207           ;; we need the link path start and end
1208           (save-excursion
1209             (goto-char (org-element-property :begin object))
1210             (search-forward link-string nil nil 1)
1211             (setq link-string-beginning (match-beginning 0))
1212             (setq link-string-end (match-end 0)))
1213
1214           ;; The key is the text between commas, or the link boundaries
1215           (save-excursion
1216             (if (search-forward "," link-string-end t 1)
1217                 (setq key-end (- (match-end 0) 1)) ; we found a match
1218               (setq key-end link-string-end))) ; no comma found so take the end
1219           ;; and backward to previous comma from point which defines the start character
1220           (save-excursion
1221             (if (search-backward "," link-string-beginning 1 1)
1222                 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1223               (setq key-beginning link-string-beginning))) ; no match found
1224           ;; save the key we clicked on.
1225           (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1226           (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1227           bibtex-key)
1228       ;; link with description. assume only one key
1229       link-string)))
1230 #+END_SRC
1231
1232 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.
1233
1234 **** Getting the bibliographies
1235 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1236 (defun org-ref-find-bibliography ()
1237   "find the bibliography in the buffer.
1238 This function sets and returns cite-bibliography-files, which is a list of files
1239 either from bibliography:f1.bib,f2.bib
1240 \bibliography{f1,f2}
1241 internal bibliographies
1242
1243 falling back to what the user has set in org-ref-default-bibliography
1244 "
1245   (interactive)
1246   (catch 'result
1247     (save-excursion
1248       (goto-char (point-min))
1249       ;;  look for a bibliography link
1250       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1251         (setq org-ref-bibliography-files
1252               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1253         (throw 'result org-ref-bibliography-files))
1254
1255       
1256       ;; we did not find a bibliography link. now look for \bibliography
1257       (goto-char (point-min))
1258       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1259         ;; split, and add .bib to each file
1260         (setq org-ref-bibliography-files
1261               (mapcar (lambda (x) (concat x ".bib"))
1262                       (mapcar 'org-ref-strip-string 
1263                               (split-string (match-string 1) ","))))
1264         (throw 'result org-ref-bibliography-files))
1265
1266       ;; no bibliography found. maybe we need a biblatex addbibresource
1267       (goto-char (point-min))
1268       ;;  look for a bibliography link
1269       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1270         (setq org-ref-bibliography-files
1271               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1272         (throw 'result org-ref-bibliography-files))
1273           
1274       ;; we did not find anything. use defaults
1275       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1276
1277     ;; set reftex-default-bibliography so we can search
1278     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1279     org-ref-bibliography-files)
1280 #+END_SRC
1281
1282 **** Finding the bibliography file a key is in
1283 Now, we can see if an entry is in a file. 
1284
1285 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1286 (defun org-ref-key-in-file-p (key filename)
1287   "determine if the key is in the file"
1288   (interactive "skey: \nsFile: ")
1289   (save-current-buffer
1290     (let ((bibtex-files (list filename)))
1291       (bibtex-search-entry key t))))
1292 #+END_SRC
1293
1294 Finally, we want to know which file the key is in.
1295
1296 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1297 (defun org-ref-get-bibtex-key-and-file (&optional key)
1298   "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1299  (interactive)
1300  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1301        (file))
1302    (unless key
1303      (setq key (org-ref-get-bibtex-key-under-cursor)))
1304    (setq file     (catch 'result
1305                     (loop for file in org-ref-bibliography-files do
1306                           (if (org-ref-key-in-file-p key (file-truename file)) 
1307                               (throw 'result file)))))
1308    (cons key file)))
1309 #+END_SRC
1310
1311 **** Creating the menu for when we click on a key
1312      :PROPERTIES:
1313      :ID:       d7b7530b-802f-42b1-b61e-1e77da33e278
1314      :END:
1315 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.
1316
1317 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1318 (defun org-ref-get-menu-options ()
1319   "returns a dynamically determined string of options for the citation under point.
1320
1321 we check to see if there is pdf, and if the key actually exists in the bibliography"
1322   (interactive)
1323   (let* ((results (org-ref-get-bibtex-key-and-file))
1324          (key (car results))
1325          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1326          (bibfile (cdr results))
1327          m1 m2 m3 m4 m5 menu-string)
1328     (setq m1 (if bibfile                 
1329                  "(o)pen"
1330                "(No key found)"))
1331
1332     (setq m3 (if (file-exists-p pdf-file)
1333                  "(p)df"
1334                      "(No pdf found)"))
1335
1336     (setq m4 (if (not
1337                   (and bibfile
1338                        (string= (catch 'url
1339                                   (progn
1340
1341                                     (with-temp-buffer
1342                                       (insert-file-contents bibfile)
1343                                       (bibtex-search-entry key)
1344                                       (when (not
1345                                              (string= (setq url (bibtex-autokey-get-field "url")) ""))
1346                                         (throw 'url url))
1347
1348                                       (when (not
1349                                              (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1350                                         (throw 'url url))))) "")))
1351                "(u)rl" "(no url found)"))
1352     (setq m5 "(n)otes")
1353     (setq m2 (if bibfile
1354                  (progn
1355                    (setq citation (progn
1356                                     (with-temp-buffer
1357                                       (insert-file-contents bibfile)
1358                                       (bibtex-search-entry key)
1359                                       (org-ref-bib-citation))))
1360                    citation)
1361                "no key found"))
1362
1363     (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") "  "))
1364     menu-string))
1365 #+END_SRC
1366
1367 **** convenience functions to act on citation at point
1368      :PROPERTIES:
1369      :ID:       af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1370      :END:
1371 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.
1372
1373 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1374 (defun org-ref-open-pdf-at-point ()
1375   "open the pdf for bibtex key under point if it exists"
1376   (interactive)
1377   (let* ((results (org-ref-get-bibtex-key-and-file))
1378          (key (car results))
1379          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1380     (if (file-exists-p pdf-file)
1381         (org-open-file pdf-file)
1382 (message "no pdf found for %s" key))))
1383
1384
1385 (defun org-ref-open-url-at-point ()
1386   "open the url for bibtex key under point."
1387   (interactive)
1388   (let* ((results (org-ref-get-bibtex-key-and-file))
1389          (key (car results))
1390          (bibfile (cdr results)))
1391     (save-excursion
1392       (with-temp-buffer
1393         (insert-file-contents bibfile)
1394         (bibtex-search-entry key)
1395         ;; I like this better than bibtex-url which does not always find
1396         ;; the urls
1397         (catch 'done
1398           (let ((url (bibtex-autokey-get-field "url")))
1399             (when  url
1400               (browse-url url)
1401               (throw 'done nil)))
1402
1403           (let ((doi (bibtex-autokey-get-field "doi")))
1404             (when doi
1405               (if (string-match "^http" doi)
1406                   (browse-url doi)
1407                 (browse-url (format "http://dx.doi.org/%s" doi)))
1408               (throw 'done nil))))))))
1409
1410 (defun org-ref-open-notes-at-point ()
1411   "open the notes for bibtex key under point."
1412   (interactive)
1413   (let* ((results (org-ref-get-bibtex-key-and-file))
1414          (key (car results))
1415          (bibfile (cdr results)))
1416     (save-excursion
1417       (with-temp-buffer
1418         (insert-file-contents bibfile)
1419         (bibtex-search-entry key)
1420         (org-ref-open-bibtex-notes)))))
1421
1422 (defun org-ref-citation-at-point ()
1423   "give message of current citation at point"
1424   (interactive)
1425   (let* ((cb (current-buffer))
1426         (results (org-ref-get-bibtex-key-and-file))
1427         (key (car results))
1428         (bibfile (cdr results)))        
1429     (message "%s" (progn
1430                     (with-temp-buffer
1431                       (insert-file-contents bibfile)
1432                       (bibtex-search-entry key)
1433                       (org-ref-bib-citation))))))
1434
1435 (defun org-ref-open-citation-at-point ()
1436   "open bibtex file to key at point"
1437   (interactive)
1438   (let* ((cb (current-buffer))
1439         (results (org-ref-get-bibtex-key-and-file))
1440         (key (car results))
1441         (bibfile (cdr results)))
1442     (find-file bibfile)
1443     (bibtex-search-entry key)))
1444 #+END_SRC
1445
1446 **** the actual minibuffer menu
1447 Now, we create the menu.
1448
1449 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1450 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1451   "use a minibuffer to select options for the citation under point.
1452
1453 you select your option with a single key press."
1454   (interactive)
1455   (let* ((choice (read-char (org-ref-get-menu-options)))
1456          (results (org-ref-get-bibtex-key-and-file))
1457          (key (car results))
1458          (cb (current-buffer))
1459          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1460          (bibfile (cdr results)))
1461
1462     (cond
1463      ;; open
1464      ((= choice ?o)
1465       (find-file bibfile)
1466        (bibtex-search-entry key))
1467
1468      ;; cite
1469      ((= choice ?c)
1470       (org-ref-citation-at-point))
1471       
1472
1473      ;; quit
1474      ((or 
1475       (= choice ?q) ; q
1476       (= choice ?\ )) ; space
1477       ;; this clears the minibuffer
1478       (message ""))
1479
1480      ;; pdf
1481      ((= choice ?p)
1482       (org-ref-open-pdf-at-point))
1483
1484      ;; notes
1485      ((= choice ?n)
1486       (org-ref-open-notes-at-point))
1487
1488      ;; url
1489      ((= choice ?u)
1490       (org-ref-open-url-at-point))
1491
1492      ;; anything else we just quit.
1493      (t (message "")))))
1494     
1495 #+END_SRC
1496
1497 *** A function to format a cite link
1498
1499 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.
1500
1501 #+BEGIN_SRC emacs-lisp  :tangle no
1502 ;(defun org-ref-cite-link-format (keyword desc format)
1503 ;   (cond
1504 ;    ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1505 ;    ((eq format 'latex)
1506 ;     (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1507 ;            (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1508 ;            "}"))))
1509 #+END_SRC
1510
1511 *** The actual cite link
1512 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1513
1514 #+BEGIN_SRC emacs-lisp :tangle no
1515 ;(org-add-link-type
1516 ; "cite"
1517 ; 'org-ref-cite-onclick-minibuffer-menu
1518 ; 'org-ref-cite-link-format)
1519 #+END_SRC
1520
1521 *** Automatic definition of the cite links
1522 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. 
1523
1524 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1525 (defmacro org-ref-make-completion-function (type)
1526   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1527      (interactive)
1528      (format "%s:%s" 
1529              ,type
1530              (completing-read 
1531               "bibtex key: " 
1532               (let ((bibtex-files (org-ref-find-bibliography)))
1533                 (bibtex-global-key-alist))))))
1534 #+END_SRC
1535
1536 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.
1537
1538 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1539 (defmacro org-ref-make-format-function (type)
1540   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1541      (cond
1542       ((eq format 'org)
1543        (mapconcat
1544         (lambda (key)
1545           (format "[[#%s][%s]]" key key))
1546         (org-ref-split-and-strip-string keyword) ","))
1547
1548       ((eq format 'ascii)
1549        (concat "["
1550                (mapconcat
1551                 (lambda (key)
1552                   (format "%s" key))
1553                 (org-ref-split-and-strip-string keyword) ",") "]"))
1554         
1555       ((eq format 'html) 
1556        (mapconcat 
1557         (lambda (key) 
1558           (format "<a href=\"#%s\">%s</a>" key key))
1559         (org-ref-split-and-strip-string keyword) ","))
1560
1561       ((eq format 'latex)
1562        (if (string= (substring type -1) "s")
1563            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1564            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1565                                          (org-ref-split-and-strip-string keyword) ""))
1566          ;; bibtex format
1567        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1568                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1569                "}"))))))
1570 #+END_SRC
1571
1572
1573
1574 We create the links by mapping the function onto the list of defined link types. 
1575
1576 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1577 (defun org-ref-format-citation-description (desc)
1578   "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 ::."
1579   (interactive)
1580   (cond
1581    ((string-match "::" desc)
1582     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1583    (t (format "[%s]" desc))))
1584
1585 (defun org-ref-define-citation-link (type &optional key)
1586   "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1587 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z, 
1588 and the completion function."
1589   (interactive "sCitation Type: \ncKey: ")
1590
1591   ;; create the formatting function
1592   (eval `(org-ref-make-format-function ,type))
1593
1594   (eval-expression 
1595    `(org-add-link-type 
1596      ,type
1597      'org-ref-cite-onclick-minibuffer-menu
1598      (quote ,(intern (format "org-ref-format-%s" type)))))
1599
1600   ;; create the completion function
1601   (eval `(org-ref-make-completion-function ,type))
1602   
1603   ;; store new type so it works with adding citations, which checks
1604   ;; for existence in this list
1605   (add-to-list 'org-ref-cite-types type)
1606
1607   ;; and finally if a key is specified, we modify the reftex menu
1608   (when key
1609     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1610           (append (nth 2 (assoc 'org reftex-cite-format-builtin)) 
1611                   `((,key  . ,(concat type ":%l")))))))
1612
1613 ;; create all the link types and their completion functions
1614 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1615 #+END_SRC
1616
1617 *** org-ref-insert-cite-link
1618 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.
1619
1620 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1621 (defun org-ref-insert-cite-link (alternative-cite)
1622   "Insert a default citation link using reftex. If you are on a link, it
1623 appends to the end of the link, otherwise, a new link is
1624 inserted. Use a prefix arg to get a menu of citation types."
1625   (interactive "P")
1626   (org-ref-find-bibliography)
1627   (let* ((object (org-element-context))
1628          (link-string-beginning (org-element-property :begin object))
1629          (link-string-end (org-element-property :end object))
1630          (path (org-element-property :path object)))  
1631
1632     (if (not alternative-cite)
1633         
1634         (cond
1635          ;; case where we are in a link
1636          ((and (equal (org-element-type object) 'link) 
1637                (-contains? org-ref-cite-types (org-element-property :type object)))
1638           (goto-char link-string-end)
1639           ;; sometimes there are spaces at the end of the link
1640           ;; this code moves point pack until no spaces are there
1641           (while (looking-back " ") (backward-char))  
1642           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1643
1644          ;; We are next to a link, and we want to append
1645          ((save-excursion 
1646             (backward-char)
1647             (and (equal (org-element-type (org-element-context)) 'link) 
1648                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1649           (while (looking-back " ") (backward-char))  
1650           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1651
1652          ;; insert fresh link
1653          (t 
1654           (insert 
1655            (concat org-ref-default-citation-link 
1656                    ":" 
1657                    (mapconcat 'identity (reftex-citation t) ",")))))
1658
1659       ;; you pressed a C-u so we run this code
1660       (reftex-citation)))
1661   )
1662 #+END_SRC
1663
1664 #+RESULTS:
1665 : org-ref-insert-cite-link
1666
1667 *** Completion in cite links
1668 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.
1669
1670 #+BEGIN_SRC emacs-lisp  :tangle no
1671 (defun org-cite-complete-link (&optional arg)
1672   "Completion function for cite links"
1673   (format "%s:%s" 
1674           org-ref-default-citation-link
1675           (completing-read 
1676            "bibtex key: " 
1677            (let ((bibtex-files (org-ref-find-bibliography)))
1678              (bibtex-global-key-alist)))))
1679 #+END_SRC
1680
1681 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1682
1683 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1684 (defun org-ref-insert-cite-with-completion (type)
1685   "Insert a cite link with completion"
1686   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1687   (insert (funcall (intern (format "org-%s-complete-link" type)))))
1688 #+END_SRC
1689
1690 ** Storing links to a bibtex entry
1691 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.
1692
1693 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1694 (defun org-ref-store-bibtex-entry-link ()
1695   "Save a citation link to the current bibtex entry. Saves in the default link type."
1696   (interactive)
1697   (let ((link (concat org-ref-default-citation-link 
1698                  ":"   
1699                  (save-excursion
1700                    (bibtex-beginning-of-entry)
1701                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1702     (message "saved %s" link)
1703     (push (list link) org-stored-links)
1704     (car org-stored-links)))
1705 #+END_SRC
1706
1707
1708 * Utilities
1709 ** create simple text citation from bibtex entry
1710
1711 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1712 (defun org-ref-bib-citation ()
1713   "from a bibtex entry, create and return a simple citation string."
1714
1715   (bibtex-beginning-of-entry)
1716   (let* ((cb (current-buffer))
1717          (bibtex-expand-strings t)
1718          (entry (loop for (key . value) in (bibtex-parse-entry t)
1719                       collect (cons (downcase key) value)))
1720          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1721          (year  (reftex-get-bib-field "year" entry))
1722          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1723          (key (reftex-get-bib-field "=key=" entry))
1724          (journal (reftex-get-bib-field "journal" entry))
1725          (volume (reftex-get-bib-field "volume" entry))
1726          (pages (reftex-get-bib-field "pages" entry))
1727          (doi (reftex-get-bib-field "doi" entry))
1728          (url (reftex-get-bib-field "url" entry))
1729          )
1730     ;;authors, "title", Journal, vol(iss):pages (year).
1731     (format "%s, \"%s\", %s, %s:%s (%s)"
1732             author title journal  volume pages year)))
1733 #+END_SRC
1734
1735 #+RESULTS:
1736 : org-ref-bib-citation
1737
1738
1739 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1740 (defun org-ref-bib-html-citation ()
1741   "from a bibtex entry, create and return a simple citation with html links."
1742
1743   (bibtex-beginning-of-entry)
1744   (let* ((cb (current-buffer))
1745          (bibtex-expand-strings t)
1746          (entry (loop for (key . value) in (bibtex-parse-entry t)
1747                       collect (cons (downcase key) value)))
1748          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1749          (year  (reftex-get-bib-field "year" entry))
1750          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1751          (key (reftex-get-bib-field "=key=" entry))
1752          (journal (reftex-get-bib-field "journal" entry))
1753          (volume (reftex-get-bib-field "volume" entry))
1754          (pages (reftex-get-bib-field "pages" entry))
1755          (doi (reftex-get-bib-field "doi" entry))
1756          (url (reftex-get-bib-field "url" entry))
1757          )
1758     ;;authors, "title", Journal, vol(iss):pages (year).
1759     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1760                     author title journal  volume pages year)
1761             (when url (format " <a href=\"%s\">link</a>" url))
1762             (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1763     ))
1764 #+END_SRC
1765
1766 ** open pdf from bibtex
1767 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1768 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1769 (defun org-ref-open-bibtex-pdf ()
1770   "open pdf for a bibtex entry, if it exists. assumes point is in
1771 the entry of interest in the bibfile. but does not check that."
1772   (interactive)
1773   (save-excursion
1774     (bibtex-beginning-of-entry)
1775     (let* ((bibtex-expand-strings t)
1776            (entry (bibtex-parse-entry t))
1777            (key (reftex-get-bib-field "=key=" entry))
1778            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1779       (message "%s" pdf)
1780       (if (file-exists-p pdf)
1781           (org-open-link-from-string (format "[[file:%s]]" pdf))
1782         (ding)))))
1783 #+END_SRC
1784
1785 ** open notes from bibtex
1786 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1787
1788 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1789 (defun org-ref-open-bibtex-notes ()
1790   "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1791
1792 I never did figure out how to use reftex to make this happen
1793 non-interactively. the reftex-format-citation function did not
1794 work perfectly; there were carriage returns in the strings, and
1795 it did not put the key where it needed to be. so, below I replace
1796 the carriage returns and extra spaces with a single space and
1797 construct the heading by hand."
1798   (interactive)
1799
1800   (bibtex-beginning-of-entry)
1801   (let* ((cb (current-buffer))
1802          (bibtex-expand-strings t)
1803          (entry (loop for (key . value) in (bibtex-parse-entry t)
1804                       collect (cons (downcase key) value)))
1805          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1806          (year  (reftex-get-bib-field "year" entry))
1807          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1808          (key (reftex-get-bib-field "=key=" entry))
1809          (journal (reftex-get-bib-field "journal" entry))
1810          (volume (reftex-get-bib-field "volume" entry))
1811          (pages (reftex-get-bib-field "pages" entry))
1812          (doi (reftex-get-bib-field "doi" entry))
1813          (url (reftex-get-bib-field "url" entry))
1814          )
1815
1816     ;; save key to clipboard to make saving pdf later easier by pasting.
1817     (with-temp-buffer
1818       (insert key)
1819       (kill-ring-save (point-min) (point-max)))
1820     
1821     ;; now look for entry in the notes file
1822     (if  org-ref-bibliography-notes
1823         (find-file-other-window org-ref-bibliography-notes)
1824       (error "org-ref-bib-bibliography-notes is not set to anything"))
1825     
1826     (goto-char (point-min))
1827     ;; put new entry in notes if we don't find it.
1828     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1829         (funcall org-ref-open-notes-function)
1830       ;; no entry found, so add one     
1831       (insert (format "\n** TODO %s - %s" year title))
1832       (insert (format"
1833  :PROPERTIES:
1834   :Custom_ID: %s
1835   :AUTHOR: %s
1836   :JOURNAL: %s
1837   :YEAR: %s
1838   :VOLUME: %s
1839   :PAGES: %s
1840   :DOI: %s
1841   :URL: %s
1842  :END:
1843 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1844 key author journal year volume pages doi url key org-ref-pdf-directory key))
1845 (save-buffer))))
1846 #+END_SRC
1847
1848 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1849 (defun org-ref-open-notes-from-reftex ()
1850   "Call reftex, and open notes for selected entry."
1851   (interactive)
1852   (let ((bibtex-key )))
1853
1854     ;; now look for entry in the notes file
1855     (if  org-ref-bibliography-notes
1856         (find-file-other-window org-ref-bibliography-notes)
1857       (error "org-ref-bib-bibliography-notes is not set to anything"))
1858     
1859     (goto-char (point-min))
1860     
1861     (re-search-forward (format
1862                         ":Custom_ID: %s$"
1863                         (first (reftex-citation t)) nil 'end))
1864     (funcall org-ref-open-notes-function))
1865 #+END_SRC
1866
1867 ** open url in browser from bibtex
1868
1869 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1870
1871 + 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.
1872
1873 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1874 (defun org-ref-open-in-browser ()
1875   "Open the bibtex entry at point in a browser using the url field or doi field"
1876 (interactive)
1877 (save-excursion
1878   (bibtex-beginning-of-entry)
1879   (catch 'done
1880     (let ((url (bibtex-autokey-get-field "url")))
1881       (when  url
1882         (browse-url url)
1883         (throw 'done nil)))
1884
1885     (let ((doi (bibtex-autokey-get-field "doi")))
1886       (when doi
1887         (if (string-match "^http" doi)
1888             (browse-url doi)
1889           (browse-url (format "http://dx.doi.org/%s" doi)))
1890         (throw 'done nil)))
1891     (message "No url or doi found"))))
1892 #+END_SRC
1893
1894 ** citeulike
1895    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.
1896
1897 *** function to upload bibtex to citeulike
1898
1899 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1900 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1901   "with point in  a bibtex entry get bibtex string and submit to citeulike.
1902
1903 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1904   (interactive)
1905   (message "uploading to citeulike")
1906   (save-restriction
1907     (bibtex-narrow-to-entry)
1908     (let ((startpos (point-min))
1909           (endpos (point-max))
1910           (bibtex-string (buffer-string))
1911           (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1912       (with-temp-buffer (insert bibtex-string)
1913                         (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1914 #+END_SRC
1915
1916 *** The upload script
1917 Here is the python script for uploading. 
1918
1919 *************** TODO document how to get the cookies
1920 *************** END
1921
1922
1923 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1924 #!python
1925 import pickle, requests, sys
1926
1927 # reload cookies
1928 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1929     cookies = pickle.load(f)
1930
1931 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1932
1933 bibtex = sys.stdin.read()
1934
1935 data = {'pasted':bibtex,
1936         'to_read':2,
1937         'tag_parsing':'simple',
1938         'strip_brackets':'no',
1939         'update_id':'bib-key',
1940         'btn_bibtex':'Import BibTeX file ...'}
1941
1942 headers = {'content-type': 'multipart/form-data',
1943            'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1944
1945 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1946 print r
1947 #+END_SRC
1948
1949 ** Build a pdf from a bibtex file
1950    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.
1951
1952 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1953 (defun org-ref-build-full-bibliography ()
1954   "build pdf of all bibtex entries, and open it."
1955   (interactive)
1956   (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1957         (bib-base (file-name-sans-extension bibfile))
1958         (texfile (concat bib-base ".tex"))
1959         (pdffile (concat bib-base ".pdf")))
1960     (find-file texfile)
1961     (erase-buffer)
1962     (insert (format "\\documentclass[12pt]{article}
1963 \\usepackage[version=3]{mhchem}
1964 \\usepackage{url}
1965 \\usepackage[numbers]{natbib}
1966 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1967 \\usepackage{doi}
1968 \\begin{document}
1969 \\nocite{*}
1970 \\bibliographystyle{unsrtnat}
1971 \\bibliography{%s}
1972 \\end{document}" bib-base))
1973     (save-buffer)
1974     (shell-command (concat "pdflatex " bib-base))
1975     (shell-command (concat "bibtex " bib-base))
1976     (shell-command (concat "pdflatex " bib-base))
1977     (shell-command (concat "pdflatex " bib-base))
1978     (kill-buffer texfile)
1979     (org-open-file pdffile)
1980     )) 
1981 #+END_SRC
1982
1983 ** Extract bibtex entries cited in an org-file
1984 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.
1985
1986 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1987 (defun org-ref-extract-bibtex-entries ()
1988   "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1989
1990 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1991   (interactive)
1992   (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1993          (tempname (make-temp-file "extract-bib"))
1994          (contents (buffer-string))
1995          (cb (current-buffer))
1996          basename texfile bibfile results)
1997     
1998     ;; open tempfile and insert org-buffer contents
1999     (find-file tempname)
2000     (insert contents)
2001     (setq basename (file-name-sans-extension 
2002                     (file-name-nondirectory buffer-file-name))
2003           texfile (concat tempname ".tex")
2004           bibfile (concat tempname ".bib"))
2005     
2006     ;; see if we have a bibliography, and insert the default one if not.
2007     (save-excursion
2008       (goto-char (point-min))
2009       (unless (re-search-forward "^bibliography:" (point-max) 'end)
2010         (insert (format "\nbibliography:%s" 
2011                         (mapconcat 'identity reftex-default-bibliography ",")))))
2012     (save-buffer)
2013
2014     ;; get a latex file and extract the references
2015     (org-latex-export-to-latex)
2016     (find-file texfile)
2017     (reftex-parse-all)
2018     (reftex-create-bibtex-file bibfile)
2019     (save-buffer)
2020     ;; save results of the references
2021     (setq results (buffer-string))
2022
2023     ;; kill buffers. these are named by basename, not full path
2024     (kill-buffer (concat basename ".bib"))
2025     (kill-buffer (concat basename ".tex"))
2026     (kill-buffer basename)
2027
2028     (delete-file bibfile)
2029     (delete-file texfile)
2030     (delete-file tempname)
2031
2032     ;; Now back to the original org buffer and insert the results
2033     (switch-to-buffer cb)
2034     (when (not (string= "" results))
2035       (save-excursion
2036         (goto-char (point-max))
2037         (insert "\n\n")
2038         (org-insert-heading)
2039         (insert (format " Bibtex entries
2040
2041 ,#+BEGIN_SRC text :tangle %s
2042 %s
2043 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2044 #+END_SRC
2045
2046 ** Find bad cite links
2047 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.
2048
2049 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
2050 (require 'cl)
2051
2052 (defun index (substring list)
2053   "return the index of string in a list of strings"
2054   (let ((i 0)
2055         (found nil))
2056     (dolist (arg list i)
2057       (if (string-match (concat "^" substring "$") arg)
2058           (progn 
2059             (setq found t)
2060             (return i)))
2061       (setq i (+ i 1)))
2062     ;; return counter if found, otherwise return nil
2063     (if found i nil)))
2064
2065
2066 (defun org-ref-find-bad-citations ()
2067   "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2068
2069 Makes a new buffer with clickable links."
2070   (interactive)
2071   ;; generate the list of bibtex-keys and cited keys
2072   (let* ((bibtex-files (org-ref-find-bibliography))
2073          (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2074          (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2075          (bad-citations '()))
2076
2077     (org-element-map (org-element-parse-buffer) 'link
2078       (lambda (link)       
2079         (let ((plist (nth 1 link)))                          
2080           (when (equal (plist-get plist ':type) "cite")
2081             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2082               (when (not (index key bibtex-keys))
2083                 (setq bad-citations (append bad-citations
2084                                             `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2085                                                        key (buffer-name)(plist-get plist ':begin)))))
2086                 ))))))
2087
2088     (if bad-citations
2089       (progn
2090         (switch-to-buffer-other-window "*Missing citations*")
2091         (org-mode)
2092         (erase-buffer)
2093         (insert "* List of bad cite links\n")
2094         (insert (mapconcat 'identity bad-citations ""))
2095                                         ;(setq buffer-read-only t)
2096         (use-local-map (copy-keymap org-mode-map))
2097         (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2098
2099       (when (get-buffer "*Missing citations*")
2100           (kill-buffer "*Missing citations*"))
2101       (message "No bad cite links found"))))
2102 #+END_SRC
2103
2104 ** Finding non-ascii characters
2105 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them. 
2106
2107 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2108 (defun org-ref-find-non-ascii-characters ()
2109   "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2110   (interactive)
2111   (occur "[^[:ascii:]]"))
2112 #+END_SRC
2113
2114 ** Resort a bibtex entry
2115 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.
2116
2117 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2118 (defun org-ref-sort-bibtex-entry ()
2119   "sort fields of entry in standard order and downcase them"
2120   (interactive)
2121   (bibtex-beginning-of-entry)
2122   (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2123          (entry (bibtex-parse-entry))
2124          (entry-fields)
2125          (other-fields)
2126          (type (cdr (assoc "=type=" entry)))
2127          (key (cdr (assoc "=key=" entry))))
2128
2129     ;; these are the fields we want to order that are in this entry
2130     (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2131     ;; we do not want to reenter these fields
2132     (setq entry-fields (remove "=key=" entry-fields))
2133     (setq entry-fields (remove "=type=" entry-fields))
2134
2135     ;;these are the other fields in the entry
2136     (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2137
2138     (cond
2139      ;; right now we only resort articles
2140      ((string= (downcase type) "article") 
2141       (bibtex-kill-entry)
2142       (insert
2143        (concat "@article{" key ",\n" 
2144                (mapconcat  
2145                 (lambda (field) 
2146                   (when (member field entry-fields)
2147                     (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2148                (mapconcat 
2149                 (lambda (field) 
2150                   (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2151                "\n}\n\n"))
2152       (bibtex-find-entry key)
2153       (bibtex-fill-entry)
2154       (bibtex-clean-entry)
2155        ))))
2156 #+END_SRC
2157
2158 ** Clean a bibtex entry
2159    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.
2160 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.
2161 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2162 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2163   "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"
2164   (interactive "P")
2165   (bibtex-beginning-of-entry) 
2166 (end-of-line)
2167   ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2168   (unless (string-match ",$" (thing-at-point 'line))
2169     (end-of-line)
2170     (insert ","))
2171
2172   ;; check for empty pages, and put eid or article id in its place
2173   (let ((entry (bibtex-parse-entry))
2174         (pages (bibtex-autokey-get-field "pages"))
2175         (year (bibtex-autokey-get-field "year"))
2176         (doi  (bibtex-autokey-get-field "doi"))
2177         ;; The Journal of Chemical Physics uses eid
2178         (eid (bibtex-autokey-get-field "eid")))
2179
2180     ;; replace http://dx.doi.org/ in doi. some journals put that in,
2181     ;; but we only want the doi.
2182     (when (string-match "^http://dx.doi.org/" doi)
2183       (bibtex-beginning-of-entry)
2184       (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2185       (bibtex-kill-field)
2186       (bibtex-make-field "doi")
2187       (backward-char)
2188       (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2189
2190     ;; asap articles often set year to 0, which messes up key
2191     ;; generation. fix that.
2192     (when (string= "0" year)  
2193       (bibtex-beginning-of-entry)
2194       (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2195       (bibtex-kill-field)
2196       (bibtex-make-field "year")
2197       (backward-char)
2198       (insert (read-string "Enter year: ")))
2199
2200     ;; fix pages if they are empty if there is an eid to put there.
2201     (when (string= "-" pages)
2202       (when eid   
2203         (bibtex-beginning-of-entry)
2204         ;; this seems like a clunky way to set the pages field.But I
2205         ;; cannot find a better way.
2206         (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2207         (bibtex-kill-field)
2208         (bibtex-make-field "pages")
2209         (backward-char)
2210         (insert eid)))
2211
2212     ;; replace naked & with \&
2213     (save-restriction
2214       (bibtex-narrow-to-entry)
2215       (bibtex-beginning-of-entry)
2216       (message "checking &")
2217       (replace-regexp " & " " \\\\& ")
2218       (widen))
2219
2220     ;; generate a key, and if it duplicates an existing key, edit it.
2221     (unless keep-key
2222       (let ((key (bibtex-generate-autokey)))
2223
2224         ;; first we delete the existing key
2225         (bibtex-beginning-of-entry)
2226         (re-search-forward bibtex-entry-maybe-empty-head)
2227         (if (match-beginning bibtex-key-in-head)
2228             (delete-region (match-beginning bibtex-key-in-head)
2229                            (match-end bibtex-key-in-head)))
2230         ;; check if the key is in the buffer
2231         (when (save-excursion
2232                 (bibtex-search-entry key))
2233           (save-excursion
2234             (bibtex-search-entry key)
2235             (bibtex-copy-entry-as-kill)
2236             (switch-to-buffer-other-window "*duplicate entry*")
2237             (bibtex-yank))
2238           (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2239
2240         (insert key)
2241         (kill-new key))) ;; save key for pasting            
2242
2243     ;; run hooks. each of these operates on the entry with no arguments.
2244     ;; this did not work like  i thought, it gives a symbolp error.
2245     ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2246     (mapcar (lambda (x)
2247               (save-restriction
2248                 (save-excursion
2249                   (funcall x))))
2250             org-ref-clean-bibtex-entry-hook)
2251     
2252     ;; sort fields within entry
2253     (org-ref-sort-bibtex-entry)
2254     ;; check for non-ascii characters
2255     (occur "[^[:ascii:]]")
2256     ))
2257 #+END_SRC
2258
2259 #+RESULTS:
2260 : org-ref-clean-bibtex-entry
2261
2262 ** Sort the entries in a citation link by year
2263 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2264
2265 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2266 (defun org-ref-get-citation-year (key)
2267   "get the year of an entry with key. Returns year as a string."
2268   (interactive)
2269   (let* ((results (org-ref-get-bibtex-key-and-file key))
2270          (bibfile (cdr results)))
2271     (with-temp-buffer
2272       (insert-file-contents bibfile)
2273       (bibtex-search-entry key nil 0)
2274       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2275         ))))
2276
2277 (defun org-ref-sort-citation-link ()
2278  "replace link at point with sorted link by year"
2279  (interactive)
2280  (let* ((object (org-element-context))   
2281         (type (org-element-property :type object))
2282         (begin (org-element-property :begin object))
2283         (end (org-element-property :end object))
2284         (link-string (org-element-property :path object))
2285         keys years data)
2286   (setq keys (org-ref-split-and-strip-string link-string))
2287   (setq years (mapcar 'org-ref-get-citation-year keys)) 
2288   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2289   (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2290   ;; now get the keys separated by commas
2291   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2292   ;; and replace the link with the sorted keys
2293   (cl--set-buffer-substring begin end (concat type ":" keys))))
2294 #+END_SRC
2295
2296 ** Sort entries in citation links with shift-arrow keys
2297 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2298 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2299 (defun org-ref-swap-keys (i j keys)
2300  "swap the keys in a list with index i and j"
2301  (let ((tempi (nth i keys)))
2302    (setf (nth i keys) (nth j keys))
2303    (setf (nth j keys) tempi))
2304   keys)
2305
2306 (defun org-ref-swap-citation-link (direction)
2307  "move citation at point in direction +1 is to the right, -1 to the left"
2308  (interactive)
2309  (let* ((object (org-element-context))   
2310         (type (org-element-property :type object))
2311         (begin (org-element-property :begin object))
2312         (end (org-element-property :end object))
2313         (link-string (org-element-property :path object))
2314         key keys i)
2315    ;;   We only want this to work on citation links
2316    (when (-contains? org-ref-cite-types type)
2317         (setq key (org-ref-get-bibtex-key-under-cursor))
2318         (setq keys (org-ref-split-and-strip-string link-string))
2319         (setq i (index key keys))  ;; defined in org-ref
2320         (if (> direction 0) ;; shift right
2321             (org-ref-swap-keys i (+ i 1) keys)
2322           (org-ref-swap-keys i (- i 1) keys))   
2323         (setq keys (mapconcat 'identity keys ","))
2324         ;; and replace the link with the sorted keys
2325         (cl--set-buffer-substring begin end (concat type ":" keys))
2326         ;; now go forward to key so we can move with the key
2327         (re-search-forward key) 
2328         (goto-char (match-beginning 0)))))
2329
2330 ;; add hooks to make it work
2331 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2332 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2333 #+END_SRC
2334 * Aliases
2335 I like convenience. Here are some aliases for faster typing.
2336
2337 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2338 (defalias 'oro 'org-ref-open-citation-at-point)
2339 (defalias 'orc 'org-ref-citation-at-point)
2340 (defalias 'orp 'org-ref-open-pdf-at-point)
2341 (defalias 'oru 'org-ref-open-url-at-point)
2342 (defalias 'orn 'org-ref-open-notes-at-point)
2343 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2344
2345 (defalias 'orib 'org-ref-insert-bibliography-link)
2346 (defalias 'oric 'org-ref-insert-cite-link)
2347 (defalias 'orir 'org-ref-insert-ref-link)
2348 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2349
2350 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2351 #+END_SRC
2352 * End of code
2353 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2354 (provide 'org-ref)
2355 #+END_SRC
2356
2357
2358 * Build                                                            :noexport:
2359
2360 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2361
2362 [[elisp:(org-babel-load-file "org-ref.org")]]
2363
2364
2365