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