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