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