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