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