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