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