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