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