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