]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.org
fix label click action for occurence plurality
[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 1. Get minibuffer messages for the cite/ref/label link under point
16
17 With helm integration (default) you can:
18
19 1. C-c ] to insert a citation link
20   in helm-bibtex
21    - Enter to insert or append citation(s)
22    - C-u Enter to insert an alternative cite link
23    - C-u C-u Enter to replace the citation at point
24 2. C-u C-c ] to insert a ref link with helm completion
25 3. C-u C-u C-c ] to insert a label with completion
26 4. M-x org-ref to get a helm completion buffer with link checks, utilities and export options
27
28 ** Header
29 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
30 ;;; org-ref.el --- setup bibliography, cite, ref and label org-mode links.
31
32 ;; Copyright(C) 2014 John Kitchin
33
34 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
35 ;; This file is not currently part of GNU Emacs.
36
37 ;; This program is free software; you can redistribute it and/or
38 ;; modify it under the terms of the GNU General Public License as
39 ;; published by the Free Software Foundation; either version 2, or (at
40 ;; your option) any later version.
41
42 ;; This program is distributed in the hope that it will be useful, but
43 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
44 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
45 ;; General Public License for more details.
46
47 ;; You should have received a copy of the GNU General Public License
48 ;; along with this program ; see the file COPYING.  If not, write to
49 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
50 ;; Boston, MA 02111-1307, USA.
51
52 ;;; Commentary:
53 ;;
54 ;; Lisp code to setup bibliography cite, ref and label org-mode links.  also
55 ;; sets up reftex and helm for org-mode citations. The links are clickable and
56 ;; do things that are useful. You should really read org-ref.org for details.
57 ;;
58 ;; Package-Requires: ((dash) (helm) (helm-bibtex))
59 #+END_SRC
60
61 ** requires
62 The only external require is reftex-cite
63
64 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
65 (require 'reftex-cite)
66 (require 'dash)
67 (require 'helm)
68 (require 'helm-bibtex)
69 #+END_SRC
70
71 ** Custom variables
72 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.
73
74 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
75 (defgroup org-ref nil
76   "customization group for org-ref")
77
78 (defcustom org-ref-bibliography-notes
79   nil
80   "filename to where you will put all your notes about an entry in
81   the default bibliography."
82   :type 'file
83   :group 'org-ref)
84
85 (defcustom org-ref-default-bibliography
86   nil
87   "list of bibtex files to search for. You should use full-paths for each file."
88   :type '(repeat :tag "List of bibtex files" file)
89   :group 'org-ref)
90
91 (defcustom org-ref-pdf-directory
92   nil
93   "directory where pdfs are stored by key. put a trailing / in"
94   :type 'directory
95   :group 'org-ref)
96
97 (defcustom org-ref-default-citation-link
98   "cite"
99   "The default type of citation link to use"
100   :type 'string
101   :group 'org-ref)
102
103 (defcustom org-ref-insert-cite-key
104   "C-c ]"
105   "Keyboard shortcut to insert a citation."
106   :type 'string
107   :group 'org-ref)
108
109 (defcustom org-ref-bibliography-entry-format
110   '(("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>.")
111
112     ("book" . "%a, %t, %u (%y).")
113
114     ("proceedings" . "%e, %t in %S, %u (%y).")
115
116     ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
117
118   "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."
119   :type 'string
120   :group 'org-ref)
121
122 (defcustom org-ref-open-notes-function
123   (lambda ()
124     (org-show-entry)
125     (show-branches)
126     (show-children)
127     (org-cycle '(64))
128     ;;(org-tree-to-indirect-buffer)
129     (outline-previous-visible-heading 1)
130     (recenter-top-bottom 0))
131   "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"
132 :type 'function
133 :group 'org-ref)
134
135
136 (defcustom org-ref-open-pdf-function
137    'org-ref-open-pdf-at-point
138 "User-defined function to open a pdf from a link. The function must get the key at point, and derive a path to the pdf file, then open it. The default function is `org-ref-open-pdf-at-point'."
139   :type 'function
140   :group 'org-ref)
141
142
143 (defcustom org-ref-insert-cite-function
144   'org-ref-helm-insert-cite-link
145   "Function to call to insert citation links. The default is `org-ref-helm-insert-cite-link' which uses `helm-bibtex'. org-ref modifies helm-bibtex a little bit to give org-mode citations, and to reorder default actions. You may use `org-ref-insert-cite-link' if you like the reftex interface."
146  :type 'function
147  :group 'org-ref)
148
149
150 (defcustom org-ref-cite-onclick-function
151   'org-ref-cite-click-helm
152   "Function that runs when you click on a cite link. The function must take no arguments. You may also use `org-ref-cite-onclick-minibuffer-menu' if you do not like helm."
153  :type 'function
154  :group 'org-ref)
155
156 (defcustom org-ref-show-citation-on-enter t
157   "If non-nil add a hook function to show the citation summary in
158   the minibuffer just by putting the cursor in a link"
159  :group 'org-ref)
160
161 #+END_SRC
162
163 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.
164
165 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
166 (defcustom org-ref-cite-types
167   '("cite" "nocite" ;; the default latex cite commands
168     ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
169     "citet" "citet*" "citep" "citep*"
170     "citealt" "citealt*" "citealp" "citealp*"
171     "citenum" "citetext"
172     "citeauthor" "citeauthor*"
173     "citeyear" "citeyear*"
174     "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
175     ;; biblatex commands
176     ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
177     "Cite"
178     "parencite" "Parencite"
179     "footcite" "footcitetext"
180     "textcite" "Textcite"
181     "smartcite" "Smartcite"
182     "cite*" "parencite*" "supercite"
183     "autocite" "Autocite" "autocite*" "Autocite*"
184     "Citeauthor*"
185     "citetitle" "citetitle*"
186     "citedate" "citedate*"
187     "citeurl"
188     "fullcite" "footfullcite"
189     ;; "volcite" "Volcite" cannot support the syntax
190     "notecite" "Notecite"
191     "pnotecite" "Pnotecite"
192     "fnotecite"
193     ;; multicites. Very limited support for these.
194     "cites" "Cites" "parencites" "Parencites"
195     "footcites" "footcitetexts"
196     "smartcites" "Smartcites" "textcites" "Textcites"
197     "supercites" "autocites" "Autocites"
198     ;; for the bibentry package
199     "bibentry"
200     )
201   "List of citation types known in org-ref"
202   :type '(repeat :tag "List of citation types" string)
203   :group 'org-ref)
204 #+END_SRC
205
206 We need a hook variable to store user-defined bibtex entry cleaning functions
207 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
208 (defcustom org-ref-clean-bibtex-entry-hook nil
209   "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
210   :group 'org-ref
211   :type 'hook)
212 #+END_SRC
213
214 ** Program variables
215 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
216 (defvar org-ref-bibliography-files
217   nil
218   "variable to hold bibliography files to be searched")
219 #+END_SRC
220
221 ** org-mode / reftex setup
222
223 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.
224
225 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
226 (require 'reftex)
227 (defun org-mode-reftex-setup ()
228     (and (buffer-file-name)
229          (file-exists-p (buffer-file-name))
230          (global-auto-revert-mode t)
231          ;; I do not remember why I put this next line in. It doesn't
232          ;; work for org-files. Nothing very bad happens, but it gives
233          ;; an annoying error. Commenting it out for now.
234          ;(reftex-parse-all
235          )
236     (make-local-variable 'reftex-cite-format)
237     (setq reftex-cite-format 'org))
238
239 ;; define key for inserting citations
240 (define-key org-mode-map
241   (kbd org-ref-insert-cite-key)
242   org-ref-insert-cite-function)
243
244 (when org-ref-show-citation-on-enter
245  (setq org-ref-message-timer
246        (run-with-idle-timer 0.5 t 'org-ref-link-message)))
247
248 (defun org-ref-show-link-messages ()
249   "Turn on link messages. You will see a message in the
250 minibuffer when on a cite, ref or label link."
251   (interactive)
252   (setq org-ref-message-timer
253         (run-with-idle-timer 0.5 t 'org-ref-link-message))
254   )
255 (defun org-ref-cancel-link-messages ()
256   "Stop showing messages in minibuffer when on a link."
257   (interactive)
258   (cancel-timer org-ref-message-timer))
259
260 ;; this approach caused the selected region to not be highlighted any more.
261 ; (add-hook 'post-command-hook 'org-ref-link-message))
262 ; (remove-hook 'post-command-hook 'org-ref-link-message))
263
264 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
265
266 (eval-after-load 'reftex-vars
267   '(progn
268       (add-to-list 'reftex-cite-format-builtin
269                    '(org "Org-mode citation"
270                          ((?\C-m . "cite:%l")     ; default
271                           (?d . ",%l")            ; for appending
272                           (?a . "autocite:%l")
273                           (?t . "citet:%l")
274                           (?T . "citet*:%l")
275                           (?p . "citep:%l")
276                           (?P . "citep*:%l")
277                           (?h . "citeauthor:%l")
278                           (?H . "citeauthor*:%l")
279                           (?y . "citeyear:%l")
280                           (?x . "citetext:%l")
281                           (?n . "nocite:%l")
282                           )))))
283 #+END_SRC
284
285 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.
286
287 #+BEGIN_SRC emacs-lisp :tangle no
288 ;; add new format
289 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
290       (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W  . "textcite:%l")
291             (?z  . "newcite:%l"))))
292 #+END_SRC
293
294 You can define a new citation link like this:
295 #+BEGIN_SRC emacs-lisp :tangle no
296 (org-ref-define-citation-link "citez" ?z)
297 #+END_SRC
298
299 * Links
300 Most of this library is the creation of functional links to help with references and citations.
301 ** General utilities
302 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.
303
304 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
305 (defun org-ref-strip-string (string)
306   "strip leading and trailing whitespace from the string"
307   (replace-regexp-in-string
308    (concat search-whitespace-regexp "$" ) ""
309    (replace-regexp-in-string
310     (concat "^" search-whitespace-regexp ) "" string)))
311 #+END_SRC
312
313 It is helpful to make the previous function operate on a list of strings here.
314
315 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
316 (defun org-ref-split-and-strip-string (string)
317   "split key-string and strip keys. Assumes the key-string is comma delimited"
318   (mapcar 'org-ref-strip-string (split-string string ",")))
319 #+END_SRC
320
321 ** bibliography and bibliographystyle
322 *** An html bibliography
323
324 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.
325
326 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
327 (defun org-ref-reftex-get-bib-field (field entry &optional format)
328   "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
329   (let ((result))
330     (setq result (reftex-get-bib-field field entry format))
331     (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
332       (setq result (substring result 1 -1)))
333     (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
334       (setq result (substring result 1 -1)))
335       result))
336
337 (defun org-ref-reftex-format-citation (entry format)
338   "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
339 to the format argument. The format is a string with these percent escapes.
340
341 In the format, the following percent escapes will be expanded.
342
343 %l   The BibTeX label of the citation.
344 %a   List of author names, see also `reftex-cite-punctuation'.
345 %2a  Like %a, but abbreviate more than 2 authors like Jones et al.
346 %A   First author name only.
347 %e   Works like %a, but on list of editor names. (%2e and %E work a well)
348
349 It is also possible to access all other BibTeX database fields:
350 %b booktitle     %c chapter        %d edition    %h howpublished
351 %i institution   %j journal        %k key        %m month
352 %n number        %o organization   %p pages      %P first page
353 %r address       %s school         %u publisher  %t title
354 %v volume        %y year
355 %B booktitle, abbreviated          %T title, abbreviated
356 %U url
357 %D doi
358 %S series
359
360 Usually, only %l is needed.  The other stuff is mainly for the echo area
361 display, and for (setq reftex-comment-citations t).
362
363 %< as a special operator kills punctuation and space around it after the
364 string has been formatted.
365
366 A pair of square brackets indicates an optional argument, and RefTeX
367 will prompt for the values of these arguments.
368
369 Beware that all this only works with BibTeX database files.  When
370 citations are made from the \bibitems in an explicit thebibliography
371 environment, only %l is available."
372   ;; Format a citation from the info in the BibTeX ENTRY
373
374   (unless (stringp format) (setq format "\\cite{%l}"))
375
376   (if (and reftex-comment-citations
377            (string-match "%l" reftex-cite-comment-format))
378       (error "reftex-cite-comment-format contains invalid %%l"))
379
380   (while (string-match
381           "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
382           format)
383     (let ((n (string-to-number (match-string 4 format)))
384           (l (string-to-char (match-string 5 format)))
385           rpl b e)
386       (save-match-data
387         (setq rpl
388               (cond
389                ((= l ?l) (concat
390                           (org-ref-reftex-get-bib-field "&key" entry)
391                           (if reftex-comment-citations
392                               reftex-cite-comment-format
393                             "")))
394                ((= l ?a) (reftex-format-names
395                           (reftex-get-bib-names "author" entry)
396                           (or n 2)))
397                ((= l ?A) (car (reftex-get-bib-names "author" entry)))
398                ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
399                ((= l ?B) (reftex-abbreviate-title
400                           (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
401                ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
402                ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
403                ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
404                ((= l ?e) (reftex-format-names
405                           (reftex-get-bib-names "editor" entry)
406                           (or n 2)))
407                ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
408                ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
409                ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
410                ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
411                ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
412                ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
413                ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
414                ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
415                ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
416                ((= l ?P) (car (split-string
417                                (org-ref-reftex-get-bib-field "pages" entry)
418                                "[- .]+")))
419                ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
420                ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
421                ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
422                ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
423                ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
424                ;; strip enclosing brackets from title if they are there
425                ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
426                ((= l ?T) (reftex-abbreviate-title
427                           (org-ref-reftex-get-bib-field "title" entry)))
428                ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
429                ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
430
431       (if (string= rpl "")
432           (setq b (match-beginning 2) e (match-end 2))
433         (setq b (match-beginning 3) e (match-end 3)))
434       (setq format (concat (substring format 0 b) rpl (substring format e)))))
435   (while (string-match "%%" format)
436     (setq format (replace-match "%" t t format)))
437   (while (string-match "[ ,.;:]*%<" format)
438     (setq format (replace-match "" t t format)))
439   ;; also replace carriage returns, tabs, and multiple whitespaces
440   (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
441   format)
442
443 (defun org-ref-get-bibtex-entry-citation (key)
444   "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
445
446   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
447         (file) (entry) (bibtex-entry) (entry-type) (format))
448
449     (setq file (catch 'result
450                  (loop for file in org-ref-bibliography-files do
451                        (if (org-ref-key-in-file-p key (file-truename file))
452                            (throw 'result file)
453                          (message "%s not found in %s" key (file-truename file))))))
454
455     (with-temp-buffer
456       (insert-file-contents file)
457       (bibtex-search-entry key nil 0)
458       (setq bibtex-entry (bibtex-parse-entry))
459       (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
460       (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
461       (if format
462           (setq entry  (org-ref-reftex-format-citation bibtex-entry format))
463         (save-restriction
464           (bibtex-narrow-to-entry)
465           (setq entry (buffer-string)))))
466     entry))
467 #+END_SRC
468
469 #+RESULTS:
470 : org-ref-reftex-format-citation
471
472 Here is how to use the function. You call it with point in an entry in a bibtex file.
473
474 #+BEGIN_SRC emacs-lisp :tangle no
475 (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>."))
476   (org-ref-get-bibtex-entry-citation  "armiento-2014-high"))
477 #+END_SRC
478 #+RESULTS:
479 : 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>.
480
481 I am not sure why full author names are not used.
482
483 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
484
485 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
486 (defun org-ref-get-bibtex-keys ()
487   "return a list of unique keys in the buffer."
488   (let ((keys '()))
489     (org-element-map (org-element-parse-buffer) 'link
490       (lambda (link)
491         (let ((plist (nth 1 link)))
492           (when (-contains? org-ref-cite-types (plist-get plist ':type))
493             (dolist
494                 (key
495                  (org-ref-split-and-strip-string (plist-get plist ':path)))
496               (when (not (-contains? keys key))
497                 (setq keys (append keys (list key)))))))))
498     ;; Sort keys alphabetically
499     (setq keys (cl-sort keys 'string-lessp :key 'downcase))
500     keys))
501 #+END_SRC
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-html (key)
507   "returns an html string for the bibliography entry corresponding to key"
508
509   (format "<li><a id=\"%s\">[%s] %s</a></li>" key 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-html-bibliography ()
516   "Create an html bibliography when there are keys"
517   (let ((keys (org-ref-get-bibtex-keys)))
518     (when keys
519       (concat "<h1>Bibliography</h1>
520 <ul>"
521               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
522               "\n</ul>"))))
523 #+END_SRC
524
525 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.
526
527 *** An org bibliography
528 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.
529
530 First, we get the string for a single entry.
531 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
532 (defun org-ref-get-bibtex-entry-org (key)
533   "returns an org string for the bibliography entry corresponding to key"
534   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
535         (file) (entry) (bibtex-entry) (entry-type) (format))
536
537     (setq file (catch 'result
538                  (loop for file in org-ref-bibliography-files do
539                        (if (org-ref-key-in-file-p key (file-truename file))
540                            (throw 'result file)
541                          (message "%s not found in %s" key (file-truename file))))))
542
543     (with-temp-buffer
544       (insert-file-contents file)
545       (bibtex-search-entry key nil 0)
546       (setq entry (bibtex-parse-entry))
547       (format "** %s - %s
548   :PROPERTIES:
549   %s
550   :END:
551 " (org-ref-reftex-get-bib-field "author" entry)
552 (org-ref-reftex-get-bib-field "title" entry)
553 (concat "   :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
554         (mapconcat (lambda (element) (format "   :%s: %s"
555                                              (upcase (car element))
556                                              (cdr element)))
557                    entry
558                    "\n"))))))
559 #+END_SRC
560
561 Now, we loop over the keys, and combine all the entries into a bibliography.
562 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
563 (defun org-ref-get-org-bibliography ()
564   "Create an org bibliography when there are keys"
565   (let ((keys (org-ref-get-bibtex-keys)))
566     (when keys
567       (concat "* Bibliography
568 "
569               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
570               "\n"))))
571 #+END_SRC
572
573 *** An ascii bibliography
574
575 This function gets the html for one entry.
576
577 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
578 (defun org-ref-get-bibtex-entry-ascii (key)
579   "returns an ascii string for the bibliography entry corresponding to key"
580
581   (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
582 #+END_SRC
583
584 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
585
586 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
587 (defun org-ref-get-ascii-bibliography ()
588   "Create an html bibliography when there are keys"
589   (let ((keys (org-ref-get-bibtex-keys)))
590     (when keys
591       (concat
592 "Bibliography
593 =============
594 "
595               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
596               "\n"))))
597 #+END_SRC
598
599
600 *** the links
601 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.
602
603 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
604 (org-add-link-type "bibliography"
605                    ;; this code is run on clicking. The bibliography
606                    ;; may contain multiple files. this code finds the
607                    ;; one you clicked on and opens it.
608                    (lambda (link-string)
609                        ;; get link-string boundaries
610                        ;; we have to go to the beginning of the line, and then search forward
611
612                      (let* ((bibfile)
613                             ;; object is the link you clicked on
614                             (object (org-element-context))
615                             (link-string-beginning)
616                             (link-string-end))
617
618                      (save-excursion
619                        (goto-char (org-element-property :begin object))
620                        (search-forward link-string nil nil 1)
621                        (setq link-string-beginning (match-beginning 0))
622                        (setq link-string-end (match-end 0)))
623
624                        ;; We set the reftex-default-bibliography
625                        ;; here. it should be a local variable only in
626                        ;; the current buffer. We need this for using
627                        ;; reftex to do citations.
628                        (set (make-local-variable 'reftex-default-bibliography)
629                             (split-string (org-element-property :path object) ","))
630
631                        ;; now if we have comma separated bibliographies
632                        ;; we find the one clicked on. we want to
633                        ;; search forward to next comma from point
634                        (save-excursion
635                          (if (search-forward "," link-string-end 1 1)
636                              (setq key-end (- (match-end 0) 1)) ; we found a match
637                            (setq key-end (point)))) ; no comma found so take the point
638                        ;; and backward to previous comma from point
639                        (save-excursion
640                          (if (search-backward "," link-string-beginning 1 1)
641                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
642                            (setq key-beginning (point)))) ; no match found
643                        ;; save the key we clicked on.
644                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
645                        (find-file bibfile))) ; open file on click
646
647                      ;; formatting code
648                    (lambda (keyword desc format)
649                      (cond
650                       ((eq format 'org) (org-ref-get-org-bibliography))
651                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
652                       ((eq format 'html) (org-ref-get-html-bibliography))
653                       ((eq format 'latex)
654                        ;; write out the latex bibliography command
655                        (format "\\bibliography{%s}" (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
656                                                                                                       (mapcar 'expand-file-name
657                                                                                                               (split-string keyword ","))
658                                                                                                       ",")))))))
659
660 #+END_SRC
661
662 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.
663
664 #+BEGIN_LaTeX
665   \input{project-description.bbl}
666 #+END_LaTeX
667
668 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.
669
670 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
671 (org-add-link-type "nobibliography"
672                    ;; this code is run on clicking. The bibliography
673                    ;; may contain multiple files. this code finds the
674                    ;; one you clicked on and opens it.
675                    (lambda (link-string)
676                        ;; get link-string boundaries
677                        ;; we have to go to the beginning of the line, and then search forward
678
679                      (let* ((bibfile)
680                             ;; object is the link you clicked on
681                             (object (org-element-context))
682
683                             (link-string-beginning)
684                             (link-string-end))
685
686                      (save-excursion
687                        (goto-char (org-element-property :begin object))
688                        (search-forward link-string nil nil 1)
689                        (setq link-string-beginning (match-beginning 0))
690                        (setq link-string-end (match-end 0)))
691
692                        ;; We set the reftex-default-bibliography
693                        ;; here. it should be a local variable only in
694                        ;; the current buffer. We need this for using
695                        ;; reftex to do citations.
696                        (set (make-local-variable 'reftex-default-bibliography)
697                             (split-string (org-element-property :path object) ","))
698
699                        ;; now if we have comma separated bibliographies
700                        ;; we find the one clicked on. we want to
701                        ;; search forward to next comma from point
702                        (save-excursion
703                          (if (search-forward "," link-string-end 1 1)
704                              (setq key-end (- (match-end 0) 1)) ; we found a match
705                            (setq key-end (point)))) ; no comma found so take the point
706                        ;; and backward to previous comma from point
707                        (save-excursion
708                          (if (search-backward "," link-string-beginning 1 1)
709                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
710                            (setq key-beginning (point)))) ; no match found
711                        ;; save the key we clicked on.
712                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
713                        (find-file bibfile))) ; open file on click
714
715                      ;; formatting code
716                    (lambda (keyword desc format)
717                      (cond
718                       ((eq format 'org) (org-ref-get-org-bibliography))
719                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
720                       ((eq format 'html) (org-ref-get-html-bibliography))
721                       ((eq format 'latex)
722                        ;; write out the latex bibliography command
723
724 ;                      (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
725 ;                              (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
726 ;                                                                                (mapcar 'expand-file-name
727 ;                                                                                        (split-string keyword ","))
728 ;                                                                                ",")))
729
730                        (format "\\nobibliography{%s}"
731                                (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
732                                                                                  (mapcar 'expand-file-name
733                                                                                          (split-string keyword ","))
734                                                                                  ",")))
735
736                        ))))
737 #+END_SRC
738
739 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
740 (org-add-link-type "printbibliography"
741                    (lambda (arg) (message "Nothing implemented for clicking here."))
742                    (lambda (keyword desc format)
743                      (cond
744                       ((eq format 'org) (org-ref-get-org-bibliography))
745                       ((eq format 'html) (org-ref-get-html-bibliography))
746                       ((eq format 'latex)
747                        ;; write out the biblatex bibliography command
748                        "\\printbibliography"))
749 ))
750 #+END_SRC
751
752 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, ...
753
754 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
755 (org-add-link-type "bibliographystyle"
756                    (lambda (arg) (message "Nothing implemented for clicking here."))
757                    (lambda (keyword desc format)
758                      (cond
759                       ((eq format 'latex)
760                        ;; write out the latex bibliography command
761                        (format "\\bibliographystyle{%s}" keyword)))))
762 #+END_SRC
763
764 *** Completion for bibliography link
765 It would be nice
766
767 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
768 (defun org-bibliography-complete-link (&optional arg)
769  (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
770
771 (defun org-ref-insert-bibliography-link ()
772   "insert a bibliography with completion"
773   (interactive)
774   (insert (org-bibliography-complete-link)))
775 #+END_SRC
776
777 ** addbibresource
778 This is apparently used for biblatex.
779 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
780 (org-add-link-type "addbibresource"
781                    ;; this code is run on clicking. The addbibresource
782                    ;; may contain multiple files. this code finds the
783                    ;; one you clicked on and opens it.
784                    (lambda (link-string)
785                        ;; get link-string boundaries
786                        ;; we have to go to the beginning of the line, and then search forward
787
788                      (let* ((bibfile)
789                             ;; object is the link you clicked on
790                             (object (org-element-context))
791
792                             (link-string-beginning)
793                             (link-string-end))
794
795                      (save-excursion
796                        (goto-char (org-element-property :begin object))
797                        (search-forward link-string nil nil 1)
798                        (setq link-string-beginning (match-beginning 0))
799                        (setq link-string-end (match-end 0)))
800
801                        ;; We set the reftex-default-addbibresource
802                        ;; here. it should be a local variable only in
803                        ;; the current buffer. We need this for using
804                        ;; reftex to do citations.
805                        (set (make-local-variable 'reftex-default-addbibresource)
806                             (split-string (org-element-property :path object) ","))
807
808                        ;; now if we have comma separated bibliographies
809                        ;; we find the one clicked on. we want to
810                        ;; search forward to next comma from point
811                        (save-excursion
812                          (if (search-forward "," link-string-end 1 1)
813                              (setq key-end (- (match-end 0) 1)) ; we found a match
814                            (setq key-end (point)))) ; no comma found so take the point
815                        ;; and backward to previous comma from point
816                        (save-excursion
817                          (if (search-backward "," link-string-beginning 1 1)
818                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
819                            (setq key-beginning (point)))) ; no match found
820                        ;; save the key we clicked on.
821                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
822                        (find-file bibfile))) ; open file on click
823
824                      ;; formatting code
825                    (lambda (keyword desc format)
826                      (cond
827                       ((eq format 'html) (format "")); no output for html
828                       ((eq format 'latex)
829                          ;; write out the latex addbibresource command
830                        (format "\\addbibresource{%s}" keyword)))))
831 #+END_SRC
832
833 ** List of Figures
834
835 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.
836
837 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
838 (defun org-ref-list-of-figures (&optional arg)
839   "Generate buffer with list of figures in them"
840   (interactive)
841   (save-excursion (widen)
842   (let* ((c-b (buffer-name))
843          (counter 0)
844          (list-of-figures
845           (org-element-map (org-element-parse-buffer) 'link
846             (lambda (link)
847               "create a link for to the figure"
848               (when
849                   (and (string= (org-element-property :type link) "file")
850                        (string-match-p
851                         "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
852                         (org-element-property :path link)))
853                 (incf counter)
854
855                 (let* ((start (org-element-property :begin link))
856                        (parent (car (cdr (org-element-property :parent link))))
857                        (caption (caaar (plist-get parent :caption)))
858                        (name (plist-get parent :name)))
859                   (if caption
860                       (format
861                        "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
862                        c-b start counter (or name "") caption)
863                     (format
864                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
865                      c-b start counter (or name "")))))))))
866     (switch-to-buffer "*List of Figures*")
867     (setq buffer-read-only nil)
868     (org-mode)
869     (erase-buffer)
870     (insert (mapconcat 'identity list-of-figures ""))
871     (setq buffer-read-only t)
872     (use-local-map (copy-keymap org-mode-map))
873     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
874
875 (org-add-link-type
876  "list-of-figures"
877  'org-ref-list-of-figures ; on click
878  (lambda (keyword desc format)
879    (cond
880     ((eq format 'latex)
881      (format "\\listoffigures")))))
882 #+END_SRC
883
884 ** List of Tables
885
886 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
887 (defun org-ref-list-of-tables (&optional arg)
888   "Generate a buffer with a list of tables"
889   (interactive)
890   (save-excursion
891   (widen)
892   (let* ((c-b (buffer-name))
893          (counter 0)
894          (list-of-tables
895           (org-element-map (org-element-parse-buffer 'element) 'table
896             (lambda (table)
897               "create a link for to the table"
898               (incf counter)
899               (let ((start (org-element-property :begin table))
900                     (name  (org-element-property :name table))
901                     (caption (caaar (org-element-property :caption table))))
902                 (if caption
903                     (format
904                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
905                      c-b start counter (or name "") caption)
906                   (format
907                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
908                    c-b start counter (or name ""))))))))
909     (switch-to-buffer "*List of Tables*")
910     (setq buffer-read-only nil)
911     (org-mode)
912     (erase-buffer)
913     (insert (mapconcat 'identity list-of-tables ""))
914     (setq buffer-read-only t)
915     (use-local-map (copy-keymap org-mode-map))
916     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
917
918 (org-add-link-type
919  "list-of-tables"
920  'org-ref-list-of-tables
921  (lambda (keyword desc format)
922    (cond
923     ((eq format 'latex)
924      (format "\\listoftables")))))
925 #+END_SRC
926 ** label
927
928 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 org-mode format for labels, tblnames too.
929
930 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
931 (defun org-ref-count-labels (label)
932   "Counts number of matches for label in the document"
933   (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
934      ;; for tblname, it is not enough to get word boundary
935      ;; tab-little and tab-little-2 match then.
936      (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
937      (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max))
938      ;; this is the org-format #+label:
939      (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
940      (let ((custom-id-count 0))
941        (org-map-entries
942         (lambda ()
943           (when (string= label (org-entry-get (point) "CUSTOM_ID"))
944             (setq custom-id-count (+ 1 custom-id-count)))))
945        custom-id-count)))
946
947 (org-add-link-type
948  "label"
949  (lambda (label)
950    "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
951    (let ((count (org-ref-count-labels label)))
952    (message (format "%s occurence%s"
953                     count
954                     (if (or (= count 0)
955                               (> count 1))
956                         "s"
957                       ""))
958                     (org-ref-count-labels label))))
959  (lambda (keyword desc format)
960    (cond
961     ((eq format 'html) (format "(<label>%s</label>)" path))
962     ((eq format 'latex)
963      (format "\\label{%s}" keyword)))))
964 #+END_SRC
965
966 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.
967
968 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
969 (defun org-label-store-link ()
970   "store a link to a label. The output will be a ref to that label"
971   ;; First we have to make sure we are on a label link.
972   (let* ((object (org-element-context)))
973     (when (and (equal (org-element-type object) 'link)
974                (equal (org-element-property :type object) "label"))
975       (org-store-link-props
976        :type "ref"
977        :link (concat "ref:" (org-element-property :path object))))
978
979     ;; Store link on table
980     (when (equal (org-element-type object) 'table)
981       (org-store-link-props
982        :type "ref"
983        :link (concat "ref:" (org-element-property :name object))))
984
985 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
986     ;; store link on heading with custom_id
987 ;    (when (and (equal (org-element-type object) 'headline)
988 ;              (org-entry-get (point) "CUSTOM_ID"))
989 ;      (org-store-link-props
990 ;       :type "ref"
991 ;       :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
992
993     ;; and to #+label: lines
994     (when (and (equal (org-element-type object) 'paragraph)
995                (org-element-property :name object))
996       (org-store-link-props
997        :type "ref"
998        :link (concat "ref:" (org-element-property :name object))))
999 ))
1000
1001 (add-hook 'org-store-link-functions 'org-label-store-link)
1002 #+END_SRC
1003 ** ref
1004
1005 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.
1006
1007 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
1008
1009 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1010 (org-add-link-type
1011  "ref"
1012  (lambda (label)
1013    "on clicking goto the label. Navigate back with C-c &"
1014    (org-mark-ring-push)
1015    ;; next search from beginning of the buffer
1016
1017    ;; it is possible you would not find the label if narrowing is in effect
1018    (widen)
1019
1020    (unless
1021        (or
1022         ;; our label links
1023         (progn
1024           (goto-char (point-min))
1025           (re-search-forward (format "label:%s\\b" label) nil t))
1026
1027         ;; a latex label
1028         (progn
1029           (goto-char (point-min))
1030           (re-search-forward (format "\\label{%s}" label) nil t))
1031
1032         ;; #+label: name  org-definition
1033         (progn
1034           (goto-char (point-min))
1035           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1036
1037         ;; org tblname
1038         (progn
1039           (goto-char (point-min))
1040           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1041
1042 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1043 ;; you need [[#label]] links.
1044         ;; CUSTOM_ID
1045 ;       (progn
1046 ;         (goto-char (point-min))
1047 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1048         )
1049      ;; we did not find anything, so go back to where we came
1050      (org-mark-ring-goto)
1051      (error "%s not found" label))
1052    (org-show-entry)
1053    (message "go back with (org-mark-ring-goto) `C-c &`"))
1054  ;formatting
1055  (lambda (keyword desc format)
1056    (cond
1057     ((eq format 'html) (format "(<ref>%s</ref>)" path))
1058     ((eq format 'latex)
1059      (format "\\ref{%s}" keyword)))))
1060 #+END_SRC
1061
1062 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 org and latex labels, custom_ids, and table names as potential items to make a ref link to.
1063
1064 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1065 (defun org-ref-get-org-labels ()
1066  "find #+LABEL: labels"
1067   (save-excursion
1068     (goto-char (point-min))
1069     (let ((matches '()))
1070       (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1071         (add-to-list 'matches (match-string-no-properties 1) t))
1072 matches)))
1073 #+END_SRC
1074
1075 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1076 (defun org-ref-get-custom-ids ()
1077  "return a list of custom_id properties in the buffer"
1078  (let ((results '()) custom_id)
1079    (org-map-entries
1080     (lambda ()
1081       (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1082         (when (not (null custom_id))
1083           (setq results (append results (list custom_id)))))))
1084 results))
1085 #+END_SRC
1086
1087 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
1088 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1089 (defun org-ref-get-latex-labels ()
1090   (save-excursion
1091     (goto-char (point-min))
1092     (let ((matches '()))
1093       (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1094         (add-to-list 'matches (match-string-no-properties 1) t))
1095 matches)))
1096 #+END_SRC
1097
1098 Finally, we get the table names.
1099
1100 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1101 (defun org-ref-get-tblnames ()
1102   (org-element-map (org-element-parse-buffer 'element) 'table
1103     (lambda (table)
1104       (org-element-property :name table))))
1105 #+END_SRC
1106
1107 Now, we can put all the labels together which will give us a list of candidates.
1108
1109 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1110 (defun org-ref-get-labels ()
1111   "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
1112   (save-excursion
1113     (save-restriction
1114       (widen)
1115       (goto-char (point-min))
1116       (let ((matches '()))
1117         (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1118           (add-to-list 'matches (match-string-no-properties 1) t))
1119         (append matches (org-ref-get-org-labels) (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
1120 #+END_SRC
1121
1122 Let us make a helm function to insert a label link. This will help you enter unique labels.
1123 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1124 (defun org-ref-helm-insert-label-link ()
1125   "Insert a label link. helm just shows you what labels already exist.
1126 If you are on a label link, replace it."
1127   (interactive)
1128   (let* ((labels (org-ref-get-labels))
1129          (cb (current-buffer)))
1130     (helm :sources `(((name . "Existing labels")
1131                       (candidates . ,labels)
1132                       ;; default action is to open to the label
1133                       (action . (lambda (label)
1134                                   ;; unfortunately I do not have markers here
1135                                   (org-open-link-from-string (format "ref:%s" label))))
1136                       ;; if you select a label, replace current one
1137                       (action . (lambda (label)
1138                                   (switch-to-buffer ,cb)
1139                                   (cond
1140                                    ;;  no prefix or on a link
1141                                    ((equal helm-current-prefix-arg nil)
1142                                     (let* ((object (org-element-context))
1143                                            (last-char (save-excursion
1144                                                         (goto-char (org-element-property :end object))
1145                                                         (backward-char)
1146                                                         (if (looking-at " ")
1147                                                             " "
1148                                                           ""))))
1149                                       (when (-contains? '("label")
1150                                                         (org-element-property :type object))
1151                                           ;; we are on a link, so replace it.
1152                                         (setf
1153                                            (buffer-substring
1154                                             (org-element-property :begin object)
1155                                             (org-element-property :end object))
1156                                            (concat
1157                                             (replace-regexp-in-string
1158                                              (org-element-property :path object)
1159                                              label
1160                                              (org-element-property :raw-link object))
1161                                             last-char)))))
1162                                    ;; no prefix options defined
1163                                    ))))
1164                      ;; no matching selection creates a new label
1165                      ((name . "Create new label")
1166                       (dummy)
1167                       ;; default action creates a new label, or replaces old one
1168                       (action .  (lambda (label)
1169                                    (switch-to-buffer ,cb)
1170                                    (let* ((object (org-element-context))
1171                                           (last-char (save-excursion
1172                                                        (goto-char (org-element-property :end object))
1173                                                        (backward-char)
1174                                                        (if (looking-at " ")
1175                                                            " "
1176                                                          ""))))
1177                                      (if (-contains? '("label")
1178                                                      (org-element-property :type object))
1179                                          ;; we are on a link, so replace it.
1180                                          (setf
1181                                           (buffer-substring
1182                                            (org-element-property :begin object)
1183                                            (org-element-property :end object))
1184                                           (concat
1185                                            (replace-regexp-in-string
1186                                             (org-element-property :path object)
1187                                             helm-pattern
1188                                             (org-element-property :raw-link object))
1189                                            last-char))
1190                                        ;; new link
1191                                        (insert
1192                                         (concat
1193                                          "label:"
1194                                          (or label
1195                                              helm-pattern))))))))))))
1196 #+END_SRC
1197
1198 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.
1199
1200 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1201 (defun org-ref-complete-link (&optional arg)
1202   "Completion function for ref links"
1203   (let ((label))
1204     (setq label (completing-read "label: " (org-ref-get-labels)))
1205     (format "ref:%s" label)))
1206 #+END_SRC
1207
1208 Alternatively, you may want to just call a function that inserts a link with completion:
1209
1210 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1211 (defun org-ref-insert-ref-link ()
1212  (interactive)
1213  (insert (org-ref-complete-link)))
1214 #+END_SRC
1215
1216 Another alternative ref insertion is to use helm.
1217
1218 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1219 (defun org-ref-helm-insert-ref-link ()
1220   "Helm menu to insert ref links to labels in the document.
1221 If you are on link, replace with newly selected label.
1222 Use C-u to insert a different kind of ref link.
1223 "
1224   (interactive)
1225   (let* ((labels (org-ref-get-labels))
1226          (contexts (mapcar 'org-ref-get-label-context labels))
1227          (cb (current-buffer)))
1228
1229     (helm :input (thing-at-point 'word)
1230           :sources `(((name . "Available labels to ref")
1231                       (candidates . ,(loop for label in labels
1232                                            for context in contexts
1233                                            ;; we do some kludgy adding spaces
1234                                            ;; and bars to make it "easier" to
1235                                            ;; see in helm.
1236                                            collect (cons (concat
1237                                                           label "\n"
1238                                                           (mapconcat
1239                                                            (lambda (x)
1240                                                              (concat "   |" x))
1241                                                            (split-string context "\n")
1242                                                            "\n"
1243                                                            ) "\n\n") label)))
1244                       ;; default action to replace or insert ref link.
1245                       (action . (lambda (label)
1246                                   (switch-to-buffer ,cb)
1247
1248                                   (cond
1249                                    ;;  no prefix or on a link
1250                                    ((equal helm-current-prefix-arg nil)
1251                                     (let* ((object (org-element-context))
1252                                            (last-char (save-excursion
1253                                                         (goto-char (org-element-property :end object))
1254                                                         (backward-char)
1255                                                         (if (looking-at " ")
1256                                                             " "
1257                                                           ""))))
1258                                       (if (-contains? '("ref" "eqref" "pageref" "nameref")
1259                                                       (org-element-property :type object))
1260                                           ;; we are on a link, so replace it.
1261                                           (setf
1262                                            (buffer-substring
1263                                             (org-element-property :begin object)
1264                                             (org-element-property :end object))
1265                                            (concat
1266                                             (replace-regexp-in-string
1267                                              (org-element-property :path object)
1268                                              label
1269                                              (org-element-property :raw-link object))
1270                                             last-char))
1271                                         ;; insert a new link
1272                                         (insert
1273                                          (concat
1274                                           "ref:" label))
1275                                         )))
1276                                    ;; one prefix, alternate ref link
1277                                    ((equal helm-current-prefix-arg '(4))
1278                                     (insert
1279                                      (concat
1280                                       (helm :sources '((name . "Ref link types")
1281                                                        (candidates . ("ref" "eqref" "pageref" "nameref"))
1282                                                        (action . (lambda (x) x))))
1283                                       ":" label)))
1284                                    ))))))))
1285 #+END_SRC
1286
1287 #+RESULTS:
1288 : org-ref-helm-insert-ref-link
1289
1290 ** pageref
1291
1292 This refers to the page of a label in LaTeX.
1293
1294 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1295 (org-add-link-type
1296  "pageref"
1297  (lambda (label)
1298    "on clicking goto the label. Navigate back with C-c &"
1299    (org-mark-ring-push)
1300    ;; next search from beginning of the buffer
1301    (widen)
1302    (unless
1303        (or
1304         ;; our label links
1305         (progn
1306           (goto-char (point-min))
1307           (re-search-forward (format "label:%s\\b" label) nil t))
1308
1309         ;; a latex label
1310         (progn
1311           (goto-char (point-min))
1312           (re-search-forward (format "\\label{%s}" label) nil t))
1313
1314         ;; #+label: name  org-definition
1315         (progn
1316           (goto-char (point-min))
1317           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1318
1319         ;; org tblname
1320         (progn
1321           (goto-char (point-min))
1322           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1323
1324 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1325 ;; you need [[#label]] links.
1326         ;; CUSTOM_ID
1327 ;       (progn
1328 ;         (goto-char (point-min))
1329 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1330         )
1331      ;; we did not find anything, so go back to where we came
1332      (org-mark-ring-goto)
1333      (error "%s not found" label))
1334    (message "go back with (org-mark-ring-goto) `C-c &`"))
1335  ;formatting
1336  (lambda (keyword desc format)
1337    (cond
1338     ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1339     ((eq format 'latex)
1340      (format "\\pageref{%s}" keyword)))))
1341 #+END_SRC
1342
1343 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1344 (defun org-pageref-complete-link (&optional arg)
1345   "Completion function for ref links"
1346   (let ((label))
1347     (setq label (completing-read "label: " (org-ref-get-labels)))
1348     (format "ref:%s" label)))
1349 #+END_SRC
1350
1351 Alternatively, you may want to just call a function that inserts a link with completion:
1352
1353 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1354 (defun org-pageref-insert-ref-link ()
1355  (interactive)
1356  (insert (org-pageref-complete-link)))
1357 #+END_SRC
1358
1359 ** nameref
1360
1361 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.
1362
1363 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1364 (org-add-link-type
1365  "nameref"
1366  (lambda (label)
1367    "on clicking goto the label. Navigate back with C-c &"
1368    (org-mark-ring-push)
1369    ;; next search from beginning of the buffer
1370    (widen)
1371    (unless
1372        (or
1373         ;; a latex label
1374         (progn
1375           (goto-char (point-min))
1376           (re-search-forward (format "\\label{%s}" label) nil t))
1377         )
1378      ;; we did not find anything, so go back to where we came
1379      (org-mark-ring-goto)
1380      (error "%s not found" label))
1381    (message "go back with (org-mark-ring-goto) `C-c &`"))
1382  ;formatting
1383  (lambda (keyword desc format)
1384    (cond
1385     ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1386     ((eq format 'latex)
1387      (format "\\nameref{%s}" keyword)))))
1388 #+END_SRC
1389
1390 ** eqref
1391 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1392
1393 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1394 (org-add-link-type
1395  "eqref"
1396  (lambda (label)
1397    "on clicking goto the label. Navigate back with C-c &"
1398    (org-mark-ring-push)
1399    ;; next search from beginning of the buffer
1400    (widen)
1401    (goto-char (point-min))
1402    (unless
1403        (or
1404         ;; search forward for the first match
1405         ;; our label links
1406         (re-search-forward (format "label:%s" label) nil t)
1407         ;; a latex label
1408         (re-search-forward (format "\\label{%s}" label) nil t)
1409         ;; #+label: name  org-definition
1410         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1411      (org-mark-ring-goto)
1412      (error "%s not found" label))
1413    (message "go back with (org-mark-ring-goto) `C-c &`"))
1414  ;formatting
1415  (lambda (keyword desc format)
1416    (cond
1417     ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1418     ((eq format 'latex)
1419      (format "\\eqref{%s}" keyword)))))
1420 #+END_SRC
1421
1422 ** cite
1423 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.
1424
1425 *** Implementing the click actions of cite
1426
1427 **** Getting the key we clicked on
1428 The first thing we need is to get the bibtex key we clicked on.
1429
1430 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1431 (defun org-ref-get-bibtex-key-under-cursor ()
1432   "returns key under the bibtex cursor. We search forward from
1433 point to get a comma, or the end of the link, and then backwards
1434 to get a comma, or the beginning of the link. that delimits the
1435 keyword we clicked on. We also strip the text properties."
1436   (interactive)
1437   (let* ((object (org-element-context))
1438          (link-string (org-element-property :path object)))
1439     ;; you may click on the part before the citations. here we make
1440     ;; sure to move to the beginning so you get the first citation.
1441     (let ((cp (point)))
1442       (goto-char (org-element-property :begin object))
1443       (search-forward link-string (org-element-property :end object))
1444       (goto-char (match-beginning 0))
1445       ;; check if we clicked before the path and move as needed.
1446       (unless (< cp (point))
1447         (goto-char cp)))
1448
1449     (if (not (org-element-property :contents-begin object))
1450         ;; this means no description in the link
1451         (progn
1452           ;; we need the link path start and end
1453           (save-excursion
1454             (goto-char (org-element-property :begin object))
1455             (search-forward link-string nil nil 1)
1456             (setq link-string-beginning (match-beginning 0))
1457             (setq link-string-end (match-end 0)))
1458
1459           ;; The key is the text between commas, or the link boundaries
1460           (save-excursion
1461             (if (search-forward "," link-string-end t 1)
1462                 (setq key-end (- (match-end 0) 1)) ; we found a match
1463               (setq key-end link-string-end))) ; no comma found so take the end
1464           ;; and backward to previous comma from point which defines the start character
1465           (save-excursion
1466             (if (search-backward "," link-string-beginning 1 1)
1467                 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1468               (setq key-beginning link-string-beginning))) ; no match found
1469           ;; save the key we clicked on.
1470           (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1471           (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1472           bibtex-key)
1473       ;; link with description. assume only one key
1474       link-string)))
1475 #+END_SRC
1476
1477 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.
1478
1479 **** Getting the bibliographies
1480 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1481 (defun org-ref-find-bibliography ()
1482   "find the bibliography in the buffer.
1483 This function sets and returns cite-bibliography-files, which is a list of files
1484 either from bibliography:f1.bib,f2.bib
1485 \bibliography{f1,f2}
1486 internal bibliographies
1487
1488 falling back to what the user has set in org-ref-default-bibliography
1489 "
1490   (interactive)
1491   (catch 'result
1492     (save-excursion
1493       (goto-char (point-min))
1494       ;;  look for a bibliography link
1495       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1496         (setq org-ref-bibliography-files
1497               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1498         (throw 'result org-ref-bibliography-files))
1499
1500
1501       ;; we did not find a bibliography link. now look for \bibliography
1502       (goto-char (point-min))
1503       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1504         ;; split, and add .bib to each file
1505         (setq org-ref-bibliography-files
1506               (mapcar (lambda (x) (concat x ".bib"))
1507                       (mapcar 'org-ref-strip-string
1508                               (split-string (match-string 1) ","))))
1509         (throw 'result org-ref-bibliography-files))
1510
1511       ;; no bibliography found. maybe we need a biblatex addbibresource
1512       (goto-char (point-min))
1513       ;;  look for a bibliography link
1514       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1515         (setq org-ref-bibliography-files
1516               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1517         (throw 'result org-ref-bibliography-files))
1518
1519       ;; we did not find anything. use defaults
1520       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1521
1522     ;; set reftex-default-bibliography so we can search
1523     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1524     org-ref-bibliography-files)
1525 #+END_SRC
1526
1527 **** Finding the bibliography file a key is in
1528 Now, we can see if an entry is in a file.
1529
1530 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1531 (defun org-ref-key-in-file-p (key filename)
1532   "determine if the key is in the file"
1533   (interactive "skey: \nsFile: ")
1534   (save-current-buffer
1535     (let ((bibtex-files (list filename)))
1536       (bibtex-search-entry key t))))
1537 #+END_SRC
1538
1539 Finally, we want to know which file the key is in.
1540
1541 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1542 (defun org-ref-get-bibtex-key-and-file (&optional key)
1543   "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1544  (interactive)
1545  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1546        (file))
1547    (unless key
1548      (setq key (org-ref-get-bibtex-key-under-cursor)))
1549    (setq file     (catch 'result
1550                     (loop for file in org-ref-bibliography-files do
1551                           (if (org-ref-key-in-file-p key (file-truename file))
1552                               (throw 'result file)))))
1553    (cons key file)))
1554 #+END_SRC
1555
1556 **** convenience functions to act on citation at point
1557      :PROPERTIES:
1558      :ID:       af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1559      :END:
1560 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.
1561
1562 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1563 (defun org-ref-open-pdf-at-point ()
1564   "open the pdf for bibtex key under point if it exists"
1565   (interactive)
1566   (let* ((results (org-ref-get-bibtex-key-and-file))
1567          (key (car results))
1568          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1569     (if (file-exists-p pdf-file)
1570         (org-open-file pdf-file)
1571 (message "no pdf found for %s" key))))
1572
1573
1574 (defun org-ref-open-url-at-point ()
1575   "open the url for bibtex key under point."
1576   (interactive)
1577   (let* ((results (org-ref-get-bibtex-key-and-file))
1578          (key (car results))
1579          (bibfile (cdr results)))
1580     (save-excursion
1581       (with-temp-buffer
1582         (insert-file-contents bibfile)
1583         (bibtex-search-entry key)
1584         ;; I like this better than bibtex-url which does not always find
1585         ;; the urls
1586         (catch 'done
1587           (let ((url (bibtex-autokey-get-field "url")))
1588             (when  url
1589               (browse-url url)
1590               (throw 'done nil)))
1591
1592           (let ((doi (bibtex-autokey-get-field "doi")))
1593             (when doi
1594               (if (string-match "^http" doi)
1595                   (browse-url doi)
1596                 (browse-url (format "http://dx.doi.org/%s" doi)))
1597               (throw 'done nil))))))))
1598
1599
1600 (defun org-ref-open-notes-at-point ()
1601   "open the notes for bibtex key under point."
1602   (interactive)
1603   (let* ((results (org-ref-get-bibtex-key-and-file))
1604          (key (car results))
1605          (bibfile (cdr results)))
1606     (save-excursion
1607       (with-temp-buffer
1608         (insert-file-contents bibfile)
1609         (bibtex-search-entry key)
1610         (org-ref-open-bibtex-notes)))))
1611
1612
1613 (defun org-ref-citation-at-point ()
1614   "give message of current citation at point"
1615   (interactive)
1616   (let* ((cb (current-buffer))
1617         (results (org-ref-get-bibtex-key-and-file))
1618         (key (car results))
1619         (bibfile (cdr results)))
1620     (message "%s" (progn
1621                     (with-temp-buffer
1622                       (insert-file-contents bibfile)
1623                       (bibtex-search-entry key)
1624                       (org-ref-bib-citation))))))
1625
1626
1627 (defun org-ref-open-citation-at-point ()
1628   "open bibtex file to key at point"
1629   (interactive)
1630   (let* ((cb (current-buffer))
1631         (results (org-ref-get-bibtex-key-and-file))
1632         (key (car results))
1633         (bibfile (cdr results)))
1634     (find-file bibfile)
1635     (bibtex-search-entry key)))
1636 #+END_SRC
1637
1638 **** the actual minibuffer menu
1639 Now, we create the menu. This is a rewrite of the cite action. This makes the function extendable by users.
1640
1641 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1642 (defvar org-ref-cite-menu-funcs '()
1643  "Functions to run on cite click menu. Each entry is a list of (key menu-name function).
1644 The function must take no arguments and work on the key at point. Do not modify this variable, it is set to empty in the menu click function, and functions are conditionally added to it.")
1645
1646
1647 (defvar org-ref-user-cite-menu-funcs
1648   '(("C" "rossref" org-ref-crossref-at-point)
1649     ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1650     ("s" "Copy summary" org-ref-copy-entry-as-summary))
1651   "user-defined functions to run on bibtex key at point.")
1652
1653
1654 (defun org-ref-copy-entry-as-summary ()
1655   "Copy the bibtex entry for the citation at point as a summary."
1656   (interactive)
1657     (save-window-excursion
1658       (org-ref-open-citation-at-point)
1659       (kill-new (org-ref-bib-citation))))
1660
1661
1662 (defun org-ref-copy-entry-at-point-to-file ()
1663   "Copy the bibtex entry for the citation at point to NEW-FILE.
1664 Prompt for NEW-FILE includes bib files in org-ref-default-bibliography, and bib files in current working directory. You can also specify a new file."
1665   (interactive)
1666   (let ((new-file (ido-completing-read
1667                    "Copy to bibfile: "
1668                    (append org-ref-default-bibliography
1669                            (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1670         (key (org-ref-get-bibtex-key-under-cursor)))
1671     (save-window-excursion
1672       (org-ref-open-citation-at-point)
1673       (bibtex-copy-entry-as-kill))
1674
1675     (let ((bibtex-files (list (file-truename new-file))))
1676       (if (assoc key (bibtex-global-key-alist))
1677           (message "That key already exists in %s" new-file)
1678         ;; add to file
1679         (save-window-excursion
1680           (find-file new-file)
1681           (goto-char (point-max))
1682           ;; make sure we are at the beginning of a line.
1683           (unless (looking-at "^") (insert "\n\n"))
1684           (bibtex-yank)
1685           (save-buffer))))))
1686
1687
1688 (defun org-ref-get-doi-at-point ()
1689   "Get doi for key at point."
1690   (interactive)
1691   (let* ((results (org-ref-get-bibtex-key-and-file))
1692          (key (car results))
1693          (bibfile (cdr results))
1694          doi)
1695     (save-excursion
1696       (with-temp-buffer
1697         (insert-file-contents bibfile)
1698         (bibtex-search-entry key)
1699         (setq doi (bibtex-autokey-get-field "doi"))
1700         ;; in case doi is a url, remove the url part.
1701         (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1702
1703
1704 ;; functions that operate on key at point for click menu
1705 (defun org-ref-wos-at-point ()
1706   "open the doi in wos for bibtex key under point."
1707   (interactive)
1708   (doi-utils-wos (org-ref-get-doi-at-point)))
1709
1710
1711 (defun org-ref-wos-citing-at-point ()
1712   "open the doi in wos citing articles for bibtex key under point."
1713   (interactive)
1714   (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1715
1716
1717 (defun org-ref-wos-related-at-point ()
1718   "open the doi in wos related articles for bibtex key under point."
1719   (interactive)
1720   (doi-utils-wos-related (org-ref-get-doi-at-point)))
1721
1722
1723 (defun org-ref-google-scholar-at-point ()
1724   "open the doi in google scholar for bibtex key under point."
1725   (interactive)
1726   (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1727
1728
1729 (defun org-ref-pubmed-at-point ()
1730   "open the doi in pubmed for bibtex key under point."
1731   (interactive)
1732   (doi-utils-pubmed (org-ref-get-doi-at-point)))
1733
1734
1735 (defun org-ref-crossref-at-point ()
1736   "open the doi in crossref for bibtex key under point."
1737   (interactive)
1738   (doi-utils-crossref (org-ref-get-doi-at-point)))
1739
1740
1741 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1742   "action when a cite link is clicked on.
1743 Provides a menu of context sensitive actions. If the bibtex entry has a pdf, you get an option to open it. If there is a doi, you get a lot of options."
1744   (interactive)
1745   (let* ((results (org-ref-get-bibtex-key-and-file))
1746          (key (car results))
1747          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1748          (bibfile (cdr results))
1749          (url (save-excursion
1750                 (with-temp-buffer
1751                   (insert-file-contents bibfile)
1752                   (bibtex-search-entry key)
1753                   (bibtex-autokey-get-field "url"))))
1754          (doi (save-excursion
1755                 (with-temp-buffer
1756                   (insert-file-contents bibfile)
1757                   (bibtex-search-entry key)
1758                   ;; I like this better than bibtex-url which does not always find
1759                   ;; the urls
1760                   (bibtex-autokey-get-field "doi")))))
1761
1762     (when (string= "" doi) (setq doi nil))
1763     (when (string= "" url) (setq url nil))
1764     (setq org-ref-cite-menu-funcs '())
1765
1766     ;; open action
1767     (when
1768         bibfile
1769       (add-to-list
1770        'org-ref-cite-menu-funcs
1771        '("o" "pen" org-ref-open-citation-at-point)))
1772
1773     ;; pdf
1774     (when (file-exists-p pdf-file)
1775       (add-to-list
1776        'org-ref-cite-menu-funcs
1777        `("p" "df" ,org-ref-open-pdf-function) t))
1778
1779     ;; notes
1780     (add-to-list
1781      'org-ref-cite-menu-funcs
1782      '("n" "otes" org-ref-open-notes-at-point) t)
1783
1784     ;; url
1785     (when (or url doi)
1786       (add-to-list
1787        'org-ref-cite-menu-funcs
1788        '("u" "rl" org-ref-open-url-at-point) t))
1789
1790     ;; doi funcs
1791     (when doi
1792       (add-to-list
1793        'org-ref-cite-menu-funcs
1794        '("w" "os" org-ref-wos-at-point) t)
1795
1796       (add-to-list
1797        'org-ref-cite-menu-funcs
1798        '("c" "iting" org-ref-wos-citing-at-point) t)
1799
1800       (add-to-list
1801        'org-ref-cite-menu-funcs
1802        '("r" "elated" org-ref-wos-related-at-point) t)
1803
1804       (add-to-list
1805        'org-ref-cite-menu-funcs
1806        '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1807
1808       (add-to-list
1809        'org-ref-cite-menu-funcs
1810        '("P" "ubmed" org-ref-pubmed-at-point) t))
1811
1812     ;; add user functions
1813     (dolist (tup org-ref-user-cite-menu-funcs)
1814       (add-to-list
1815        'org-ref-cite-menu-funcs
1816        tup t))
1817
1818     ;; finally quit
1819     (add-to-list
1820      'org-ref-cite-menu-funcs
1821      '("q" "uit" (lambda ())) t)
1822
1823     ;; now we make a menu
1824     ;; construct menu string as a message
1825     (message
1826      (concat
1827       (let* ((results (org-ref-get-bibtex-key-and-file))
1828              (key (car results))
1829              (bibfile (cdr results)))
1830         (save-excursion
1831           (with-temp-buffer
1832             (insert-file-contents bibfile)
1833             (bibtex-search-entry key)
1834             (org-ref-bib-citation))))
1835       "\n"
1836       (mapconcat
1837        (lambda (tup)
1838          (concat "[" (elt tup 0) "]"
1839                  (elt tup 1) " "))
1840        org-ref-cite-menu-funcs "")))
1841     ;; get the input
1842     (let* ((input (read-char-exclusive))
1843            (choice (assoc
1844                     (char-to-string input) org-ref-cite-menu-funcs)))
1845       ;; now run the function (2nd element in choice)
1846       (when choice
1847         (funcall
1848          (elt
1849           choice
1850           2))))))
1851 #+END_SRC
1852
1853 #+RESULTS:
1854 : org-ref-cite-onclick-minibuffer-menu
1855
1856 *** A function to format a cite link
1857
1858 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.
1859
1860 #+BEGIN_SRC emacs-lisp  :tangle no
1861 ;(defun org-ref-cite-link-format (keyword desc format)
1862 ;   (cond
1863 ;    ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1864 ;    ((eq format 'latex)
1865 ;     (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1866 ;            (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1867 ;            "}"))))
1868 #+END_SRC
1869
1870 *** The actual cite link
1871 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1872
1873 #+BEGIN_SRC emacs-lisp :tangle no
1874 ;(org-add-link-type
1875 ; "cite"
1876 ; 'org-ref-cite-onclick-minibuffer-menu
1877 ; 'org-ref-cite-link-format)
1878 #+END_SRC
1879
1880 *** Automatic definition of the cite links
1881 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.
1882
1883 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1884 (defmacro org-ref-make-completion-function (type)
1885   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1886      (interactive)
1887      (format "%s:%s"
1888              ,type
1889              (completing-read
1890               "bibtex key: "
1891               (let ((bibtex-files (org-ref-find-bibliography)))
1892                 (bibtex-global-key-alist))))))
1893 #+END_SRC
1894
1895 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.
1896
1897 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1898 (defmacro org-ref-make-format-function (type)
1899   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1900      (cond
1901       ((eq format 'org)
1902        (mapconcat
1903         (lambda (key)
1904           (format "[[#%s][%s]]" key key))
1905         (org-ref-split-and-strip-string keyword) ","))
1906
1907       ((eq format 'ascii)
1908        (concat "["
1909                (mapconcat
1910                 (lambda (key)
1911                   (format "%s" key))
1912                 (org-ref-split-and-strip-string keyword) ",") "]"))
1913
1914       ((eq format 'html)
1915        (mapconcat
1916         (lambda (key)
1917           (format "<a href=\"#%s\">%s</a>" key key))
1918         (org-ref-split-and-strip-string keyword) ","))
1919
1920       ((eq format 'latex)
1921        (if (string= (substring type -1) "s")
1922            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1923            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1924                                          (org-ref-split-and-strip-string keyword) ""))
1925          ;; bibtex format
1926        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1927                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1928                "}"))))))
1929 #+END_SRC
1930
1931
1932
1933 We create the links by mapping the function onto the list of defined link types.
1934
1935 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1936 (defun org-ref-format-citation-description (desc)
1937   "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 ::."
1938   (interactive)
1939   (cond
1940    ((string-match "::" desc)
1941     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1942    (t (format "[%s]" desc))))
1943
1944 (defun org-ref-define-citation-link (type &optional key)
1945   "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1946 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1947 and the completion function."
1948   (interactive "sCitation Type: \ncKey: ")
1949
1950   ;; create the formatting function
1951   (eval `(org-ref-make-format-function ,type))
1952
1953   (eval-expression
1954    `(org-add-link-type
1955      ,type
1956      org-ref-cite-onclick-function
1957      (quote ,(intern (format "org-ref-format-%s" type)))))
1958
1959   ;; create the completion function
1960   (eval `(org-ref-make-completion-function ,type))
1961
1962   ;; store new type so it works with adding citations, which checks
1963   ;; for existence in this list
1964   (add-to-list 'org-ref-cite-types type)
1965
1966   ;; and finally if a key is specified, we modify the reftex menu
1967   (when key
1968     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1969           (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1970                   `((,key  . ,(concat type ":%l")))))))
1971
1972 ;; create all the link types and their completion functions
1973 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1974 #+END_SRC
1975
1976 *** org-ref-insert-cite-link
1977 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.
1978
1979 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1980 (defun org-ref-insert-cite-link (alternative-cite)
1981   "Insert a default citation link using reftex. If you are on a link, it
1982 appends to the end of the link, otherwise, a new link is
1983 inserted. Use a prefix arg to get a menu of citation types."
1984   (interactive "P")
1985   (org-ref-find-bibliography)
1986   (let* ((object (org-element-context))
1987          (link-string-beginning (org-element-property :begin object))
1988          (link-string-end (org-element-property :end object))
1989          (path (org-element-property :path object)))
1990
1991     (if (not alternative-cite)
1992
1993         (cond
1994          ;; case where we are in a link
1995          ((and (equal (org-element-type object) 'link)
1996                (-contains? org-ref-cite-types (org-element-property :type object)))
1997           (goto-char link-string-end)
1998           ;; sometimes there are spaces at the end of the link
1999           ;; this code moves point pack until no spaces are there
2000           (while (looking-back " ") (backward-char))
2001           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
2002
2003          ;; We are next to a link, and we want to append
2004          ((save-excursion
2005             (backward-char)
2006             (and (equal (org-element-type (org-element-context)) 'link)
2007                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
2008           (while (looking-back " ") (backward-char))
2009           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
2010
2011          ;; insert fresh link
2012          (t
2013           (insert
2014            (concat org-ref-default-citation-link
2015                    ":"
2016                    (mapconcat 'identity (reftex-citation t) ",")))))
2017
2018       ;; you pressed a C-u so we run this code
2019       (reftex-citation)))
2020   )
2021 #+END_SRC
2022 cite:zhou-2004-first-lda-u,paier-2006-errat,boes-2015-estim-bulk
2023
2024
2025 #+RESULTS:
2026 : org-ref-insert-cite-link
2027
2028 *** Completion in cite links
2029 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.
2030
2031 #+BEGIN_SRC emacs-lisp  :tangle no
2032 (defun org-cite-complete-link (&optional arg)
2033   "Completion function for cite links"
2034   (format "%s:%s"
2035           org-ref-default-citation-link
2036           (completing-read
2037            "bibtex key: "
2038            (let ((bibtex-files (org-ref-find-bibliography)))
2039              (bibtex-global-key-alist)))))
2040 #+END_SRC
2041
2042 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
2043
2044 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2045 (defun org-ref-insert-cite-with-completion (type)
2046   "Insert a cite link with completion"
2047   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
2048   (insert (funcall (intern (format "org-%s-complete-link" type)))))
2049 #+END_SRC
2050
2051 ** Storing links to a bibtex entry
2052 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.
2053
2054 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2055 (defun org-ref-store-bibtex-entry-link ()
2056   "Save a citation link to the current bibtex entry. Saves in the default link type."
2057   (interactive)
2058   (let ((link (concat org-ref-default-citation-link
2059                  ":"
2060                  (save-excursion
2061                    (bibtex-beginning-of-entry)
2062                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
2063     (message "saved %s" link)
2064     (push (list link) org-stored-links)
2065     (car org-stored-links)))
2066 #+END_SRC
2067
2068 ** Index entries
2069 org-ref minimally supports index entries. To make an index in a file, you should put in the LaTeX header these lines
2070
2071
2072 #+LATEX_HEADER: \usepackage{makeidx}
2073 #+LATEX_HEADER: \makeindex
2074
2075
2076 Finally, put \makeindex at the end of the document where you want the index to appear. You will need to run the makeindex program at an appropriate point in your LaTeX to pdf, or use ox-manuscript, which will do it for you.
2077
2078
2079 Use index links to create entries (see http://en.wikibooks.org/wiki/LaTeX/Indexing). Clicking on an index link runs occur on the buffer for the entry. The link exports to LaTeX. Some links may need to be enclosed in double brackets if they have spaces in them.
2080
2081
2082 index:hello
2083 index:hello!Peter
2084 [[index:hello!Sam@\textsl{Sam}]]
2085 [[index:Lin@\textbf{Lin}]]
2086 [[index:Joe|textit]]
2087 [[index:Lin@\textbf{Lin}]]
2088 [[index:Peter|see {hello}]]
2089 [[index:Jen|seealso{Jenny}]]
2090
2091 index:encodings!input!cp850
2092
2093 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2094 (org-add-link-type
2095  "index"
2096  (lambda (path)
2097    (occur path))
2098
2099  (lambda (path desc format)
2100    (cond
2101     ((eq format 'latex)
2102       (format "\\index{%s}" path)))))
2103
2104 ;; this will generate a temporary index of entries in the file.
2105 (org-add-link-type
2106  "printindex"
2107  (lambda (path)
2108    (let ((*index-links* '())
2109          (*initial-letters* '()))
2110
2111      ;; get links
2112      (org-element-map (org-element-parse-buffer) 'link
2113        (lambda (link)
2114          (let ((type (nth 0 link))
2115                (plist (nth 1 link)))
2116
2117            (when (equal (plist-get plist ':type) "index")
2118              (add-to-list
2119               '*index-links*
2120               (cons (plist-get plist :path)
2121                     (format
2122                      "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2123 (current-buffer)
2124                      (plist-get plist :begin)  ;; position of link
2125                      ;; grab a description
2126                      (save-excursion
2127                        (goto-char (plist-get plist :begin))
2128                        (if (thing-at-point 'sentence)
2129                            ;; get a sentence
2130                            (replace-regexp-in-string
2131                             "\n" "" (thing-at-point 'sentence))
2132                          ;; or call it a link
2133                          "link")))))))))
2134
2135      ;; sort the links
2136      (setq *index-links*  (cl-sort *index-links* 'string-lessp :key 'car))
2137
2138      ;; now first letters
2139      (dolist (link *index-links*)
2140        (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2141
2142      ;; now create the index
2143      (switch-to-buffer (get-buffer-create "*index*"))
2144      (org-mode)
2145      (erase-buffer)
2146      (insert "#+TITLE: Index\n\n")
2147      (dolist (letter *initial-letters*)
2148        (insert (format "* %s\n" (upcase letter)))
2149        ;; now process the links
2150        (while (and
2151                ,*index-links*
2152                (string= letter (substring (car (car *index-links*)) 0 1)))
2153          (let ((link (pop *index-links*)))
2154            (insert (format "%s %s\n\n" (car link) (cdr link))))))
2155      (switch-to-buffer "*index*")))
2156  ;; formatting
2157  (lambda (path desc format)
2158    (cond
2159     ((eq format 'latex)
2160       (format "\\printindex")))))
2161 #+END_SRC
2162
2163 #+RESULTS:
2164 | lambda | (path)             | (let ((*index-links* (quote nil)) (*initial-letters* (quote nil))) (org-element-map (org-element-parse-buffer) (quote link) (lambda (link) (let ((type (nth 0 link)) (plist (nth 1 link))) (when (equal (plist-get plist (quote :type)) index) (add-to-list (quote *index-links*) (cons (plist-get plist :path) (format [[elisp:(progn (switch-to-buffer "%s") (goto-char %s))][%s]] (current-buffer) (plist-get plist :begin) (save-excursion (goto-char (plist-get plist :begin)) (if (thing-at-point (quote sentence)) (replace-regexp-in-string \n  (thing-at-point (quote sentence))) link))))))))) (setq *index-links* (cl-sort *index-links* (quote string-lessp) :key (quote car))) (dolist (link *index-links*) (add-to-list (quote *initial-letters*) (substring (car link) 0 1) t)) (switch-to-buffer (get-buffer-create *index*)) (org-mode) (erase-buffer) (insert #+TITLE: Index\n\n) (dolist (letter *initial-letters*) (insert (format * %s\n (upcase letter))) (while (and *index-links* (string= letter (substring (car (car *index-links*)) 0 1))) (let ((link (pop *index-links*))) (insert (format %s %s\n\n (car link) (cdr link)))))) (switch-to-buffer *index*)) |
2165 | lambda | (path desc format) | (cond ((eq format (quote latex)) (format \printindex)))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
2166
2167 ** Glossary
2168 org-ref provides some minimal support for a glossary. See http://en.wikibooks.org/wiki/LaTeX/Glossary for details. You need to put these lines in the header.
2169
2170 #+LATEX_HEADER: \usepackage{glossaries}
2171 #+LATEX_HEADER: \makeglossaries
2172
2173 And at the end of the document put \makeglossaries.
2174
2175 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2176 (org-add-link-type
2177  "newglossaryentry"
2178  nil ;; no follow action
2179  (lambda (path desc format)
2180    (cond
2181     ((eq format 'latex)
2182      (format "\\newglossaryentry{%s}{%s}" path desc)))))
2183
2184
2185 ;; link to entry
2186 (org-add-link-type
2187  "gls"
2188   nil ;; no follow action
2189  (lambda (path desc format)
2190    (cond
2191     ((eq format 'latex)
2192      (format "\\gls{%s}" path)))))
2193
2194 ;; plural
2195 (org-add-link-type
2196  "glspl"
2197   nil ;; no follow action
2198  (lambda (path desc format)
2199    (cond
2200     ((eq format 'latex)
2201      (format "\\glspl{%s}" path)))))
2202
2203 ;; capitalized link
2204 (org-add-link-type
2205  "Gls"
2206   nil ;; no follow action
2207  (lambda (path desc format)
2208    (cond
2209     ((eq format 'latex)
2210      (format "\\Gls{%s}" path)))))
2211
2212 ;; capitalized link
2213 (org-add-link-type
2214  "Glspl"
2215   nil ;; no follow action
2216  (lambda (path desc format)
2217    (cond
2218     ((eq format 'latex)
2219      (format "\\Glspl{%s}" path)))))
2220 #+END_SRC
2221
2222 * Utilities
2223 ** create simple text citation from bibtex entry
2224
2225 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2226 (defun org-ref-bib-citation ()
2227   "From a bibtex entry, create and return a simple citation string.
2228 This assumes you are in an article."
2229
2230   (bibtex-beginning-of-entry)
2231   (let* ((cb (current-buffer))
2232          (bibtex-expand-strings t)
2233          (entry (loop for (key . value) in (bibtex-parse-entry t)
2234                       collect (cons (downcase key) value)))
2235          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2236          (year  (reftex-get-bib-field "year" entry))
2237          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2238          (key (reftex-get-bib-field "=key=" entry))
2239          (journal (reftex-get-bib-field "journal" entry))
2240          (volume (reftex-get-bib-field "volume" entry))
2241          (pages (reftex-get-bib-field "pages" entry))
2242          (doi (reftex-get-bib-field "doi" entry))
2243          (url (reftex-get-bib-field "url" entry))
2244          )
2245     ;;authors, "title", Journal, vol(iss):pages (year).
2246     (format "%s, \"%s\", %s, %s:%s (%s)"
2247             author title journal  volume pages year)))
2248 #+END_SRC
2249
2250 #+RESULTS:
2251 : org-ref-bib-citation
2252
2253
2254 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2255 (defun org-ref-bib-html-citation ()
2256   "from a bibtex entry, create and return a simple citation with html links."
2257
2258   (bibtex-beginning-of-entry)
2259   (let* ((cb (current-buffer))
2260          (bibtex-expand-strings t)
2261          (entry (loop for (key . value) in (bibtex-parse-entry t)
2262                       collect (cons (downcase key) value)))
2263          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2264          (year  (reftex-get-bib-field "year" entry))
2265          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2266          (key (reftex-get-bib-field "=key=" entry))
2267          (journal (reftex-get-bib-field "journal" entry))
2268          (volume (reftex-get-bib-field "volume" entry))
2269          (pages (reftex-get-bib-field "pages" entry))
2270          (doi (reftex-get-bib-field "doi" entry))
2271          (url (reftex-get-bib-field "url" entry))
2272          )
2273     ;;authors, "title", Journal, vol(iss):pages (year).
2274     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2275                     author title journal  volume pages year)
2276             (when url (format " <a href=\"%s\">link</a>" url))
2277             (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2278     ))
2279 #+END_SRC
2280
2281 ** open pdf from bibtex
2282 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2283 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2284 (defun org-ref-open-bibtex-pdf ()
2285   "open pdf for a bibtex entry, if it exists. assumes point is in
2286 the entry of interest in the bibfile. but does not check that."
2287   (interactive)
2288   (save-excursion
2289     (bibtex-beginning-of-entry)
2290     (let* ((bibtex-expand-strings t)
2291            (entry (bibtex-parse-entry t))
2292            (key (reftex-get-bib-field "=key=" entry))
2293            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2294       (message "%s" pdf)
2295       (if (file-exists-p pdf)
2296           (org-open-link-from-string (format "[[file:%s]]" pdf))
2297         (ding)))))
2298 #+END_SRC
2299
2300 ** open notes from bibtex
2301 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2302
2303 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2304 (defun org-ref-open-bibtex-notes ()
2305   "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
2306
2307 I never did figure out how to use reftex to make this happen
2308 non-interactively. the reftex-format-citation function did not
2309 work perfectly; there were carriage returns in the strings, and
2310 it did not put the key where it needed to be. so, below I replace
2311 the carriage returns and extra spaces with a single space and
2312 construct the heading by hand."
2313   (interactive)
2314
2315   (bibtex-beginning-of-entry)
2316   (let* ((cb (current-buffer))
2317          (bibtex-expand-strings t)
2318          (entry (loop for (key . value) in (bibtex-parse-entry t)
2319                       collect (cons (downcase key) value)))
2320          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2321          (year  (reftex-get-bib-field "year" entry))
2322          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2323          (key (reftex-get-bib-field "=key=" entry))
2324          (journal (reftex-get-bib-field "journal" entry))
2325          (volume (reftex-get-bib-field "volume" entry))
2326          (pages (reftex-get-bib-field "pages" entry))
2327          (doi (reftex-get-bib-field "doi" entry))
2328          (url (reftex-get-bib-field "url" entry))
2329          )
2330
2331     ;; save key to clipboard to make saving pdf later easier by pasting.
2332     (with-temp-buffer
2333       (insert key)
2334       (kill-ring-save (point-min) (point-max)))
2335
2336     ;; now look for entry in the notes file
2337     (if  org-ref-bibliography-notes
2338         (find-file-other-window org-ref-bibliography-notes)
2339       (error "org-ref-bib-bibliography-notes is not set to anything"))
2340
2341     (goto-char (point-min))
2342     ;; put new entry in notes if we don't find it.
2343     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2344         (funcall org-ref-open-notes-function)
2345       ;; no entry found, so add one
2346       (insert (format "\n** TODO %s - %s" year title))
2347       (insert (format"
2348  :PROPERTIES:
2349   :Custom_ID: %s
2350   :AUTHOR: %s
2351   :JOURNAL: %s
2352   :YEAR: %s
2353   :VOLUME: %s
2354   :PAGES: %s
2355   :DOI: %s
2356   :URL: %s
2357  :END:
2358 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2359 key author journal year volume pages doi url key org-ref-pdf-directory key))
2360 (save-buffer))))
2361 #+END_SRC
2362
2363 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2364 (defun org-ref-open-notes-from-reftex ()
2365   "Call reftex, and open notes for selected entry."
2366   (interactive)
2367   (let ((bibtex-key )))
2368
2369     ;; now look for entry in the notes file
2370     (if  org-ref-bibliography-notes
2371         (find-file-other-window org-ref-bibliography-notes)
2372       (error "org-ref-bib-bibliography-notes is not set to anything"))
2373
2374     (goto-char (point-min))
2375
2376     (re-search-forward (format
2377                         ":Custom_ID: %s$"
2378                         (first (reftex-citation t)) nil 'end))
2379     (funcall org-ref-open-notes-function))
2380 #+END_SRC
2381
2382 ** open url in browser from bibtex
2383
2384 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2385
2386 + 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.
2387
2388 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2389 (defun org-ref-open-in-browser ()
2390   "Open the bibtex entry at point in a browser using the url field or doi field"
2391 (interactive)
2392 (save-excursion
2393   (bibtex-beginning-of-entry)
2394   (catch 'done
2395     (let ((url (bibtex-autokey-get-field "url")))
2396       (when  url
2397         (browse-url url)
2398         (throw 'done nil)))
2399
2400     (let ((doi (bibtex-autokey-get-field "doi")))
2401       (when doi
2402         (if (string-match "^http" doi)
2403             (browse-url doi)
2404           (browse-url (format "http://dx.doi.org/%s" doi)))
2405         (throw 'done nil)))
2406     (message "No url or doi found"))))
2407 #+END_SRC
2408
2409 ** citeulike
2410    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.
2411
2412 *** function to upload bibtex to citeulike
2413
2414 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2415 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2416   "with point in  a bibtex entry get bibtex string and submit to citeulike.
2417
2418 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2419   (interactive)
2420   (message "uploading to citeulike")
2421   (save-restriction
2422     (bibtex-narrow-to-entry)
2423     (let ((startpos (point-min))
2424           (endpos (point-max))
2425           (bibtex-string (buffer-string))
2426           (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2427       (with-temp-buffer (insert bibtex-string)
2428                         (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2429 #+END_SRC
2430
2431 *** The upload script
2432 Here is the python script for uploading.
2433
2434 *************** TODO document how to get the cookies
2435 *************** END
2436
2437
2438 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
2439 #!python
2440 import pickle, requests, sys
2441
2442 # reload cookies
2443 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
2444     cookies = pickle.load(f)
2445
2446 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
2447
2448 bibtex = sys.stdin.read()
2449
2450 data = {'pasted':bibtex,
2451         'to_read':2,
2452         'tag_parsing':'simple',
2453         'strip_brackets':'no',
2454         'update_id':'bib-key',
2455         'btn_bibtex':'Import BibTeX file ...'}
2456
2457 headers = {'content-type': 'multipart/form-data',
2458            'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
2459
2460 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
2461 print r
2462 #+END_SRC
2463
2464 ** Build a pdf from a bibtex file
2465    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.
2466
2467 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2468 (defun org-ref-build-full-bibliography ()
2469   "build pdf of all bibtex entries, and open it."
2470   (interactive)
2471   (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2472         (bib-base (file-name-sans-extension bibfile))
2473         (texfile (concat bib-base ".tex"))
2474         (pdffile (concat bib-base ".pdf")))
2475     (find-file texfile)
2476     (erase-buffer)
2477     (insert (format "\\documentclass[12pt]{article}
2478 \\usepackage[version=3]{mhchem}
2479 \\usepackage{url}
2480 \\usepackage[numbers]{natbib}
2481 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2482 \\usepackage{doi}
2483 \\begin{document}
2484 \\nocite{*}
2485 \\bibliographystyle{unsrtnat}
2486 \\bibliography{%s}
2487 \\end{document}" bib-base))
2488     (save-buffer)
2489     (shell-command (concat "pdflatex " bib-base))
2490     (shell-command (concat "bibtex " bib-base))
2491     (shell-command (concat "pdflatex " bib-base))
2492     (shell-command (concat "pdflatex " bib-base))
2493     (kill-buffer texfile)
2494     (org-open-file pdffile)
2495     ))
2496 #+END_SRC
2497
2498 ** Extract bibtex entries cited in an org-file
2499 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.
2500
2501 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
2502 (defun org-ref-extract-bibtex-entries ()
2503   "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2504
2505 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
2506   (interactive)
2507   (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2508          (tempname (make-temp-file "extract-bib"))
2509          (contents (buffer-string))
2510          (cb (current-buffer))
2511          basename texfile bibfile results)
2512
2513     ;; open tempfile and insert org-buffer contents
2514     (find-file tempname)
2515     (insert contents)
2516     (setq basename (file-name-sans-extension
2517                     (file-name-nondirectory buffer-file-name))
2518           texfile (concat tempname ".tex")
2519           bibfile (concat tempname ".bib"))
2520
2521     ;; see if we have a bibliography, and insert the default one if not.
2522     (save-excursion
2523       (goto-char (point-min))
2524       (unless (re-search-forward "^bibliography:" (point-max) 'end)
2525         (insert (format "\nbibliography:%s"
2526                         (mapconcat 'identity reftex-default-bibliography ",")))))
2527     (save-buffer)
2528
2529     ;; get a latex file and extract the references
2530     (org-latex-export-to-latex)
2531     (find-file texfile)
2532     (reftex-parse-all)
2533     (reftex-create-bibtex-file bibfile)
2534     (save-buffer)
2535     ;; save results of the references
2536     (setq results (buffer-string))
2537
2538     ;; kill buffers. these are named by basename, not full path
2539     (kill-buffer (concat basename ".bib"))
2540     (kill-buffer (concat basename ".tex"))
2541     (kill-buffer basename)
2542
2543     (delete-file bibfile)
2544     (delete-file texfile)
2545     (delete-file tempname)
2546
2547     ;; Now back to the original org buffer and insert the results
2548     (switch-to-buffer cb)
2549     (when (not (string= "" results))
2550       (save-excursion
2551         (goto-char (point-max))
2552         (insert "\n\n")
2553         (org-insert-heading)
2554         (insert (format " Bibtex entries
2555
2556 ,#+BEGIN_SRC text :tangle %s
2557 %s
2558 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2559 #+END_SRC
2560
2561 ** Find bad cite links
2562    :PROPERTIES:
2563    :ID:       8515E800-EDA0-4B2A-85FD-55B6FF849203
2564    :END:
2565 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.
2566
2567 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
2568 (require 'cl)
2569
2570 (defun index (substring list)
2571   "return the index of string in a list of strings"
2572   (let ((i 0)
2573         (found nil))
2574     (dolist (arg list i)
2575       (if (string-match (concat "^" substring "$") arg)
2576           (progn
2577             (setq found t)
2578             (return i)))
2579       (setq i (+ i 1)))
2580     ;; return counter if found, otherwise return nil
2581     (if found i nil)))
2582
2583
2584 (defun org-ref-find-bad-citations ()
2585   "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2586
2587 Makes a new buffer with clickable links."
2588   (interactive)
2589   ;; generate the list of bibtex-keys and cited keys
2590   (let* ((bibtex-files (org-ref-find-bibliography))
2591          (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2592          (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2593          (bad-citations '()))
2594
2595     (org-element-map (org-element-parse-buffer) 'link
2596       (lambda (link)
2597         (let ((plist (nth 1 link)))
2598           (when (equal (plist-get plist ':type) "cite")
2599             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2600               (when (not (index key bibtex-keys))
2601                 (setq bad-citations (append bad-citations
2602                                             `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2603                                                        key (buffer-name)(plist-get plist ':begin)))))
2604                 ))))))
2605
2606     (if bad-citations
2607       (progn
2608         (switch-to-buffer-other-window "*Missing citations*")
2609         (org-mode)
2610         (erase-buffer)
2611         (insert "* List of bad cite links\n")
2612         (insert (mapconcat 'identity bad-citations ""))
2613                                         ;(setq buffer-read-only t)
2614         (use-local-map (copy-keymap org-mode-map))
2615         (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2616
2617       (when (get-buffer "*Missing citations*")
2618           (kill-buffer "*Missing citations*"))
2619       (message "No bad cite links found"))))
2620 #+END_SRC
2621
2622 ** helm interface to org-ref
2623 In [[id:8515E800-EDA0-4B2A-85FD-55B6FF849203][Find bad cite links]] we wrote a function that finds bad links and creates a buffer of links to them.
2624
2625 Here we develop a similar idea, but instead of an org-buffer with links, we create helm sources for bad cite links, bad ref links, and multiple labels.
2626
2627 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2628 (defun org-ref-bad-cite-candidates ()
2629   "Returns a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2630   (let* ((cp (point))                   ; save to return to later
2631          (bibtex-files (org-ref-find-bibliography))
2632          (bibtex-file-path (mapconcat
2633                             (lambda (x)
2634                               (file-name-directory (file-truename x)))
2635                             bibtex-files ":"))
2636          (bibtex-keys (mapcar (lambda (x) (car x))
2637                               (bibtex-global-key-alist)))
2638          (bad-citations '()))
2639
2640     (org-element-map (org-element-parse-buffer) 'link
2641       (lambda (link)
2642         (let ((plist (nth 1 link)))
2643           (when (-contains? org-ref-cite-types (plist-get plist ':type))
2644             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2645               (when (not (index key bibtex-keys))
2646                 (goto-char (plist-get plist ':begin))
2647                 (re-search-forward key)
2648                 (push (cons key (point-marker)) bad-citations)))
2649               ))))
2650     (goto-char cp)
2651     bad-citations))
2652
2653 ;; It seems I forgot I already defined this earlier!
2654 ;; (defun org-ref-get-labels ()
2655 ;;   "Returns a list of known labels in the org document. These include label links, latex labels, label tags, and table names. The list contains all labels, not just unique ones.
2656 ;; "
2657 ;;   (let ((cp (point))
2658 ;;      (labels '()))
2659 ;;     (goto-char (point-min))
2660 ;;     (while (re-search-forward "[^#+]label:\\(.*\\)\\s-" nil t)
2661 ;;       (push  (match-string 1) labels))
2662
2663 ;;     (goto-char (point-min))
2664 ;;     (while (re-search-forward "\\label{\\(.*\\)}\\s-?" nil t)
2665 ;;       (push (match-string 1) labels))
2666
2667 ;;     (goto-char (point-min))
2668 ;;     (while (re-search-forward "^#\\+label:\\s-*\\(.*\\)" nil t)
2669 ;;       (push (match-string 1) labels))
2670
2671 ;;     (goto-char (point-min))
2672 ;;     (while (re-search-forward "^#\\+tblname:\\s-*\\(.*\\)" nil t)
2673 ;;       (push (match-string 1) labels))
2674 ;;     ;; check for CUSTOM_ID
2675 ;;     (org-map-entries
2676 ;;      (lambda ()
2677 ;;        (when (org-entry-get (point) "CUSTOM_ID")
2678 ;;       (push (org-entry-get (point) "CUSTOM_ID") labels))))
2679 ;;     ;; return to original place
2680 ;;     (goto-char cp)
2681 ;;     labels))
2682
2683
2684 (defun org-ref-bad-ref-candidates ()
2685   "Returns a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2686   ;; first get a list of legitimate labels
2687   (let ((cp (point))
2688         (labels (org-ref-get-labels))
2689         (bad-refs '()))
2690     ;; now loop over ref links
2691     (goto-char (point-min))
2692     (org-element-map (org-element-parse-buffer) 'link
2693       (lambda (link)
2694         (let ((plist (nth 1 link)))
2695           (when (or  (equal (plist-get plist ':type) "ref")
2696                      (equal (plist-get plist ':type) "eqref")
2697                      (equal (plist-get plist ':type) "pageref")
2698                      (equal (plist-get plist ':type) "nameref"))
2699             (unless (-contains? labels (plist-get plist :path))
2700               (goto-char (plist-get plist :begin))
2701               (add-to-list
2702                'bad-refs
2703                (cons (plist-get plist :path)
2704                      (point-marker))))))))
2705     (goto-char cp)
2706     bad-refs))
2707
2708
2709 (defun org-ref-bad-label-candidates ()
2710   "Return a list of labels where label is multiply defined."
2711   (let ((labels (org-ref-get-labels))
2712         (multiple-labels '()))
2713     (when (not (= (length labels)
2714                   (length (-uniq labels))))
2715       (dolist (label labels)
2716         (when (> (-count (lambda (a)
2717                            (equal a label))
2718                          labels) 1)
2719           ;; this is a multiply defined label.
2720           (let ((cp (point)))
2721             (goto-char (point-min))
2722             (while (re-search-forward
2723                     (format  "[^#+]label:%s\\s-" label) nil t)
2724               (push (cons label (point-marker)) multiple-labels))
2725
2726             (goto-char (point-min))
2727             (while (re-search-forward
2728                     (format  "\\label{%s}\\s-?" label) nil t)
2729               (push (cons label (point-marker)) multiple-labels))
2730
2731             (goto-char (point-min))
2732             (while (re-search-forward
2733                     (format  "^#\\+label:\\s-*%s" label) nil t)
2734               (push (cons label (point-marker)) multiple-labels))
2735
2736             (goto-char (point-min))
2737             (while (re-search-forward
2738                     (format   "^#\\+tblname:\\s-*%s" label) nil t)
2739               (push (cons label (point-marker)) multiple-labels))
2740             (goto-char cp)))))
2741       multiple-labels))
2742 #+END_SRC
2743
2744 #+RESULTS:
2745 : org-ref-bad-label-candidates
2746
2747 Now, we have a functions for candidates, we can make helm sources for each one, and then run a helm command to view them.
2748
2749 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2750 (defun org-ref ()
2751   "Opens a helm interface to actions for org-ref.
2752 Shows bad citations, ref links and labels"
2753   (interactive)
2754   (let ((cb (current-buffer))
2755         (bad-citations (org-ref-bad-cite-candidates))
2756         (bad-refs (org-ref-bad-ref-candidates))
2757         (bad-labels (org-ref-bad-label-candidates)))
2758
2759     (helm :sources `(((name . "Bad citations")
2760                        (candidates . ,bad-citations)
2761                        (action . (lambda (marker)
2762                                    (switch-to-buffer (marker-buffer marker))
2763                                    (goto-char marker))))
2764                      ;;
2765                      ((name . "Bad Labels")
2766                       (candidates . ,bad-labels)
2767                       (action . (lambda (marker)
2768                                    (switch-to-buffer (marker-buffer marker))
2769                                    (goto-char marker))))
2770                      ;;
2771                      ((name . "Bad ref links")
2772                       (candidates . ,bad-refs)
2773                       (action . (lambda (marker)
2774                                           (switch-to-buffer (marker-buffer marker))
2775                                           (goto-char marker))))
2776                      ;;
2777                      ((name . "Utilities")
2778                       (candidates . (("Check buffer again" . org-ref)
2779                                      ("Insert citation" . helm-bibtex)
2780                                      ("Insert label link" . org-ref-helm-insert-label-link)
2781                                      ("Insert ref link" . org-ref-helm-insert-ref-link)
2782                                      ("List of figures" . org-ref-list-of-figures)
2783                                      ("List of tables" . org-ref-list-of-tables)
2784                                      ("Table of contents" . nil)
2785                                      ))
2786                       (action . (lambda (x)
2787                                   (switch-to-buffer ,cb)
2788                                   (funcall x))))
2789                      ;;
2790                      ((name . "Export functions")
2791                       (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2792                                      ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2793                                      ("Export to pdf and open" . (lambda ()
2794                                                                    (org-open-file (org-latex-export-to-pdf))))
2795                                      ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2796                                      ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2797
2798                                      ))
2799                       (action . (lambda (x)
2800                                   (switch-to-buffer ,cb)
2801                                   (funcall x))))
2802                       ))))
2803 #+END_SRC
2804
2805
2806 ** Finding non-ascii characters
2807 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2808
2809 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2810 (defun org-ref-find-non-ascii-characters ()
2811   "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2812   (interactive)
2813   (occur "[^[:ascii:]]"))
2814 #+END_SRC
2815
2816 ** Resort a bibtex entry
2817 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.
2818
2819 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2820 (defun org-ref-sort-bibtex-entry ()
2821   "sort fields of entry in standard order and downcase them"
2822   (interactive)
2823   (bibtex-beginning-of-entry)
2824   (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2825          (entry (bibtex-parse-entry))
2826          (entry-fields)
2827          (other-fields)
2828          (type (cdr (assoc "=type=" entry)))
2829          (key (cdr (assoc "=key=" entry))))
2830
2831     ;; these are the fields we want to order that are in this entry
2832     (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2833     ;; we do not want to reenter these fields
2834     (setq entry-fields (remove "=key=" entry-fields))
2835     (setq entry-fields (remove "=type=" entry-fields))
2836
2837     ;;these are the other fields in the entry
2838     (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2839
2840     (cond
2841      ;; right now we only resort articles
2842      ((string= (downcase type) "article")
2843       (bibtex-kill-entry)
2844       (insert
2845        (concat "@article{" key ",\n"
2846                (mapconcat
2847                 (lambda (field)
2848                   (when (member field entry-fields)
2849                     (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2850                (mapconcat
2851                 (lambda (field)
2852                   (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2853                "\n}\n\n"))
2854       (bibtex-find-entry key)
2855       (bibtex-fill-entry)
2856       (bibtex-clean-entry)
2857        ))))
2858 #+END_SRC
2859
2860 ** Clean a bibtex entry
2861    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.
2862 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.
2863 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2864 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2865   "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"
2866   (interactive "P")
2867   (bibtex-beginning-of-entry)
2868 (end-of-line)
2869   ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2870   (unless (string-match ",$" (thing-at-point 'line))
2871     (end-of-line)
2872     (insert ","))
2873
2874   ;; check for empty pages, and put eid or article id in its place
2875   (let ((entry (bibtex-parse-entry))
2876         (pages (bibtex-autokey-get-field "pages"))
2877         (year (bibtex-autokey-get-field "year"))
2878         (doi  (bibtex-autokey-get-field "doi"))
2879         ;; The Journal of Chemical Physics uses eid
2880         (eid (bibtex-autokey-get-field "eid")))
2881
2882     ;; replace http://dx.doi.org/ in doi. some journals put that in,
2883     ;; but we only want the doi.
2884     (when (string-match "^http://dx.doi.org/" doi)
2885       (bibtex-beginning-of-entry)
2886       (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2887       (bibtex-kill-field)
2888       (bibtex-make-field "doi")
2889       (backward-char)
2890       (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2891
2892     ;; asap articles often set year to 0, which messes up key
2893     ;; generation. fix that.
2894     (when (string= "0" year)
2895       (bibtex-beginning-of-entry)
2896       (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2897       (bibtex-kill-field)
2898       (bibtex-make-field "year")
2899       (backward-char)
2900       (insert (read-string "Enter year: ")))
2901
2902     ;; fix pages if they are empty if there is an eid to put there.
2903     (when (string= "-" pages)
2904       (when eid
2905         (bibtex-beginning-of-entry)
2906         ;; this seems like a clunky way to set the pages field.But I
2907         ;; cannot find a better way.
2908         (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2909         (bibtex-kill-field)
2910         (bibtex-make-field "pages")
2911         (backward-char)
2912         (insert eid)))
2913
2914     ;; replace naked & with \&
2915     (save-restriction
2916       (bibtex-narrow-to-entry)
2917       (bibtex-beginning-of-entry)
2918       (message "checking &")
2919       (replace-regexp " & " " \\\\& ")
2920       (widen))
2921
2922     ;; generate a key, and if it duplicates an existing key, edit it.
2923     (unless keep-key
2924       (let ((key (bibtex-generate-autokey)))
2925
2926         ;; first we delete the existing key
2927         (bibtex-beginning-of-entry)
2928         (re-search-forward bibtex-entry-maybe-empty-head)
2929         (if (match-beginning bibtex-key-in-head)
2930             (delete-region (match-beginning bibtex-key-in-head)
2931                            (match-end bibtex-key-in-head)))
2932         ;; check if the key is in the buffer
2933         (when (save-excursion
2934                 (bibtex-search-entry key))
2935           (save-excursion
2936             (bibtex-search-entry key)
2937             (bibtex-copy-entry-as-kill)
2938             (switch-to-buffer-other-window "*duplicate entry*")
2939             (bibtex-yank))
2940           (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2941
2942         (insert key)
2943         (kill-new key))) ;; save key for pasting
2944
2945     ;; run hooks. each of these operates on the entry with no arguments.
2946     ;; this did not work like  i thought, it gives a symbolp error.
2947     ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2948     (mapcar (lambda (x)
2949               (save-restriction
2950                 (save-excursion
2951                   (funcall x))))
2952             org-ref-clean-bibtex-entry-hook)
2953
2954     ;; sort fields within entry
2955     (org-ref-sort-bibtex-entry)
2956     ;; check for non-ascii characters
2957     (occur "[^[:ascii:]]")
2958     ))
2959 #+END_SRC
2960
2961 #+RESULTS:
2962 : org-ref-clean-bibtex-entry
2963
2964 ** Sort the entries in a citation link by year
2965 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2966
2967 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2968 (defun org-ref-get-citation-year (key)
2969   "get the year of an entry with key. Returns year as a string."
2970   (interactive)
2971   (let* ((results (org-ref-get-bibtex-key-and-file key))
2972          (bibfile (cdr results)))
2973     (with-temp-buffer
2974       (insert-file-contents bibfile)
2975       (bibtex-search-entry key nil 0)
2976       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2977         ))))
2978
2979 (defun org-ref-sort-citation-link ()
2980  "replace link at point with sorted link by year"
2981  (interactive)
2982  (let* ((object (org-element-context))
2983         (type (org-element-property :type object))
2984         (begin (org-element-property :begin object))
2985         (end (org-element-property :end object))
2986         (link-string (org-element-property :path object))
2987         keys years data)
2988   (setq keys (org-ref-split-and-strip-string link-string))
2989   (setq years (mapcar 'org-ref-get-citation-year keys))
2990   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2991   (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2992   ;; now get the keys separated by commas
2993   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2994   ;; and replace the link with the sorted keys
2995   (cl--set-buffer-substring begin end (concat type ":" keys))))
2996 #+END_SRC
2997
2998 ** Sort entries in citation links with shift-arrow keys
2999 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
3000 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3001 (defun org-ref-swap-keys (i j keys)
3002  "swap the keys in a list with index i and j"
3003  (let ((tempi (nth i keys)))
3004    (setf (nth i keys) (nth j keys))
3005    (setf (nth j keys) tempi))
3006   keys)
3007
3008 (defun org-ref-swap-citation-link (direction)
3009  "move citation at point in direction +1 is to the right, -1 to the left"
3010  (interactive)
3011  (let* ((object (org-element-context))
3012         (type (org-element-property :type object))
3013         (begin (org-element-property :begin object))
3014         (end (org-element-property :end object))
3015         (link-string (org-element-property :path object))
3016         key keys i)
3017    ;;   We only want this to work on citation links
3018    (when (-contains? org-ref-cite-types type)
3019         (setq key (org-ref-get-bibtex-key-under-cursor))
3020         (setq keys (org-ref-split-and-strip-string link-string))
3021         (setq i (index key keys))  ;; defined in org-ref
3022         (if (> direction 0) ;; shift right
3023             (org-ref-swap-keys i (+ i 1) keys)
3024           (org-ref-swap-keys i (- i 1) keys))
3025         (setq keys (mapconcat 'identity keys ","))
3026         ;; and replace the link with the sorted keys
3027         (cl--set-buffer-substring begin end (concat type ":" keys " "))
3028         ;; now go forward to key so we can move with the key
3029         (re-search-forward key)
3030         (goto-char (match-beginning 0)))))
3031
3032 ;; add hooks to make it work
3033 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
3034 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
3035 #+END_SRC
3036
3037 ** Lightweight messages about links
3038 To get a lighter weight message about the label, ref and cite links, we define a function that gives us the minibuffer message, without the menu. We run this in an idle timer.
3039
3040 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3041 (defun org-ref-get-label-context (label)
3042   "Return a string of context around a label."
3043   (save-excursion
3044     (catch 'result
3045       (goto-char (point-min))
3046       (when (re-search-forward
3047              (format "label:%s\\b" label) nil t)
3048         (throw 'result (buffer-substring
3049                         (progn
3050                           (previous-line)
3051                           (beginning-of-line)
3052                           (point))
3053                         (progn
3054                           (forward-line 4)
3055                           (point)))))
3056
3057       (goto-char (point-min))
3058       (when (re-search-forward
3059              (format "\\label{%s}" label) nil t)
3060         (throw 'result (buffer-substring
3061                         (progn
3062                           (previous-line)
3063                           (beginning-of-line)
3064                           (point))
3065                         (progn
3066                           (forward-line 4)
3067                           (point)))))
3068
3069       (goto-char (point-min))
3070       (when (re-search-forward
3071              (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
3072         (throw 'result (buffer-substring
3073                         (progn
3074                           (previous-line)
3075                           (beginning-of-line)
3076                           (point))
3077                         (progn
3078                           (forward-line 4)
3079                           (point)))))
3080
3081       (goto-char (point-min))
3082       (when (re-search-forward
3083              (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
3084         (throw 'result (buffer-substring
3085                         (progn
3086                           (previous-line)
3087                           (beginning-of-line)
3088                           (point))
3089                         (progn
3090                           (forward-line 4)
3091                           (point)))))
3092       (beep)
3093       (throw 'result "!!! NO CONTEXT FOUND !!!"))))
3094
3095
3096 (defun org-ref-link-message ()
3097   "Print a minibuffer message about the link that point is on."
3098   (interactive)
3099   (when (eq major-mode 'org-mode)
3100     (let* ((object (org-element-context))
3101            (type (org-element-property :type object)))
3102       (save-excursion
3103         (cond
3104          ;; cite links
3105          ((-contains? org-ref-cite-types type)
3106           (message (org-ref-get-citation-string-at-point)))
3107
3108          ;; message some context about the label we are referring to
3109          ((string= type "ref")
3110           (message (org-ref-get-label-context
3111                     (org-element-property :path object))))
3112
3113          ((string= type "eqref")
3114           (message (org-ref-get-label-context
3115                     (org-element-property :path object))))
3116
3117          ;; message the count
3118          ((string= type "label")
3119           (let ((count (org-ref-count-labels
3120                         (org-element-property :path object))))
3121             ;; get plurality on occurrence correct
3122             (when (> count 1) (beep))
3123             (message (concat
3124                       (number-to-string count)
3125                       " occurence"
3126                       (when (or (= count 0)
3127                                 (> count 1))
3128                         "s")))))
3129
3130          ((string= type "custom-id")
3131           (save-excursion
3132             (org-open-link-from-string
3133              (format "[[#%s]]" (org-element-property :path object)))
3134             (message "%s" (org-get-heading))))
3135
3136          ;; check if the bibliography files exist.
3137          ((string= type "bibliography")
3138           (let* ((bibfile)
3139                  ;; object is the link you clicked on
3140                  (object (org-element-context))
3141                  (link-string (org-element-property :path object))
3142                  (link-string-beginning)
3143                  (link-string-end))
3144             (save-excursion
3145               (goto-char (org-element-property :begin object))
3146               (search-forward link-string nil nil 1)
3147               (setq link-string-beginning (match-beginning 0))
3148               (setq link-string-end (match-end 0)))
3149
3150              ;; make sure we are in link and not before the :
3151             (when (> link-string-beginning (point))
3152               (goto-char link-string-beginning))
3153
3154             ;; now if we have comma separated bibliographies
3155             ;; we find the one clicked on. we want to
3156             ;; search forward to next comma from point
3157             (save-excursion
3158               (if (search-forward "," link-string-end 1 1)
3159                   (setq key-end (- (match-end 0) 1)) ; we found a match
3160                 (setq key-end (point)))) ; no comma found so take the point
3161
3162             ;; and backward to previous comma from point
3163             (save-excursion
3164               (if (search-backward "," link-string-beginning 1 1)
3165                   (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
3166                 (setq key-beginning (point)))) ; no match found
3167             ;; save the key we clicked on.
3168             (setq bibfile
3169                   (org-ref-strip-string
3170                    (buffer-substring key-beginning key-end)))
3171             (if (file-exists-p bibfile)
3172                 (message "%s exists." bibfile)
3173               (beep)
3174               (message "!!! %s NOT FOUND !!!" bibfile))))
3175          )))))
3176 #+END_SRC
3177
3178 * Aliases
3179 I like convenience. Here are some aliases for faster typing.
3180
3181 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3182 (defalias 'oro 'org-ref-open-citation-at-point)
3183 (defalias 'orc 'org-ref-citation-at-point)
3184 (defalias 'orp 'org-ref-open-pdf-at-point)
3185 (defalias 'oru 'org-ref-open-url-at-point)
3186 (defalias 'orn 'org-ref-open-notes-at-point)
3187 (defalias 'ornr 'org-ref-open-notes-from-reftex)
3188
3189 (defalias 'orib 'org-ref-insert-bibliography-link)
3190 (defalias 'oric 'org-ref-insert-cite-link)
3191 (defalias 'orir 'org-ref-insert-ref-link)
3192 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
3193
3194 (defalias 'orcb 'org-ref-clean-bibtex-entry)
3195 #+END_SRC
3196 * Helm interface
3197 [[https://github.com/tmalsburg/helm-bibtex][helm-bibtex]] is a very cool interface to bibtex files. Out of the box though, it is not super convenient for org-ref. Here, we modify it to make it fit our workflow and extend it where needed.
3198
3199 1. Make the default action to insert selected keys.
3200 2. Make open entry second action
3201 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3202 (setq helm-source-bibtex
3203       '((name                                      . "BibTeX entries")
3204         (init                                      . helm-bibtex-init)
3205         (candidates                                . helm-bibtex-candidates)
3206         (filtered-candidate-transformer            . helm-bibtex-candidates-formatter)
3207         (action . (("Insert citation"              . helm-bibtex-insert-citation)
3208                    ("Show entry"                   . helm-bibtex-show-entry)
3209                    ("Open PDF file (if present)"   . helm-bibtex-open-pdf)
3210                    ("Open URL or DOI in browser"   . helm-bibtex-open-url-or-doi)
3211                    ("Insert reference"             . helm-bibtex-insert-reference)
3212                    ("Insert BibTeX key"            . helm-bibtex-insert-key)
3213                    ("Insert BibTeX entry"          . helm-bibtex-insert-bibtex)
3214                    ("Attach PDF to email"          . helm-bibtex-add-PDF-attachment)
3215                    ("Edit notes"                   . helm-bibtex-edit-notes)
3216                    ))))
3217 #+END_SRC
3218
3219 Now, let us define a function that inserts the cite links:
3220 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3221 (defun helm-bibtex-format-org-ref (keys)
3222   "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3223 Technically, this function should return a string that is inserted by helm. This function does the insertion and gives helm an empty string to insert. This lets us handle appending to a link properly.
3224
3225 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3226
3227 C-u C-u will change the key at point to the selected keys.
3228 "
3229   (let* ((object (org-element-context))
3230          (last-char (save-excursion
3231                       (goto-char (org-element-property :end object))
3232                       (backward-char)
3233                       (if (looking-at " ")
3234                           " "
3235                         ""))))
3236     (cond
3237      ;; case where we are in a link
3238      ((and (equal (org-element-type object) 'link)
3239            (-contains?
3240             org-ref-cite-types
3241             (org-element-property :type object)))
3242       (cond
3243        ;; no prefix. append keys
3244        ((equal helm-current-prefix-arg nil)
3245         (goto-char (org-element-property :end object))
3246         (while (looking-back " ") (backward-char))
3247         (insert (concat "," (mapconcat 'identity keys ","))))
3248        ;; double prefix, replace key at point
3249        ((equal helm-current-prefix-arg '(16))
3250         (setf (buffer-substring
3251                (org-element-property :begin object)
3252                (org-element-property :end object))
3253               (concat
3254                (replace-regexp-in-string
3255                 (car (org-ref-get-bibtex-key-and-file)) ; key
3256                 (mapconcat 'identity keys ",")          ; new keys
3257                 (org-element-property :raw-link object)
3258                 )
3259                ;; replace space at end to avoid collapsing into next word.
3260                last-char)))
3261        (t
3262         (message "Not found"))))
3263
3264      ;; We are next to a link, and we want to append
3265      ;; next to a link means one character back is on a link.
3266      ((save-excursion
3267         (backward-char)
3268         (and (equal (org-element-type (org-element-context)) 'link)
3269              (-contains?
3270               org-ref-cite-types
3271               (org-element-property :type (org-element-context)))))
3272       (while (looking-back " ") (backward-char))
3273       (insert (concat "," (mapconcat 'identity keys ","))))
3274
3275      ;; insert fresh link
3276      (t
3277       ;;(message-box "fresh link")
3278       (insert
3279        (concat (if (equal helm-current-prefix-arg '(4))
3280                    (helm :sources `((name . "link types")
3281                                     (candidates . ,org-ref-cite-types)
3282                                     (action . (lambda (x) x))))
3283                org-ref-default-citation-link)
3284                ":"
3285                (s-join "," keys))))))
3286   ;; return empty string for helm
3287   "")
3288
3289 (setq helm-bibtex-format-citation-functions
3290       '((org-mode . helm-bibtex-format-org-ref)))
3291
3292 (defun org-ref-helm-insert-cite-link (arg)
3293   "org-ref function to use helm-bibtex to insert a citation link.
3294 With one prefix arg, insert a ref link.
3295 With two prefix args, insert a label link."
3296   (interactive "P")
3297   (cond
3298    ((equal arg nil)
3299      (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3300        (helm-bibtex)))
3301    ((equal arg '(4))
3302     (org-ref-helm-insert-ref-link))
3303    ((equal arg '(16))
3304     (org-ref-helm-insert-label-link))))
3305
3306 (require 'helm-bibtex)
3307
3308 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3309 (setq helm-bibtex-fallback-options
3310       (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3311
3312 (setq helm-bibtex-fallback-options
3313       (-insert-at
3314        1
3315        '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3316        helm-bibtex-fallback-options))
3317
3318 (setq helm-bibtex-fallback-options
3319       (-insert-at 1 '("Open Web of Science" . (lambda () (browse-url "http://apps.webofknowledge.com")))
3320                   helm-bibtex-fallback-options))
3321 #+END_SRC
3322
3323 ** A helm click menu
3324 This code provides a helm interface to things you can do when you click on a citation link. This is an alternative to the minibuffer menu.
3325 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3326 (defun org-ref-get-citation-string-at-point ()
3327   "Get a string of a formatted citation"
3328   (interactive)
3329   (let* ((results (org-ref-get-bibtex-key-and-file))
3330          (key (car results))
3331          (bibfile (cdr results)))
3332     (if bibfile
3333         (save-excursion
3334           (with-temp-buffer
3335             (insert-file-contents bibfile)
3336             (bibtex-search-entry key)
3337             (org-ref-bib-citation)))
3338       (beep)
3339       "!!! No entry found !!!" )))
3340
3341 (defun org-ref-cite-candidates ()
3342   "Generate the list of possible candidates for click actions on a cite link.
3343 Checks for pdf and doi, and add appropriate functions."
3344   (interactive)
3345   (let* ((results (org-ref-get-bibtex-key-and-file))
3346          (key (car results))
3347          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3348          (bibfile (cdr results))
3349          (url (save-excursion
3350                 (with-temp-buffer
3351                   (insert-file-contents bibfile)
3352                   (bibtex-search-entry key)
3353                   (bibtex-autokey-get-field "url"))))
3354          (doi (save-excursion
3355                 (with-temp-buffer
3356                   (insert-file-contents bibfile)
3357                   (bibtex-search-entry key)
3358                   ;; I like this better than bibtex-url which does not always find
3359                   ;; the urls
3360                   (bibtex-autokey-get-field "doi"))))
3361          (candidates `(("Quit" . org-ref-citation-at-point)
3362                        ("Open bibtex entry" . org-ref-open-citation-at-point))))
3363     ;; for some reason, when there is no doi or url, they are returned as "". I
3364     ;; prefer nil so we correct this here.
3365     (when (string= doi "") (setq doi nil))
3366     (when (string= url "") (setq url nil))
3367
3368     ;; Conditional pdf functions
3369     (if (file-exists-p pdf-file)
3370         (add-to-list
3371          'candidates
3372          '("Open pdf" . org-ref-open-pdf-at-point)
3373          t)
3374       (add-to-list
3375        'candidates
3376        '("Try to get pdf" . (lambda ()
3377                               (save-window-excursion
3378                                 (org-ref-open-citation-at-point)
3379                                 (bibtex-beginning-of-entry)
3380                                 (doi-utils-get-bibtex-entry-pdf))))
3381        t))
3382
3383
3384     (add-to-list
3385      'candidates
3386      '("Open notes" . org-ref-open-notes-at-point)
3387      t)
3388
3389     ;; conditional url and doi functions
3390     (when (or url doi)
3391       (add-to-list
3392        'candidates
3393        '("Open in browser" . org-ref-open-url-at-point)
3394        t))
3395
3396     (when doi
3397       (mapc (lambda (x)
3398               (add-to-list 'candidates x t))
3399             `(("WOS" . org-ref-wos-at-point)
3400               ("Related articles in WOS" . org-ref-wos-related-at-point)
3401               ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3402               ("Google Scholar" . org-ref-google-scholar-at-point)
3403               ("Pubmed" . org-ref-pubmed-at-point)
3404               ("Crossref" . org-ref-crossref-at-point)
3405               )))
3406
3407     (add-to-list
3408      'candidates
3409      '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3410      t)
3411
3412     (add-to-list
3413      'candidates
3414      '("Copy key to clipboard" . (lambda ()
3415                                   (kill-new
3416                                    (car (org-ref-get-bibtex-key-and-file)))))
3417      t)
3418
3419     (add-to-list
3420      'candidates
3421      '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3422      t)
3423
3424     (add-to-list
3425      'candidates
3426      '("Email bibtex entry and pdf" . (lambda ()
3427                   (save-excursion
3428                     (org-ref-open-citation-at-point)
3429                     (email-bibtex-entry))))
3430      t)
3431   ;; finally return a numbered list of the candidates
3432   (loop for i from 0
3433         for cell in candidates
3434         collect (cons (format "%2s. %s" i (car cell))
3435                       (cdr cell)))))
3436
3437
3438 (defvar org-ref-helm-user-candidates '()
3439   "List of user-defined candidates to act when clicking on a cite link.
3440 This is a list of cons cells '((\"description\" . action)). The action function should not take an argument, and should assume point is on the cite key of interest.
3441 ")
3442
3443 ;; example of adding your own function
3444 (add-to-list
3445  'org-ref-helm-user-candidates
3446  '("Example" . (lambda () (message-box "You did it!")))
3447  t)
3448
3449 (defun org-ref-cite-click-helm (key)
3450   "subtle points.
3451 1. get name and candidates before entering helm because we need the org-buffer.
3452 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer."
3453   (interactive)
3454   (let ((name (org-ref-get-citation-string-at-point))
3455         (candidates (org-ref-cite-candidates))
3456         (cb (current-buffer)))
3457
3458     (helm :sources `(((name . ,name)
3459                       (candidates . ,candidates)
3460                       (action . (lambda (f)
3461                                   (switch-to-buffer cb)
3462                                   (funcall f))))
3463                      ((name . "User functions")
3464                       (candidates . ,org-ref-helm-user-candidates)
3465                       (action . (lambda (f)
3466                                   (switch-to-buffer cb)
3467                                   (funcall f))))
3468                      ))))
3469 #+END_SRC
3470
3471 #+RESULTS:
3472 : org-ref-cite-click-helm
3473
3474 * End of code
3475 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3476 (provide 'org-ref)
3477 #+END_SRC
3478
3479 * Build                                                            :noexport:
3480 This code will tangle the elisp code out to org-ref.el and load it.
3481
3482 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
3483
3484 Alternatively you may use:
3485
3486 [[elisp:(org-babel-load-file "org-ref.org")]]