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