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