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