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