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