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