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