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