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