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