]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.org
fix issue in bibliography link message
[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                             (link-string-beginning)
603                             (link-string-end))
604
605                      (save-excursion
606                        (goto-char (org-element-property :begin object))
607                        (search-forward link-string nil nil 1)
608                        (setq link-string-beginning (match-beginning 0))
609                        (setq link-string-end (match-end 0)))
610
611                        ;; We set the reftex-default-bibliography
612                        ;; here. it should be a local variable only in
613                        ;; the current buffer. We need this for using
614                        ;; reftex to do citations.
615                        (set (make-local-variable 'reftex-default-bibliography)
616                             (split-string (org-element-property :path object) ","))
617
618                        ;; now if we have comma separated bibliographies
619                        ;; we find the one clicked on. we want to
620                        ;; search forward to next comma from point
621                        (save-excursion
622                          (if (search-forward "," link-string-end 1 1)
623                              (setq key-end (- (match-end 0) 1)) ; we found a match
624                            (setq key-end (point)))) ; no comma found so take the point
625                        ;; and backward to previous comma from point
626                        (save-excursion
627                          (if (search-backward "," link-string-beginning 1 1)
628                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
629                            (setq key-beginning (point)))) ; no match found
630                        ;; save the key we clicked on.
631                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
632                        (find-file bibfile))) ; open file on click
633
634                      ;; formatting code
635                    (lambda (keyword desc format)
636                      (cond
637                       ((eq format 'org) (org-ref-get-org-bibliography))
638                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
639                       ((eq format 'html) (org-ref-get-html-bibliography))
640                       ((eq format 'latex)
641                        ;; write out the latex bibliography command
642                        (format "\\bibliography{%s}" (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
643                                                                                                       (mapcar 'expand-file-name
644                                                                                                               (split-string keyword ","))
645                                                                                                       ",")))))))
646
647 #+END_SRC
648
649 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.
650
651 #+BEGIN_LaTeX
652   \input{project-description.bbl}
653 #+END_LaTeX
654
655 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.
656
657 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
658 (org-add-link-type "nobibliography"
659                    ;; this code is run on clicking. The bibliography
660                    ;; may contain multiple files. this code finds the
661                    ;; one you clicked on and opens it.
662                    (lambda (link-string)
663                        ;; get link-string boundaries
664                        ;; we have to go to the beginning of the line, and then search forward
665
666                      (let* ((bibfile)
667                             ;; object is the link you clicked on
668                             (object (org-element-context))
669
670                             (link-string-beginning)
671                             (link-string-end))
672
673                      (save-excursion
674                        (goto-char (org-element-property :begin object))
675                        (search-forward link-string nil nil 1)
676                        (setq link-string-beginning (match-beginning 0))
677                        (setq link-string-end (match-end 0)))
678
679                        ;; We set the reftex-default-bibliography
680                        ;; here. it should be a local variable only in
681                        ;; the current buffer. We need this for using
682                        ;; reftex to do citations.
683                        (set (make-local-variable 'reftex-default-bibliography)
684                             (split-string (org-element-property :path object) ","))
685
686                        ;; now if we have comma separated bibliographies
687                        ;; we find the one clicked on. we want to
688                        ;; search forward to next comma from point
689                        (save-excursion
690                          (if (search-forward "," link-string-end 1 1)
691                              (setq key-end (- (match-end 0) 1)) ; we found a match
692                            (setq key-end (point)))) ; no comma found so take the point
693                        ;; and backward to previous comma from point
694                        (save-excursion
695                          (if (search-backward "," link-string-beginning 1 1)
696                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
697                            (setq key-beginning (point)))) ; no match found
698                        ;; save the key we clicked on.
699                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
700                        (find-file bibfile))) ; open file on click
701
702                      ;; formatting code
703                    (lambda (keyword desc format)
704                      (cond
705                       ((eq format 'org) (org-ref-get-org-bibliography))
706                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
707                       ((eq format 'html) (org-ref-get-html-bibliography))
708                       ((eq format 'latex)
709                        ;; write out the latex bibliography command
710
711 ;                      (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
712 ;                              (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
713 ;                                                                                (mapcar 'expand-file-name
714 ;                                                                                        (split-string keyword ","))
715 ;                                                                                ",")))
716
717                        (format "\\nobibliography{%s}"
718                                (replace-regexp-in-string  "\\.bib" "" (mapconcat 'identity
719                                                                                  (mapcar 'expand-file-name
720                                                                                          (split-string keyword ","))
721                                                                                  ",")))
722
723                        ))))
724 #+END_SRC
725
726 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
727 (org-add-link-type "printbibliography"
728                    (lambda (arg) (message "Nothing implemented for clicking here."))
729                    (lambda (keyword desc format)
730                      (cond
731                       ((eq format 'org) (org-ref-get-org-bibliography))
732                       ((eq format 'html) (org-ref-get-html-bibliography))
733                       ((eq format 'latex)
734                        ;; write out the biblatex bibliography command
735                        "\\printbibliography"))
736 ))
737 #+END_SRC
738
739 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, ...
740
741 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
742 (org-add-link-type "bibliographystyle"
743                    (lambda (arg) (message "Nothing implemented for clicking here."))
744                    (lambda (keyword desc format)
745                      (cond
746                       ((eq format 'latex)
747                        ;; write out the latex bibliography command
748                        (format "\\bibliographystyle{%s}" keyword)))))
749 #+END_SRC
750
751 *** Completion for bibliography link
752 It would be nice
753
754 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
755 (defun org-bibliography-complete-link (&optional arg)
756  (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
757
758 (defun org-ref-insert-bibliography-link ()
759   "insert a bibliography with completion"
760   (interactive)
761   (insert (org-bibliography-complete-link)))
762 #+END_SRC
763
764 ** addbibresource
765 This is apparently used for biblatex.
766 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
767 (org-add-link-type "addbibresource"
768                    ;; this code is run on clicking. The addbibresource
769                    ;; may contain multiple files. this code finds the
770                    ;; one you clicked on and opens it.
771                    (lambda (link-string)
772                        ;; get link-string boundaries
773                        ;; we have to go to the beginning of the line, and then search forward
774
775                      (let* ((bibfile)
776                             ;; object is the link you clicked on
777                             (object (org-element-context))
778
779                             (link-string-beginning)
780                             (link-string-end))
781
782                      (save-excursion
783                        (goto-char (org-element-property :begin object))
784                        (search-forward link-string nil nil 1)
785                        (setq link-string-beginning (match-beginning 0))
786                        (setq link-string-end (match-end 0)))
787
788                        ;; We set the reftex-default-addbibresource
789                        ;; here. it should be a local variable only in
790                        ;; the current buffer. We need this for using
791                        ;; reftex to do citations.
792                        (set (make-local-variable 'reftex-default-addbibresource)
793                             (split-string (org-element-property :path object) ","))
794
795                        ;; now if we have comma separated bibliographies
796                        ;; we find the one clicked on. we want to
797                        ;; search forward to next comma from point
798                        (save-excursion
799                          (if (search-forward "," link-string-end 1 1)
800                              (setq key-end (- (match-end 0) 1)) ; we found a match
801                            (setq key-end (point)))) ; no comma found so take the point
802                        ;; and backward to previous comma from point
803                        (save-excursion
804                          (if (search-backward "," link-string-beginning 1 1)
805                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
806                            (setq key-beginning (point)))) ; no match found
807                        ;; save the key we clicked on.
808                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
809                        (find-file bibfile))) ; open file on click
810
811                      ;; formatting code
812                    (lambda (keyword desc format)
813                      (cond
814                       ((eq format 'html) (format "")); no output for html
815                       ((eq format 'latex)
816                          ;; write out the latex addbibresource command
817                        (format "\\addbibresource{%s}" keyword)))))
818 #+END_SRC
819
820 ** List of Figures
821
822 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.
823
824 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
825 (defun org-ref-list-of-figures (&optional arg)
826   "Generate buffer with list of figures in them"
827   (interactive)
828   (save-excursion (widen)
829   (let* ((c-b (buffer-name))
830          (counter 0)
831          (list-of-figures
832           (org-element-map (org-element-parse-buffer) 'link
833             (lambda (link)
834               "create a link for to the figure"
835               (when
836                   (and (string= (org-element-property :type link) "file")
837                        (string-match-p
838                         "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
839                         (org-element-property :path link)))
840                 (incf counter)
841
842                 (let* ((start (org-element-property :begin link))
843                        (parent (car (cdr (org-element-property :parent link))))
844                        (caption (caaar (plist-get parent :caption)))
845                        (name (plist-get parent :name)))
846                   (if caption
847                       (format
848                        "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
849                        c-b start counter (or name "") caption)
850                     (format
851                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
852                      c-b start counter (or name "")))))))))
853     (switch-to-buffer "*List of Figures*")
854     (setq buffer-read-only nil)
855     (org-mode)
856     (erase-buffer)
857     (insert (mapconcat 'identity list-of-figures ""))
858     (setq buffer-read-only t)
859     (use-local-map (copy-keymap org-mode-map))
860     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
861
862 (org-add-link-type
863  "list-of-figures"
864  'org-ref-list-of-figures ; on click
865  (lambda (keyword desc format)
866    (cond
867     ((eq format 'latex)
868      (format "\\listoffigures")))))
869 #+END_SRC
870
871 ** List of Tables
872
873 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
874 (defun org-ref-list-of-tables (&optional arg)
875   "Generate a buffer with a list of tables"
876   (interactive)
877   (save-excursion
878   (widen)
879   (let* ((c-b (buffer-name))
880          (counter 0)
881          (list-of-tables
882           (org-element-map (org-element-parse-buffer 'element) 'table
883             (lambda (table)
884               "create a link for to the table"
885               (incf counter)
886               (let ((start (org-element-property :begin table))
887                     (name  (org-element-property :name table))
888                     (caption (caaar (org-element-property :caption table))))
889                 (if caption
890                     (format
891                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
892                      c-b start counter (or name "") caption)
893                   (format
894                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
895                    c-b start counter (or name ""))))))))
896     (switch-to-buffer "*List of Tables*")
897     (setq buffer-read-only nil)
898     (org-mode)
899     (erase-buffer)
900     (insert (mapconcat 'identity list-of-tables ""))
901     (setq buffer-read-only t)
902     (use-local-map (copy-keymap org-mode-map))
903     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
904
905 (org-add-link-type
906  "list-of-tables"
907  'org-ref-list-of-tables
908  (lambda (keyword desc format)
909    (cond
910     ((eq format 'latex)
911      (format "\\listoftables")))))
912 #+END_SRC
913 ** label
914
915 The label link provides a way to create labels in org-mode. We make it clickable because we want to make sure labels are unique. This code will tell you how many instances of a label are found.  We search for label links, LaTeX labels, and org-mode format for labels, tblnames too.
916
917 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
918 (defun org-ref-count-labels (label)
919   "Counts number of matches for label in the document"
920   (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
921      ;; for tblname, it is not enough to get word boundary
922      ;; tab-little and tab-little-2 match then.
923      (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
924      (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
925      ;; this is the org-format #+label:
926      (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
927      (let ((custom-id-count 0))
928        (org-map-entries
929         (lambda ()
930           (when (string= label  (org-entry-get (point) "CUSTOM_ID"))
931             (setq custom-id-count (+ 1 custom-id-count)))))
932        custom-id-count)))
933
934 (org-add-link-type
935  "label"
936  (lambda (label)
937    "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
938    (message (format "%s occurences" (org-ref-count-labels label))))
939  (lambda (keyword desc format)
940    (cond
941     ((eq format 'html) (format "(<label>%s</label>)" path))
942     ((eq format 'latex)
943      (format "\\label{%s}" keyword)))))
944 #+END_SRC
945
946 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.
947
948 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
949 (defun org-label-store-link ()
950   "store a link to a label. The output will be a ref to that label"
951   ;; First we have to make sure we are on a label link.
952   (let* ((object (org-element-context)))
953     (when (and (equal (org-element-type object) 'link)
954                (equal (org-element-property :type object) "label"))
955       (org-store-link-props
956        :type "ref"
957        :link (concat "ref:" (org-element-property :path object))))
958
959     ;; Store link on table
960     (when (equal (org-element-type object) 'table)
961       (org-store-link-props
962        :type "ref"
963        :link (concat "ref:" (org-element-property :name object))))
964
965 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
966     ;; store link on heading with custom_id
967 ;    (when (and (equal (org-element-type object) 'headline)
968 ;              (org-entry-get (point) "CUSTOM_ID"))
969 ;      (org-store-link-props
970 ;       :type "ref"
971 ;       :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
972
973     ;; and to #+label: lines
974     (when (and (equal (org-element-type object) 'paragraph)
975                (org-element-property :name object))
976       (org-store-link-props
977        :type "ref"
978        :link (concat "ref:" (org-element-property :name object))))
979 ))
980
981 (add-hook 'org-store-link-functions 'org-label-store-link)
982 #+END_SRC
983 ** ref
984
985 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.
986
987 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
988
989 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
990 (org-add-link-type
991  "ref"
992  (lambda (label)
993    "on clicking goto the label. Navigate back with C-c &"
994    (org-mark-ring-push)
995    ;; next search from beginning of the buffer
996
997    ;; it is possible you would not find the label if narrowing is in effect
998    (widen)
999
1000    (unless
1001        (or
1002         ;; our label links
1003         (progn
1004           (goto-char (point-min))
1005           (re-search-forward (format "label:%s\\b" label) nil t))
1006
1007         ;; a latex label
1008         (progn
1009           (goto-char (point-min))
1010           (re-search-forward (format "\\label{%s}" label) nil t))
1011
1012         ;; #+label: name  org-definition
1013         (progn
1014           (goto-char (point-min))
1015           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1016
1017         ;; org tblname
1018         (progn
1019           (goto-char (point-min))
1020           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1021
1022 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1023 ;; you need [[#label]] links.
1024         ;; CUSTOM_ID
1025 ;       (progn
1026 ;         (goto-char (point-min))
1027 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1028         )
1029      ;; we did not find anything, so go back to where we came
1030      (org-mark-ring-goto)
1031      (error "%s not found" label))
1032    (org-show-entry)
1033    (message "go back with (org-mark-ring-goto) `C-c &`"))
1034  ;formatting
1035  (lambda (keyword desc format)
1036    (cond
1037     ((eq format 'html) (format "(<ref>%s</ref>)" path))
1038     ((eq format 'latex)
1039      (format "\\ref{%s}" keyword)))))
1040 #+END_SRC
1041
1042 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.
1043
1044 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1045 (defun org-ref-get-org-labels ()
1046  "find #+LABEL: labels"
1047   (save-excursion
1048     (goto-char (point-min))
1049     (let ((matches '()))
1050       (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1051         (add-to-list 'matches (match-string-no-properties 1) t))
1052 matches)))
1053 #+END_SRC
1054
1055 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1056 (defun org-ref-get-custom-ids ()
1057  "return a list of custom_id properties in the buffer"
1058  (let ((results '()) custom_id)
1059    (org-map-entries
1060     (lambda ()
1061       (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1062         (when (not (null custom_id))
1063           (setq results (append results (list custom_id)))))))
1064 results))
1065 #+END_SRC
1066
1067 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
1068 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1069 (defun org-ref-get-latex-labels ()
1070   (save-excursion
1071     (goto-char (point-min))
1072     (let ((matches '()))
1073       (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1074         (add-to-list 'matches (match-string-no-properties 1) t))
1075 matches)))
1076 #+END_SRC
1077
1078 Finally, we get the table names.
1079
1080 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1081 (defun org-ref-get-tblnames ()
1082   (org-element-map (org-element-parse-buffer 'element) 'table
1083     (lambda (table)
1084       (org-element-property :name table))))
1085 #+END_SRC
1086
1087 Now, we can put all the labels together which will give us a list of candidates.
1088
1089 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1090 (defun org-ref-get-labels ()
1091   "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
1092   (save-excursion
1093     (save-restriction
1094       (widen)
1095       (goto-char (point-min))
1096       (let ((matches '()))
1097         (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1098           (add-to-list 'matches (match-string-no-properties 1) t))
1099         (append matches (org-ref-get-org-labels) (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
1100 #+END_SRC
1101
1102 Let us make a helm function to insert a label link. This will help you enter unique labels.
1103 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1104 (defun org-ref-helm-insert-label-link ()
1105   "Insert a label link. helm just shows you what labels already exist.
1106 If you are on a label link, replace it."
1107   (interactive)
1108   (let* ((labels (org-ref-get-labels))
1109          (cb (current-buffer)))
1110     (helm :sources `(((name . "Existing labels")
1111                       (candidates . ,labels)
1112                       ;; default action is to open to the label
1113                       (action . (lambda (label)
1114                                   ;; unfortunately I do not have markers here
1115                                   (org-open-link-from-string (format "ref:%s" label))))
1116                       ;; if you select a label, replace current one
1117                       (action . (lambda (label)
1118                                   (switch-to-buffer ,cb)
1119                                   (cond
1120                                    ;;  no prefix or on a link
1121                                    ((equal helm-current-prefix-arg nil)
1122                                     (let* ((object (org-element-context))
1123                                            (last-char (save-excursion
1124                                                         (goto-char (org-element-property :end object))
1125                                                         (backward-char)
1126                                                         (if (looking-at " ")
1127                                                             " "
1128                                                           ""))))
1129                                       (when (-contains? '("label")
1130                                                         (org-element-property :type object))
1131                                           ;; we are on a link, so replace it.
1132                                         (setf
1133                                            (buffer-substring
1134                                             (org-element-property :begin object)
1135                                             (org-element-property :end object))
1136                                            (concat
1137                                             (replace-regexp-in-string
1138                                              (org-element-property :path object)
1139                                              label
1140                                              (org-element-property :raw-link object))
1141                                             last-char)))))
1142                                    ;; no prefix options defined
1143                                    ))))
1144                      ;; no matching selection creates a new label
1145                      ((name . "Create new label")
1146                       (dummy)
1147                       ;; default action creates a new label, or replaces old one
1148                       (action .  (lambda (label)
1149                                    (switch-to-buffer ,cb)
1150                                    (let* ((object (org-element-context))
1151                                           (last-char (save-excursion
1152                                                        (goto-char (org-element-property :end object))
1153                                                        (backward-char)
1154                                                        (if (looking-at " ")
1155                                                            " "
1156                                                          ""))))
1157                                      (if (-contains? '("label")
1158                                                      (org-element-property :type object))
1159                                          ;; we are on a link, so replace it.
1160                                          (setf
1161                                           (buffer-substring
1162                                            (org-element-property :begin object)
1163                                            (org-element-property :end object))
1164                                           (concat
1165                                            (replace-regexp-in-string
1166                                             (org-element-property :path object)
1167                                             helm-pattern
1168                                             (org-element-property :raw-link object))
1169                                            last-char))
1170                                        ;; new link
1171                                        (insert
1172                                         (concat
1173                                          "label:"
1174                                          (or label
1175                                              helm-pattern))))))))))))
1176 #+END_SRC
1177
1178 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.
1179
1180 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1181 (defun org-ref-complete-link (&optional arg)
1182   "Completion function for ref links"
1183   (let ((label))
1184     (setq label (completing-read "label: " (org-ref-get-labels)))
1185     (format "ref:%s" label)))
1186 #+END_SRC
1187
1188 Alternatively, you may want to just call a function that inserts a link with completion:
1189
1190 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1191 (defun org-ref-insert-ref-link ()
1192  (interactive)
1193  (insert (org-ref-complete-link)))
1194 #+END_SRC
1195
1196 Another alternative ref insertion is to use helm.
1197
1198 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1199 (defun org-ref-helm-insert-ref-link ()
1200   "Helm menu to insert ref links to labels in the document.
1201 If you are on link, replace with newly selected label.
1202 Use C-u to insert a different kind of ref link.
1203 "
1204   (interactive)
1205   (let* ((labels (org-ref-get-labels))
1206          (contexts (mapcar 'org-ref-get-label-context labels))
1207          (cb (current-buffer)))
1208
1209     (helm :input (thing-at-point 'word)
1210           :sources `(((name . "Available labels to ref")
1211                       (candidates . ,(loop for label in labels
1212                                            for context in contexts
1213                                            ;; we do some kludgy adding spaces
1214                                            ;; and bars to make it "easier" to
1215                                            ;; see in helm.
1216                                            collect (cons (concat
1217                                                           label "\n"
1218                                                           (mapconcat
1219                                                            (lambda (x)
1220                                                              (concat "   |" x))
1221                                                            (split-string context "\n")
1222                                                            "\n"
1223                                                            ) "\n\n") label)))
1224                       ;; default action to replace or insert ref link.
1225                       (action . (lambda (label)
1226                                   (switch-to-buffer ,cb)
1227
1228                                   (cond
1229                                    ;;  no prefix or on a link
1230                                    ((equal helm-current-prefix-arg nil)
1231                                     (let* ((object (org-element-context))
1232                                            (last-char (save-excursion
1233                                                         (goto-char (org-element-property :end object))
1234                                                         (backward-char)
1235                                                         (if (looking-at " ")
1236                                                             " "
1237                                                           ""))))
1238                                       (if (-contains? '("ref" "eqref" "pageref" "nameref")
1239                                                       (org-element-property :type object))
1240                                           ;; we are on a link, so replace it.
1241                                           (setf
1242                                            (buffer-substring
1243                                             (org-element-property :begin object)
1244                                             (org-element-property :end object))
1245                                            (concat
1246                                             (replace-regexp-in-string
1247                                              (org-element-property :path object)
1248                                              label
1249                                              (org-element-property :raw-link object))
1250                                             last-char))
1251                                         ;; insert a new link
1252                                         (insert
1253                                          (concat
1254                                           "ref:" label))
1255                                         )))
1256                                    ;; one prefix, alternate ref link
1257                                    ((equal helm-current-prefix-arg '(4))
1258                                     (insert
1259                                      (concat
1260                                       (helm :sources '((name . "Ref link types")
1261                                                        (candidates . ("ref" "eqref" "pageref" "nameref"))
1262                                                        (action . (lambda (x) x))))
1263                                       ":" label)))
1264                                    ))))))))
1265 #+END_SRC
1266
1267 #+RESULTS:
1268 : org-ref-helm-insert-ref-link
1269
1270 ** pageref
1271
1272 This refers to the page of a label in LaTeX.
1273
1274 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1275 (org-add-link-type
1276  "pageref"
1277  (lambda (label)
1278    "on clicking goto the label. Navigate back with C-c &"
1279    (org-mark-ring-push)
1280    ;; next search from beginning of the buffer
1281    (widen)
1282    (unless
1283        (or
1284         ;; our label links
1285         (progn
1286           (goto-char (point-min))
1287           (re-search-forward (format "label:%s\\b" label) nil t))
1288
1289         ;; a latex label
1290         (progn
1291           (goto-char (point-min))
1292           (re-search-forward (format "\\label{%s}" label) nil t))
1293
1294         ;; #+label: name  org-definition
1295         (progn
1296           (goto-char (point-min))
1297           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1298
1299         ;; org tblname
1300         (progn
1301           (goto-char (point-min))
1302           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1303
1304 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1305 ;; you need [[#label]] links.
1306         ;; CUSTOM_ID
1307 ;       (progn
1308 ;         (goto-char (point-min))
1309 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1310         )
1311      ;; we did not find anything, so go back to where we came
1312      (org-mark-ring-goto)
1313      (error "%s not found" label))
1314    (message "go back with (org-mark-ring-goto) `C-c &`"))
1315  ;formatting
1316  (lambda (keyword desc format)
1317    (cond
1318     ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1319     ((eq format 'latex)
1320      (format "\\pageref{%s}" keyword)))))
1321 #+END_SRC
1322
1323 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1324 (defun org-pageref-complete-link (&optional arg)
1325   "Completion function for ref links"
1326   (let ((label))
1327     (setq label (completing-read "label: " (org-ref-get-labels)))
1328     (format "ref:%s" label)))
1329 #+END_SRC
1330
1331 Alternatively, you may want to just call a function that inserts a link with completion:
1332
1333 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1334 (defun org-pageref-insert-ref-link ()
1335  (interactive)
1336  (insert (org-pageref-complete-link)))
1337 #+END_SRC
1338
1339 ** nameref
1340
1341 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.
1342
1343 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1344 (org-add-link-type
1345  "nameref"
1346  (lambda (label)
1347    "on clicking goto the label. Navigate back with C-c &"
1348    (org-mark-ring-push)
1349    ;; next search from beginning of the buffer
1350    (widen)
1351    (unless
1352        (or
1353         ;; a latex label
1354         (progn
1355           (goto-char (point-min))
1356           (re-search-forward (format "\\label{%s}" label) nil t))
1357         )
1358      ;; we did not find anything, so go back to where we came
1359      (org-mark-ring-goto)
1360      (error "%s not found" label))
1361    (message "go back with (org-mark-ring-goto) `C-c &`"))
1362  ;formatting
1363  (lambda (keyword desc format)
1364    (cond
1365     ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1366     ((eq format 'latex)
1367      (format "\\nameref{%s}" keyword)))))
1368 #+END_SRC
1369
1370 ** eqref
1371 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1372
1373 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1374 (org-add-link-type
1375  "eqref"
1376  (lambda (label)
1377    "on clicking goto the label. Navigate back with C-c &"
1378    (org-mark-ring-push)
1379    ;; next search from beginning of the buffer
1380    (widen)
1381    (goto-char (point-min))
1382    (unless
1383        (or
1384         ;; search forward for the first match
1385         ;; our label links
1386         (re-search-forward (format "label:%s" label) nil t)
1387         ;; a latex label
1388         (re-search-forward (format "\\label{%s}" label) nil t)
1389         ;; #+label: name  org-definition
1390         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1391      (org-mark-ring-goto)
1392      (error "%s not found" label))
1393    (message "go back with (org-mark-ring-goto) `C-c &`"))
1394  ;formatting
1395  (lambda (keyword desc format)
1396    (cond
1397     ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1398     ((eq format 'latex)
1399      (format "\\eqref{%s}" keyword)))))
1400 #+END_SRC
1401
1402 ** cite
1403 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.
1404
1405 *** Implementing the click actions of cite
1406
1407 **** Getting the key we clicked on
1408 The first thing we need is to get the bibtex key we clicked on.
1409
1410 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1411 (defun org-ref-get-bibtex-key-under-cursor ()
1412   "returns key under the bibtex cursor. We search forward from
1413 point to get a comma, or the end of the link, and then backwards
1414 to get a comma, or the beginning of the link. that delimits the
1415 keyword we clicked on. We also strip the text properties."
1416   (interactive)
1417   (let* ((object (org-element-context))
1418          (link-string (org-element-property :path object)))
1419     ;; you may click on the part before the citations. here we make
1420     ;; sure to move to the beginning so you get the first citation.
1421     (let ((cp (point)))
1422       (goto-char (org-element-property :begin object))
1423       (search-forward link-string (org-element-property :end object))
1424       (goto-char (match-beginning 0))
1425       ;; check if we clicked before the path and move as needed.
1426       (unless (< cp (point))
1427         (goto-char cp)))
1428
1429     (if (not (org-element-property :contents-begin object))
1430         ;; this means no description in the link
1431         (progn
1432           ;; we need the link path start and end
1433           (save-excursion
1434             (goto-char (org-element-property :begin object))
1435             (search-forward link-string nil nil 1)
1436             (setq link-string-beginning (match-beginning 0))
1437             (setq link-string-end (match-end 0)))
1438
1439           ;; The key is the text between commas, or the link boundaries
1440           (save-excursion
1441             (if (search-forward "," link-string-end t 1)
1442                 (setq key-end (- (match-end 0) 1)) ; we found a match
1443               (setq key-end link-string-end))) ; no comma found so take the end
1444           ;; and backward to previous comma from point which defines the start character
1445           (save-excursion
1446             (if (search-backward "," link-string-beginning 1 1)
1447                 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1448               (setq key-beginning link-string-beginning))) ; no match found
1449           ;; save the key we clicked on.
1450           (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1451           (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1452           bibtex-key)
1453       ;; link with description. assume only one key
1454       link-string)))
1455 #+END_SRC
1456
1457 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.
1458
1459 **** Getting the bibliographies
1460 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1461 (defun org-ref-find-bibliography ()
1462   "find the bibliography in the buffer.
1463 This function sets and returns cite-bibliography-files, which is a list of files
1464 either from bibliography:f1.bib,f2.bib
1465 \bibliography{f1,f2}
1466 internal bibliographies
1467
1468 falling back to what the user has set in org-ref-default-bibliography
1469 "
1470   (interactive)
1471   (catch 'result
1472     (save-excursion
1473       (goto-char (point-min))
1474       ;;  look for a bibliography link
1475       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1476         (setq org-ref-bibliography-files
1477               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1478         (throw 'result org-ref-bibliography-files))
1479
1480
1481       ;; we did not find a bibliography link. now look for \bibliography
1482       (goto-char (point-min))
1483       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1484         ;; split, and add .bib to each file
1485         (setq org-ref-bibliography-files
1486               (mapcar (lambda (x) (concat x ".bib"))
1487                       (mapcar 'org-ref-strip-string
1488                               (split-string (match-string 1) ","))))
1489         (throw 'result org-ref-bibliography-files))
1490
1491       ;; no bibliography found. maybe we need a biblatex addbibresource
1492       (goto-char (point-min))
1493       ;;  look for a bibliography link
1494       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1495         (setq org-ref-bibliography-files
1496               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1497         (throw 'result org-ref-bibliography-files))
1498
1499       ;; we did not find anything. use defaults
1500       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1501
1502     ;; set reftex-default-bibliography so we can search
1503     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1504     org-ref-bibliography-files)
1505 #+END_SRC
1506
1507 **** Finding the bibliography file a key is in
1508 Now, we can see if an entry is in a file.
1509
1510 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1511 (defun org-ref-key-in-file-p (key filename)
1512   "determine if the key is in the file"
1513   (interactive "skey: \nsFile: ")
1514   (save-current-buffer
1515     (let ((bibtex-files (list filename)))
1516       (bibtex-search-entry key t))))
1517 #+END_SRC
1518
1519 Finally, we want to know which file the key is in.
1520
1521 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1522 (defun org-ref-get-bibtex-key-and-file (&optional key)
1523   "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1524  (interactive)
1525  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1526        (file))
1527    (unless key
1528      (setq key (org-ref-get-bibtex-key-under-cursor)))
1529    (setq file     (catch 'result
1530                     (loop for file in org-ref-bibliography-files do
1531                           (if (org-ref-key-in-file-p key (file-truename file))
1532                               (throw 'result file)))))
1533    (cons key file)))
1534 #+END_SRC
1535
1536 **** convenience functions to act on citation at point
1537      :PROPERTIES:
1538      :ID:       af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1539      :END:
1540 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.
1541
1542 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1543 (defun org-ref-open-pdf-at-point ()
1544   "open the pdf for bibtex key under point if it exists"
1545   (interactive)
1546   (let* ((results (org-ref-get-bibtex-key-and-file))
1547          (key (car results))
1548          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1549     (if (file-exists-p pdf-file)
1550         (org-open-file pdf-file)
1551 (message "no pdf found for %s" key))))
1552
1553
1554 (defun org-ref-open-url-at-point ()
1555   "open the url for bibtex key under point."
1556   (interactive)
1557   (let* ((results (org-ref-get-bibtex-key-and-file))
1558          (key (car results))
1559          (bibfile (cdr results)))
1560     (save-excursion
1561       (with-temp-buffer
1562         (insert-file-contents bibfile)
1563         (bibtex-search-entry key)
1564         ;; I like this better than bibtex-url which does not always find
1565         ;; the urls
1566         (catch 'done
1567           (let ((url (bibtex-autokey-get-field "url")))
1568             (when  url
1569               (browse-url url)
1570               (throw 'done nil)))
1571
1572           (let ((doi (bibtex-autokey-get-field "doi")))
1573             (when doi
1574               (if (string-match "^http" doi)
1575                   (browse-url doi)
1576                 (browse-url (format "http://dx.doi.org/%s" doi)))
1577               (throw 'done nil))))))))
1578
1579
1580 (defun org-ref-open-notes-at-point ()
1581   "open the notes for bibtex key under point."
1582   (interactive)
1583   (let* ((results (org-ref-get-bibtex-key-and-file))
1584          (key (car results))
1585          (bibfile (cdr results)))
1586     (save-excursion
1587       (with-temp-buffer
1588         (insert-file-contents bibfile)
1589         (bibtex-search-entry key)
1590         (org-ref-open-bibtex-notes)))))
1591
1592
1593 (defun org-ref-citation-at-point ()
1594   "give message of current citation at point"
1595   (interactive)
1596   (let* ((cb (current-buffer))
1597         (results (org-ref-get-bibtex-key-and-file))
1598         (key (car results))
1599         (bibfile (cdr results)))
1600     (message "%s" (progn
1601                     (with-temp-buffer
1602                       (insert-file-contents bibfile)
1603                       (bibtex-search-entry key)
1604                       (org-ref-bib-citation))))))
1605
1606
1607 (defun org-ref-open-citation-at-point ()
1608   "open bibtex file to key at point"
1609   (interactive)
1610   (let* ((cb (current-buffer))
1611         (results (org-ref-get-bibtex-key-and-file))
1612         (key (car results))
1613         (bibfile (cdr results)))
1614     (find-file bibfile)
1615     (bibtex-search-entry key)))
1616 #+END_SRC
1617
1618 **** the actual minibuffer menu
1619 Now, we create the menu. This is a rewrite of the cite action. This makes the function extendable by users.
1620
1621 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1622 (defvar org-ref-cite-menu-funcs '()
1623  "Functions to run on cite click menu. Each entry is a list of (key menu-name function).
1624 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.")
1625
1626
1627 (defvar org-ref-user-cite-menu-funcs
1628   '(("C" "rossref" org-ref-crossref-at-point)
1629     ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1630     ("s" "Copy summary" org-ref-copy-entry-as-summary))
1631   "user-defined functions to run on bibtex key at point.")
1632
1633
1634 (defun org-ref-copy-entry-as-summary ()
1635   "Copy the bibtex entry for the citation at point as a summary."
1636   (interactive)
1637     (save-window-excursion
1638       (org-ref-open-citation-at-point)
1639       (kill-new (org-ref-bib-citation))))
1640
1641
1642 (defun org-ref-copy-entry-at-point-to-file ()
1643   "Copy the bibtex entry for the citation at point to NEW-FILE.
1644 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."
1645   (interactive)
1646   (let ((new-file (ido-completing-read
1647                    "Copy to bibfile: "
1648                    (append org-ref-default-bibliography
1649                            (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1650         (key (org-ref-get-bibtex-key-under-cursor)))
1651     (save-window-excursion
1652       (org-ref-open-citation-at-point)
1653       (bibtex-copy-entry-as-kill))
1654
1655     (let ((bibtex-files (list (file-truename new-file))))
1656       (if (assoc key (bibtex-global-key-alist))
1657           (message "That key already exists in %s" new-file)
1658         ;; add to file
1659         (save-window-excursion
1660           (find-file new-file)
1661           (goto-char (point-max))
1662           ;; make sure we are at the beginning of a line.
1663           (unless (looking-at "^") (insert "\n\n"))
1664           (bibtex-yank)
1665           (save-buffer))))))
1666
1667
1668 (defun org-ref-get-doi-at-point ()
1669   "Get doi for key at point."
1670   (interactive)
1671   (let* ((results (org-ref-get-bibtex-key-and-file))
1672          (key (car results))
1673          (bibfile (cdr results))
1674          doi)
1675     (save-excursion
1676       (with-temp-buffer
1677         (insert-file-contents bibfile)
1678         (bibtex-search-entry key)
1679         (setq doi (bibtex-autokey-get-field "doi"))
1680         ;; in case doi is a url, remove the url part.
1681         (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1682
1683
1684 ;; functions that operate on key at point for click menu
1685 (defun org-ref-wos-at-point ()
1686   "open the doi in wos for bibtex key under point."
1687   (interactive)
1688   (doi-utils-wos (org-ref-get-doi-at-point)))
1689
1690
1691 (defun org-ref-wos-citing-at-point ()
1692   "open the doi in wos citing articles for bibtex key under point."
1693   (interactive)
1694   (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1695
1696
1697 (defun org-ref-wos-related-at-point ()
1698   "open the doi in wos related articles for bibtex key under point."
1699   (interactive)
1700   (doi-utils-wos-related (org-ref-get-doi-at-point)))
1701
1702
1703 (defun org-ref-google-scholar-at-point ()
1704   "open the doi in google scholar for bibtex key under point."
1705   (interactive)
1706   (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1707
1708
1709 (defun org-ref-pubmed-at-point ()
1710   "open the doi in pubmed for bibtex key under point."
1711   (interactive)
1712   (doi-utils-pubmed (org-ref-get-doi-at-point)))
1713
1714
1715 (defun org-ref-crossref-at-point ()
1716   "open the doi in crossref for bibtex key under point."
1717   (interactive)
1718   (doi-utils-crossref (org-ref-get-doi-at-point)))
1719
1720
1721 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1722   "action when a cite link is clicked on.
1723 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."
1724   (interactive)
1725   (let* ((results (org-ref-get-bibtex-key-and-file))
1726          (key (car results))
1727          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1728          (bibfile (cdr results))
1729          (url (save-excursion
1730                 (with-temp-buffer
1731                   (insert-file-contents bibfile)
1732                   (bibtex-search-entry key)
1733                   (bibtex-autokey-get-field "url"))))
1734          (doi (save-excursion
1735                 (with-temp-buffer
1736                   (insert-file-contents bibfile)
1737                   (bibtex-search-entry key)
1738                   ;; I like this better than bibtex-url which does not always find
1739                   ;; the urls
1740                   (bibtex-autokey-get-field "doi")))))
1741
1742     (when (string= "" doi) (setq doi nil))
1743     (when (string= "" url) (setq url nil))
1744     (setq org-ref-cite-menu-funcs '())
1745
1746     ;; open action
1747     (when
1748         bibfile
1749       (add-to-list
1750        'org-ref-cite-menu-funcs
1751        '("o" "pen" org-ref-open-citation-at-point)))
1752
1753     ;; pdf
1754     (when (file-exists-p pdf-file)
1755       (add-to-list
1756        'org-ref-cite-menu-funcs
1757        `("p" "df" ,org-ref-open-pdf-function) t))
1758
1759     ;; notes
1760     (add-to-list
1761      'org-ref-cite-menu-funcs
1762      '("n" "otes" org-ref-open-notes-at-point) t)
1763
1764     ;; url
1765     (when (or url doi)
1766       (add-to-list
1767        'org-ref-cite-menu-funcs
1768        '("u" "rl" org-ref-open-url-at-point) t))
1769
1770     ;; doi funcs
1771     (when doi
1772       (add-to-list
1773        'org-ref-cite-menu-funcs
1774        '("w" "os" org-ref-wos-at-point) t)
1775
1776       (add-to-list
1777        'org-ref-cite-menu-funcs
1778        '("c" "iting" org-ref-wos-citing-at-point) t)
1779
1780       (add-to-list
1781        'org-ref-cite-menu-funcs
1782        '("r" "elated" org-ref-wos-related-at-point) t)
1783
1784       (add-to-list
1785        'org-ref-cite-menu-funcs
1786        '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1787
1788       (add-to-list
1789        'org-ref-cite-menu-funcs
1790        '("P" "ubmed" org-ref-pubmed-at-point) t))
1791
1792     ;; add user functions
1793     (dolist (tup org-ref-user-cite-menu-funcs)
1794       (add-to-list
1795        'org-ref-cite-menu-funcs
1796        tup t))
1797
1798     ;; finally quit
1799     (add-to-list
1800      'org-ref-cite-menu-funcs
1801      '("q" "uit" (lambda ())) t)
1802
1803     ;; now we make a menu
1804     ;; construct menu string as a message
1805     (message
1806      (concat
1807       (let* ((results (org-ref-get-bibtex-key-and-file))
1808              (key (car results))
1809              (bibfile (cdr results)))
1810         (save-excursion
1811           (with-temp-buffer
1812             (insert-file-contents bibfile)
1813             (bibtex-search-entry key)
1814             (org-ref-bib-citation))))
1815       "\n"
1816       (mapconcat
1817        (lambda (tup)
1818          (concat "[" (elt tup 0) "]"
1819                  (elt tup 1) " "))
1820        org-ref-cite-menu-funcs "")))
1821     ;; get the input
1822     (let* ((input (read-char-exclusive))
1823            (choice (assoc
1824                     (char-to-string input) org-ref-cite-menu-funcs)))
1825       ;; now run the function (2nd element in choice)
1826       (when choice
1827         (funcall
1828          (elt
1829           choice
1830           2))))))
1831 #+END_SRC
1832
1833 #+RESULTS:
1834 : org-ref-cite-onclick-minibuffer-menu
1835
1836 *** A function to format a cite link
1837
1838 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.
1839
1840 #+BEGIN_SRC emacs-lisp  :tangle no
1841 ;(defun org-ref-cite-link-format (keyword desc format)
1842 ;   (cond
1843 ;    ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1844 ;    ((eq format 'latex)
1845 ;     (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1846 ;            (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1847 ;            "}"))))
1848 #+END_SRC
1849
1850 *** The actual cite link
1851 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1852
1853 #+BEGIN_SRC emacs-lisp :tangle no
1854 ;(org-add-link-type
1855 ; "cite"
1856 ; 'org-ref-cite-onclick-minibuffer-menu
1857 ; 'org-ref-cite-link-format)
1858 #+END_SRC
1859
1860 *** Automatic definition of the cite links
1861 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.
1862
1863 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1864 (defmacro org-ref-make-completion-function (type)
1865   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1866      (interactive)
1867      (format "%s:%s"
1868              ,type
1869              (completing-read
1870               "bibtex key: "
1871               (let ((bibtex-files (org-ref-find-bibliography)))
1872                 (bibtex-global-key-alist))))))
1873 #+END_SRC
1874
1875 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.
1876
1877 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1878 (defmacro org-ref-make-format-function (type)
1879   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1880      (cond
1881       ((eq format 'org)
1882        (mapconcat
1883         (lambda (key)
1884           (format "[[#%s][%s]]" key key))
1885         (org-ref-split-and-strip-string keyword) ","))
1886
1887       ((eq format 'ascii)
1888        (concat "["
1889                (mapconcat
1890                 (lambda (key)
1891                   (format "%s" key))
1892                 (org-ref-split-and-strip-string keyword) ",") "]"))
1893
1894       ((eq format 'html)
1895        (mapconcat
1896         (lambda (key)
1897           (format "<a href=\"#%s\">%s</a>" key key))
1898         (org-ref-split-and-strip-string keyword) ","))
1899
1900       ((eq format 'latex)
1901        (if (string= (substring type -1) "s")
1902            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1903            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1904                                          (org-ref-split-and-strip-string keyword) ""))
1905          ;; bibtex format
1906        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1907                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1908                "}"))))))
1909 #+END_SRC
1910
1911
1912
1913 We create the links by mapping the function onto the list of defined link types.
1914
1915 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1916 (defun org-ref-format-citation-description (desc)
1917   "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 ::."
1918   (interactive)
1919   (cond
1920    ((string-match "::" desc)
1921     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1922    (t (format "[%s]" desc))))
1923
1924 (defun org-ref-define-citation-link (type &optional key)
1925   "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1926 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1927 and the completion function."
1928   (interactive "sCitation Type: \ncKey: ")
1929
1930   ;; create the formatting function
1931   (eval `(org-ref-make-format-function ,type))
1932
1933   (eval-expression
1934    `(org-add-link-type
1935      ,type
1936      org-ref-cite-onclick-function
1937      (quote ,(intern (format "org-ref-format-%s" type)))))
1938
1939   ;; create the completion function
1940   (eval `(org-ref-make-completion-function ,type))
1941
1942   ;; store new type so it works with adding citations, which checks
1943   ;; for existence in this list
1944   (add-to-list 'org-ref-cite-types type)
1945
1946   ;; and finally if a key is specified, we modify the reftex menu
1947   (when key
1948     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1949           (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1950                   `((,key  . ,(concat type ":%l")))))))
1951
1952 ;; create all the link types and their completion functions
1953 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1954 #+END_SRC
1955
1956 *** org-ref-insert-cite-link
1957 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.
1958
1959 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1960 (defun org-ref-insert-cite-link (alternative-cite)
1961   "Insert a default citation link using reftex. If you are on a link, it
1962 appends to the end of the link, otherwise, a new link is
1963 inserted. Use a prefix arg to get a menu of citation types."
1964   (interactive "P")
1965   (org-ref-find-bibliography)
1966   (let* ((object (org-element-context))
1967          (link-string-beginning (org-element-property :begin object))
1968          (link-string-end (org-element-property :end object))
1969          (path (org-element-property :path object)))
1970
1971     (if (not alternative-cite)
1972
1973         (cond
1974          ;; case where we are in a link
1975          ((and (equal (org-element-type object) 'link)
1976                (-contains? org-ref-cite-types (org-element-property :type object)))
1977           (goto-char link-string-end)
1978           ;; sometimes there are spaces at the end of the link
1979           ;; this code moves point pack until no spaces are there
1980           (while (looking-back " ") (backward-char))
1981           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1982
1983          ;; We are next to a link, and we want to append
1984          ((save-excursion
1985             (backward-char)
1986             (and (equal (org-element-type (org-element-context)) 'link)
1987                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1988           (while (looking-back " ") (backward-char))
1989           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1990
1991          ;; insert fresh link
1992          (t
1993           (insert
1994            (concat org-ref-default-citation-link
1995                    ":"
1996                    (mapconcat 'identity (reftex-citation t) ",")))))
1997
1998       ;; you pressed a C-u so we run this code
1999       (reftex-citation)))
2000   )
2001 #+END_SRC
2002 cite:zhou-2004-first-lda-u,paier-2006-errat,boes-2015-estim-bulk
2003
2004
2005 #+RESULTS:
2006 : org-ref-insert-cite-link
2007
2008 *** Completion in cite links
2009 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.
2010
2011 #+BEGIN_SRC emacs-lisp  :tangle no
2012 (defun org-cite-complete-link (&optional arg)
2013   "Completion function for cite links"
2014   (format "%s:%s"
2015           org-ref-default-citation-link
2016           (completing-read
2017            "bibtex key: "
2018            (let ((bibtex-files (org-ref-find-bibliography)))
2019              (bibtex-global-key-alist)))))
2020 #+END_SRC
2021
2022 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
2023
2024 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2025 (defun org-ref-insert-cite-with-completion (type)
2026   "Insert a cite link with completion"
2027   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
2028   (insert (funcall (intern (format "org-%s-complete-link" type)))))
2029 #+END_SRC
2030
2031 ** Storing links to a bibtex entry
2032 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.
2033
2034 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2035 (defun org-ref-store-bibtex-entry-link ()
2036   "Save a citation link to the current bibtex entry. Saves in the default link type."
2037   (interactive)
2038   (let ((link (concat org-ref-default-citation-link
2039                  ":"
2040                  (save-excursion
2041                    (bibtex-beginning-of-entry)
2042                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
2043     (message "saved %s" link)
2044     (push (list link) org-stored-links)
2045     (car org-stored-links)))
2046 #+END_SRC
2047
2048 ** Index entries
2049 org-ref minimally supports index entries. To make an index in a file, you should put in the LaTeX header these lines
2050
2051
2052 #+LATEX_HEADER: \usepackage{makeidx}
2053 #+LATEX_HEADER: \makeindex
2054
2055
2056 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.
2057
2058
2059 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.
2060
2061
2062 index:hello
2063 index:hello!Peter
2064 [[index:hello!Sam@\textsl{Sam}]]
2065 [[index:Lin@\textbf{Lin}]]
2066 [[index:Joe|textit]]
2067 [[index:Lin@\textbf{Lin}]]
2068 [[index:Peter|see {hello}]]
2069 [[index:Jen|seealso{Jenny}]]
2070
2071 index:encodings!input!cp850
2072
2073 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2074 (org-add-link-type
2075  "index"
2076  (lambda (path)
2077    (occur path))
2078
2079  (lambda (path desc format)
2080    (cond
2081     ((eq format 'latex)
2082       (format "\\index{%s}" path)))))
2083
2084 ;; this will generate a temporary index of entries in the file.
2085 (org-add-link-type
2086  "printindex"
2087  (lambda (path)
2088    (let ((*index-links* '())
2089          (*initial-letters* '()))
2090
2091      ;; get links
2092      (org-element-map (org-element-parse-buffer) 'link
2093        (lambda (link)
2094          (let ((type (nth 0 link))
2095                (plist (nth 1 link)))
2096
2097            (when (equal (plist-get plist ':type) "index")
2098              (add-to-list
2099               '*index-links*
2100               (cons (plist-get plist :path)
2101                     (format
2102                      "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2103 (current-buffer)
2104                      (plist-get plist :begin)  ;; position of link
2105                      ;; grab a description
2106                      (save-excursion
2107                        (goto-char (plist-get plist :begin))
2108                        (if (thing-at-point 'sentence)
2109                            ;; get a sentence
2110                            (replace-regexp-in-string
2111                             "\n" "" (thing-at-point 'sentence))
2112                          ;; or call it a link
2113                          "link")))))))))
2114
2115      ;; sort the links
2116      (setq *index-links*  (cl-sort *index-links* 'string-lessp :key 'car))
2117
2118      ;; now first letters
2119      (dolist (link *index-links*)
2120        (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2121
2122      ;; now create the index
2123      (switch-to-buffer (get-buffer-create "*index*"))
2124      (org-mode)
2125      (erase-buffer)
2126      (insert "#+TITLE: Index\n\n")
2127      (dolist (letter *initial-letters*)
2128        (insert (format "* %s\n" (upcase letter)))
2129        ;; now process the links
2130        (while (and
2131                ,*index-links*
2132                (string= letter (substring (car (car *index-links*)) 0 1)))
2133          (let ((link (pop *index-links*)))
2134            (insert (format "%s %s\n\n" (car link) (cdr link))))))
2135      (switch-to-buffer "*index*")))
2136  ;; formatting
2137  (lambda (path desc format)
2138    (cond
2139     ((eq format 'latex)
2140       (format "\\printindex")))))
2141 #+END_SRC
2142
2143 #+RESULTS:
2144 | 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*)) |
2145 | lambda | (path desc format) | (cond ((eq format (quote latex)) (format \printindex)))                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
2146
2147 ** Glossary
2148 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.
2149
2150 #+LATEX_HEADER: \usepackage{glossaries}
2151 #+LATEX_HEADER: \makeglossaries
2152
2153 And at the end of the document put \makeglossaries.
2154
2155 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2156 (org-add-link-type
2157  "newglossaryentry"
2158  nil ;; no follow action
2159  (lambda (path desc format)
2160    (cond
2161     ((eq format 'latex)
2162      (format "\\newglossaryentry{%s}{%s}" path desc)))))
2163
2164
2165 ;; link to entry
2166 (org-add-link-type
2167  "gls"
2168   nil ;; no follow action
2169  (lambda (path desc format)
2170    (cond
2171     ((eq format 'latex)
2172      (format "\\gls{%s}" path)))))
2173
2174 ;; plural
2175 (org-add-link-type
2176  "glspl"
2177   nil ;; no follow action
2178  (lambda (path desc format)
2179    (cond
2180     ((eq format 'latex)
2181      (format "\\glspl{%s}" path)))))
2182
2183 ;; capitalized link
2184 (org-add-link-type
2185  "Gls"
2186   nil ;; no follow action
2187  (lambda (path desc format)
2188    (cond
2189     ((eq format 'latex)
2190      (format "\\Gls{%s}" path)))))
2191
2192 ;; capitalized link
2193 (org-add-link-type
2194  "Glspl"
2195   nil ;; no follow action
2196  (lambda (path desc format)
2197    (cond
2198     ((eq format 'latex)
2199      (format "\\Glspl{%s}" path)))))
2200 #+END_SRC
2201
2202 * Utilities
2203 ** create simple text citation from bibtex entry
2204
2205 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2206 (defun org-ref-bib-citation ()
2207   "From a bibtex entry, create and return a simple citation string.
2208 This assumes you are in an article."
2209
2210   (bibtex-beginning-of-entry)
2211   (let* ((cb (current-buffer))
2212          (bibtex-expand-strings t)
2213          (entry (loop for (key . value) in (bibtex-parse-entry t)
2214                       collect (cons (downcase key) value)))
2215          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2216          (year  (reftex-get-bib-field "year" entry))
2217          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2218          (key (reftex-get-bib-field "=key=" entry))
2219          (journal (reftex-get-bib-field "journal" entry))
2220          (volume (reftex-get-bib-field "volume" entry))
2221          (pages (reftex-get-bib-field "pages" entry))
2222          (doi (reftex-get-bib-field "doi" entry))
2223          (url (reftex-get-bib-field "url" entry))
2224          )
2225     ;;authors, "title", Journal, vol(iss):pages (year).
2226     (format "%s, \"%s\", %s, %s:%s (%s)"
2227             author title journal  volume pages year)))
2228 #+END_SRC
2229
2230 #+RESULTS:
2231 : org-ref-bib-citation
2232
2233
2234 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2235 (defun org-ref-bib-html-citation ()
2236   "from a bibtex entry, create and return a simple citation with html links."
2237
2238   (bibtex-beginning-of-entry)
2239   (let* ((cb (current-buffer))
2240          (bibtex-expand-strings t)
2241          (entry (loop for (key . value) in (bibtex-parse-entry t)
2242                       collect (cons (downcase key) value)))
2243          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2244          (year  (reftex-get-bib-field "year" entry))
2245          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2246          (key (reftex-get-bib-field "=key=" entry))
2247          (journal (reftex-get-bib-field "journal" entry))
2248          (volume (reftex-get-bib-field "volume" entry))
2249          (pages (reftex-get-bib-field "pages" entry))
2250          (doi (reftex-get-bib-field "doi" entry))
2251          (url (reftex-get-bib-field "url" entry))
2252          )
2253     ;;authors, "title", Journal, vol(iss):pages (year).
2254     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2255                     author title journal  volume pages year)
2256             (when url (format " <a href=\"%s\">link</a>" url))
2257             (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2258     ))
2259 #+END_SRC
2260
2261 ** open pdf from bibtex
2262 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2263 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2264 (defun org-ref-open-bibtex-pdf ()
2265   "open pdf for a bibtex entry, if it exists. assumes point is in
2266 the entry of interest in the bibfile. but does not check that."
2267   (interactive)
2268   (save-excursion
2269     (bibtex-beginning-of-entry)
2270     (let* ((bibtex-expand-strings t)
2271            (entry (bibtex-parse-entry t))
2272            (key (reftex-get-bib-field "=key=" entry))
2273            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2274       (message "%s" pdf)
2275       (if (file-exists-p pdf)
2276           (org-open-link-from-string (format "[[file:%s]]" pdf))
2277         (ding)))))
2278 #+END_SRC
2279
2280 ** open notes from bibtex
2281 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2282
2283 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2284 (defun org-ref-open-bibtex-notes ()
2285   "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
2286
2287 I never did figure out how to use reftex to make this happen
2288 non-interactively. the reftex-format-citation function did not
2289 work perfectly; there were carriage returns in the strings, and
2290 it did not put the key where it needed to be. so, below I replace
2291 the carriage returns and extra spaces with a single space and
2292 construct the heading by hand."
2293   (interactive)
2294
2295   (bibtex-beginning-of-entry)
2296   (let* ((cb (current-buffer))
2297          (bibtex-expand-strings t)
2298          (entry (loop for (key . value) in (bibtex-parse-entry t)
2299                       collect (cons (downcase key) value)))
2300          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2301          (year  (reftex-get-bib-field "year" entry))
2302          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2303          (key (reftex-get-bib-field "=key=" entry))
2304          (journal (reftex-get-bib-field "journal" entry))
2305          (volume (reftex-get-bib-field "volume" entry))
2306          (pages (reftex-get-bib-field "pages" entry))
2307          (doi (reftex-get-bib-field "doi" entry))
2308          (url (reftex-get-bib-field "url" entry))
2309          )
2310
2311     ;; save key to clipboard to make saving pdf later easier by pasting.
2312     (with-temp-buffer
2313       (insert key)
2314       (kill-ring-save (point-min) (point-max)))
2315
2316     ;; now look for entry in the notes file
2317     (if  org-ref-bibliography-notes
2318         (find-file-other-window org-ref-bibliography-notes)
2319       (error "org-ref-bib-bibliography-notes is not set to anything"))
2320
2321     (goto-char (point-min))
2322     ;; put new entry in notes if we don't find it.
2323     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2324         (funcall org-ref-open-notes-function)
2325       ;; no entry found, so add one
2326       (insert (format "\n** TODO %s - %s" year title))
2327       (insert (format"
2328  :PROPERTIES:
2329   :Custom_ID: %s
2330   :AUTHOR: %s
2331   :JOURNAL: %s
2332   :YEAR: %s
2333   :VOLUME: %s
2334   :PAGES: %s
2335   :DOI: %s
2336   :URL: %s
2337  :END:
2338 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2339 key author journal year volume pages doi url key org-ref-pdf-directory key))
2340 (save-buffer))))
2341 #+END_SRC
2342
2343 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2344 (defun org-ref-open-notes-from-reftex ()
2345   "Call reftex, and open notes for selected entry."
2346   (interactive)
2347   (let ((bibtex-key )))
2348
2349     ;; now look for entry in the notes file
2350     (if  org-ref-bibliography-notes
2351         (find-file-other-window org-ref-bibliography-notes)
2352       (error "org-ref-bib-bibliography-notes is not set to anything"))
2353
2354     (goto-char (point-min))
2355
2356     (re-search-forward (format
2357                         ":Custom_ID: %s$"
2358                         (first (reftex-citation t)) nil 'end))
2359     (funcall org-ref-open-notes-function))
2360 #+END_SRC
2361
2362 ** open url in browser from bibtex
2363
2364 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2365
2366 + 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.
2367
2368 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2369 (defun org-ref-open-in-browser ()
2370   "Open the bibtex entry at point in a browser using the url field or doi field"
2371 (interactive)
2372 (save-excursion
2373   (bibtex-beginning-of-entry)
2374   (catch 'done
2375     (let ((url (bibtex-autokey-get-field "url")))
2376       (when  url
2377         (browse-url url)
2378         (throw 'done nil)))
2379
2380     (let ((doi (bibtex-autokey-get-field "doi")))
2381       (when doi
2382         (if (string-match "^http" doi)
2383             (browse-url doi)
2384           (browse-url (format "http://dx.doi.org/%s" doi)))
2385         (throw 'done nil)))
2386     (message "No url or doi found"))))
2387 #+END_SRC
2388
2389 ** citeulike
2390    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.
2391
2392 *** function to upload bibtex to citeulike
2393
2394 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2395 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2396   "with point in  a bibtex entry get bibtex string and submit to citeulike.
2397
2398 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2399   (interactive)
2400   (message "uploading to citeulike")
2401   (save-restriction
2402     (bibtex-narrow-to-entry)
2403     (let ((startpos (point-min))
2404           (endpos (point-max))
2405           (bibtex-string (buffer-string))
2406           (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2407       (with-temp-buffer (insert bibtex-string)
2408                         (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2409 #+END_SRC
2410
2411 *** The upload script
2412 Here is the python script for uploading.
2413
2414 *************** TODO document how to get the cookies
2415 *************** END
2416
2417
2418 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
2419 #!python
2420 import pickle, requests, sys
2421
2422 # reload cookies
2423 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
2424     cookies = pickle.load(f)
2425
2426 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
2427
2428 bibtex = sys.stdin.read()
2429
2430 data = {'pasted':bibtex,
2431         'to_read':2,
2432         'tag_parsing':'simple',
2433         'strip_brackets':'no',
2434         'update_id':'bib-key',
2435         'btn_bibtex':'Import BibTeX file ...'}
2436
2437 headers = {'content-type': 'multipart/form-data',
2438            'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
2439
2440 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
2441 print r
2442 #+END_SRC
2443
2444 ** Build a pdf from a bibtex file
2445    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.
2446
2447 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2448 (defun org-ref-build-full-bibliography ()
2449   "build pdf of all bibtex entries, and open it."
2450   (interactive)
2451   (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2452         (bib-base (file-name-sans-extension bibfile))
2453         (texfile (concat bib-base ".tex"))
2454         (pdffile (concat bib-base ".pdf")))
2455     (find-file texfile)
2456     (erase-buffer)
2457     (insert (format "\\documentclass[12pt]{article}
2458 \\usepackage[version=3]{mhchem}
2459 \\usepackage{url}
2460 \\usepackage[numbers]{natbib}
2461 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2462 \\usepackage{doi}
2463 \\begin{document}
2464 \\nocite{*}
2465 \\bibliographystyle{unsrtnat}
2466 \\bibliography{%s}
2467 \\end{document}" bib-base))
2468     (save-buffer)
2469     (shell-command (concat "pdflatex " bib-base))
2470     (shell-command (concat "bibtex " bib-base))
2471     (shell-command (concat "pdflatex " bib-base))
2472     (shell-command (concat "pdflatex " bib-base))
2473     (kill-buffer texfile)
2474     (org-open-file pdffile)
2475     ))
2476 #+END_SRC
2477
2478 ** Extract bibtex entries cited in an org-file
2479 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.
2480
2481 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
2482 (defun org-ref-extract-bibtex-entries ()
2483   "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2484
2485 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
2486   (interactive)
2487   (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2488          (tempname (make-temp-file "extract-bib"))
2489          (contents (buffer-string))
2490          (cb (current-buffer))
2491          basename texfile bibfile results)
2492
2493     ;; open tempfile and insert org-buffer contents
2494     (find-file tempname)
2495     (insert contents)
2496     (setq basename (file-name-sans-extension
2497                     (file-name-nondirectory buffer-file-name))
2498           texfile (concat tempname ".tex")
2499           bibfile (concat tempname ".bib"))
2500
2501     ;; see if we have a bibliography, and insert the default one if not.
2502     (save-excursion
2503       (goto-char (point-min))
2504       (unless (re-search-forward "^bibliography:" (point-max) 'end)
2505         (insert (format "\nbibliography:%s"
2506                         (mapconcat 'identity reftex-default-bibliography ",")))))
2507     (save-buffer)
2508
2509     ;; get a latex file and extract the references
2510     (org-latex-export-to-latex)
2511     (find-file texfile)
2512     (reftex-parse-all)
2513     (reftex-create-bibtex-file bibfile)
2514     (save-buffer)
2515     ;; save results of the references
2516     (setq results (buffer-string))
2517
2518     ;; kill buffers. these are named by basename, not full path
2519     (kill-buffer (concat basename ".bib"))
2520     (kill-buffer (concat basename ".tex"))
2521     (kill-buffer basename)
2522
2523     (delete-file bibfile)
2524     (delete-file texfile)
2525     (delete-file tempname)
2526
2527     ;; Now back to the original org buffer and insert the results
2528     (switch-to-buffer cb)
2529     (when (not (string= "" results))
2530       (save-excursion
2531         (goto-char (point-max))
2532         (insert "\n\n")
2533         (org-insert-heading)
2534         (insert (format " Bibtex entries
2535
2536 ,#+BEGIN_SRC text :tangle %s
2537 %s
2538 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2539 #+END_SRC
2540
2541 ** Find bad cite links
2542    :PROPERTIES:
2543    :ID:       8515E800-EDA0-4B2A-85FD-55B6FF849203
2544    :END:
2545 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.
2546
2547 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
2548 (require 'cl)
2549
2550 (defun index (substring list)
2551   "return the index of string in a list of strings"
2552   (let ((i 0)
2553         (found nil))
2554     (dolist (arg list i)
2555       (if (string-match (concat "^" substring "$") arg)
2556           (progn
2557             (setq found t)
2558             (return i)))
2559       (setq i (+ i 1)))
2560     ;; return counter if found, otherwise return nil
2561     (if found i nil)))
2562
2563
2564 (defun org-ref-find-bad-citations ()
2565   "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2566
2567 Makes a new buffer with clickable links."
2568   (interactive)
2569   ;; generate the list of bibtex-keys and cited keys
2570   (let* ((bibtex-files (org-ref-find-bibliography))
2571          (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2572          (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2573          (bad-citations '()))
2574
2575     (org-element-map (org-element-parse-buffer) 'link
2576       (lambda (link)
2577         (let ((plist (nth 1 link)))
2578           (when (equal (plist-get plist ':type) "cite")
2579             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2580               (when (not (index key bibtex-keys))
2581                 (setq bad-citations (append bad-citations
2582                                             `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2583                                                        key (buffer-name)(plist-get plist ':begin)))))
2584                 ))))))
2585
2586     (if bad-citations
2587       (progn
2588         (switch-to-buffer-other-window "*Missing citations*")
2589         (org-mode)
2590         (erase-buffer)
2591         (insert "* List of bad cite links\n")
2592         (insert (mapconcat 'identity bad-citations ""))
2593                                         ;(setq buffer-read-only t)
2594         (use-local-map (copy-keymap org-mode-map))
2595         (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2596
2597       (when (get-buffer "*Missing citations*")
2598           (kill-buffer "*Missing citations*"))
2599       (message "No bad cite links found"))))
2600 #+END_SRC
2601
2602 ** helm interface to org-ref
2603 In [[id:8515E800-EDA0-4B2A-85FD-55B6FF849203][Find bad cite links]] we wrote a function that finds bad links and creates a buffer of links to them.
2604
2605 Here we develop a similar idea, but instead of an org-buffer with links, we create helm sources for bad cite links, bad ref links, and multiple labels.
2606
2607 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2608 (defun org-ref-bad-cite-candidates ()
2609   "Returns a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2610   (let* ((cp (point))                   ; save to return to later
2611          (bibtex-files (org-ref-find-bibliography))
2612          (bibtex-file-path (mapconcat
2613                             (lambda (x)
2614                               (file-name-directory (file-truename x)))
2615                             bibtex-files ":"))
2616          (bibtex-keys (mapcar (lambda (x) (car x))
2617                               (bibtex-global-key-alist)))
2618          (bad-citations '()))
2619
2620     (org-element-map (org-element-parse-buffer) 'link
2621       (lambda (link)
2622         (let ((plist (nth 1 link)))
2623           (when (-contains? org-ref-cite-types (plist-get plist ':type))
2624             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2625               (when (not (index key bibtex-keys))
2626                 (goto-char (plist-get plist ':begin))
2627                 (re-search-forward key)
2628                 (push (cons key (point-marker)) bad-citations)))
2629               ))))
2630     (goto-char cp)
2631     bad-citations))
2632
2633 ;; It seems I forgot I already defined this earlier!
2634 ;; (defun org-ref-get-labels ()
2635 ;;   "Returns a list of known labels in the org document. These include label links, latex labels, label tags, and table names. The list contains all labels, not just unique ones.
2636 ;; "
2637 ;;   (let ((cp (point))
2638 ;;      (labels '()))
2639 ;;     (goto-char (point-min))
2640 ;;     (while (re-search-forward "[^#+]label:\\(.*\\)\\s-" nil t)
2641 ;;       (push  (match-string 1) labels))
2642
2643 ;;     (goto-char (point-min))
2644 ;;     (while (re-search-forward "\\label{\\(.*\\)}\\s-?" nil t)
2645 ;;       (push (match-string 1) labels))
2646
2647 ;;     (goto-char (point-min))
2648 ;;     (while (re-search-forward "^#\\+label:\\s-*\\(.*\\)" nil t)
2649 ;;       (push (match-string 1) labels))
2650
2651 ;;     (goto-char (point-min))
2652 ;;     (while (re-search-forward "^#\\+tblname:\\s-*\\(.*\\)" nil t)
2653 ;;       (push (match-string 1) labels))
2654 ;;     ;; check for CUSTOM_ID
2655 ;;     (org-map-entries
2656 ;;      (lambda ()
2657 ;;        (when (org-entry-get (point) "CUSTOM_ID")
2658 ;;       (push (org-entry-get (point) "CUSTOM_ID") labels))))
2659 ;;     ;; return to original place
2660 ;;     (goto-char cp)
2661 ;;     labels))
2662
2663
2664 (defun org-ref-bad-ref-candidates ()
2665   "Returns a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2666   ;; first get a list of legitimate labels
2667   (let ((cp (point))
2668         (labels (org-ref-get-labels))
2669         (bad-refs '()))
2670     ;; now loop over ref links
2671     (goto-char (point-min))
2672     (org-element-map (org-element-parse-buffer) 'link
2673       (lambda (link)
2674         (let ((plist (nth 1 link)))
2675           (when (or  (equal (plist-get plist ':type) "ref")
2676                      (equal (plist-get plist ':type) "eqref")
2677                      (equal (plist-get plist ':type) "pageref")
2678                      (equal (plist-get plist ':type) "nameref"))
2679             (unless (-contains? labels (plist-get plist :path))
2680               (goto-char (plist-get plist :begin))
2681               (add-to-list
2682                'bad-refs
2683                (cons (plist-get plist :path)
2684                      (point-marker))))))))
2685     (goto-char cp)
2686     bad-refs))
2687
2688
2689 (defun org-ref-bad-label-candidates ()
2690   "Return a list of labels where label is multiply defined."
2691   (let ((labels (org-ref-get-labels))
2692         (multiple-labels '()))
2693     (when (not (= (length labels)
2694                   (length (-uniq labels))))
2695       (dolist (label labels)
2696         (when (> (-count (lambda (a)
2697                            (equal a label))
2698                          labels) 1)
2699           ;; this is a multiply defined label.
2700           (let ((cp (point)))
2701             (goto-char (point-min))
2702             (while (re-search-forward
2703                     (format  "[^#+]label:%s\\s-" label) nil t)
2704               (push (cons label (point-marker)) multiple-labels))
2705
2706             (goto-char (point-min))
2707             (while (re-search-forward
2708                     (format  "\\label{%s}\\s-?" label) nil t)
2709               (push (cons label (point-marker)) multiple-labels))
2710
2711             (goto-char (point-min))
2712             (while (re-search-forward
2713                     (format  "^#\\+label:\\s-*%s" label) nil t)
2714               (push (cons label (point-marker)) multiple-labels))
2715
2716             (goto-char (point-min))
2717             (while (re-search-forward
2718                     (format   "^#\\+tblname:\\s-*%s" label) nil t)
2719               (push (cons label (point-marker)) multiple-labels))
2720             (goto-char cp)))))
2721       multiple-labels))
2722 #+END_SRC
2723
2724 #+RESULTS:
2725 : org-ref-bad-label-candidates
2726
2727 Now, we have a functions for candidates, we can make helm sources for each one, and then run a helm command to view them.
2728
2729 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2730 (defun org-ref ()
2731   "Opens a helm interface to actions for org-ref.
2732 Shows bad citations, ref links and labels"
2733   (interactive)
2734   (let ((cb (current-buffer))
2735         (bad-citations (org-ref-bad-cite-candidates))
2736         (bad-refs (org-ref-bad-ref-candidates))
2737         (bad-labels (org-ref-bad-label-candidates)))
2738
2739     (helm :sources `(((name . "Bad citations")
2740                        (candidates . ,bad-citations)
2741                        (action . (lambda (marker)
2742                                    (switch-to-buffer (marker-buffer marker))
2743                                    (goto-char marker))))
2744                      ;;
2745                      ((name . "Bad Labels")
2746                       (candidates . ,bad-labels)
2747                       (action . (lambda (marker)
2748                                    (switch-to-buffer (marker-buffer marker))
2749                                    (goto-char marker))))
2750                      ;;
2751                      ((name . "Bad ref links")
2752                       (candidates . ,bad-refs)
2753                       (action . (lambda (marker)
2754                                           (switch-to-buffer (marker-buffer marker))
2755                                           (goto-char marker))))
2756                      ;;
2757                      ((name . "Utilities")
2758                       (candidates . (("Check buffer again" . org-ref)
2759                                      ("Insert citation" . helm-bibtex)
2760                                      ("Insert label link" . org-ref-helm-insert-label-link)
2761                                      ("Insert ref link" . org-ref-helm-insert-ref-link)
2762                                      ("List of figures" . org-ref-list-of-figures)
2763                                      ("List of tables" . org-ref-list-of-tables)
2764                                      ("Table of contents" . nil)
2765                                      ))
2766                       (action . (lambda (x)
2767                                   (switch-to-buffer ,cb)
2768                                   (funcall x))))
2769                      ;;
2770                      ((name . "Export functions")
2771                       (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2772                                      ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2773                                      ("Export to pdf and open" . (lambda ()
2774                                                                    (org-open-file (org-latex-export-to-pdf))))
2775                                      ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2776                                      ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2777
2778                                      ))
2779                       (action . (lambda (x)
2780                                   (switch-to-buffer ,cb)
2781                                   (funcall x))))
2782                       ))))
2783 #+END_SRC
2784
2785
2786 ** Finding non-ascii characters
2787 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2788
2789 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2790 (defun org-ref-find-non-ascii-characters ()
2791   "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2792   (interactive)
2793   (occur "[^[:ascii:]]"))
2794 #+END_SRC
2795
2796 ** Resort a bibtex entry
2797 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.
2798
2799 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2800 (defun org-ref-sort-bibtex-entry ()
2801   "sort fields of entry in standard order and downcase them"
2802   (interactive)
2803   (bibtex-beginning-of-entry)
2804   (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2805          (entry (bibtex-parse-entry))
2806          (entry-fields)
2807          (other-fields)
2808          (type (cdr (assoc "=type=" entry)))
2809          (key (cdr (assoc "=key=" entry))))
2810
2811     ;; these are the fields we want to order that are in this entry
2812     (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2813     ;; we do not want to reenter these fields
2814     (setq entry-fields (remove "=key=" entry-fields))
2815     (setq entry-fields (remove "=type=" entry-fields))
2816
2817     ;;these are the other fields in the entry
2818     (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2819
2820     (cond
2821      ;; right now we only resort articles
2822      ((string= (downcase type) "article")
2823       (bibtex-kill-entry)
2824       (insert
2825        (concat "@article{" key ",\n"
2826                (mapconcat
2827                 (lambda (field)
2828                   (when (member field entry-fields)
2829                     (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2830                (mapconcat
2831                 (lambda (field)
2832                   (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2833                "\n}\n\n"))
2834       (bibtex-find-entry key)
2835       (bibtex-fill-entry)
2836       (bibtex-clean-entry)
2837        ))))
2838 #+END_SRC
2839
2840 ** Clean a bibtex entry
2841    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.
2842 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.
2843 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2844 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2845   "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"
2846   (interactive "P")
2847   (bibtex-beginning-of-entry)
2848 (end-of-line)
2849   ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2850   (unless (string-match ",$" (thing-at-point 'line))
2851     (end-of-line)
2852     (insert ","))
2853
2854   ;; check for empty pages, and put eid or article id in its place
2855   (let ((entry (bibtex-parse-entry))
2856         (pages (bibtex-autokey-get-field "pages"))
2857         (year (bibtex-autokey-get-field "year"))
2858         (doi  (bibtex-autokey-get-field "doi"))
2859         ;; The Journal of Chemical Physics uses eid
2860         (eid (bibtex-autokey-get-field "eid")))
2861
2862     ;; replace http://dx.doi.org/ in doi. some journals put that in,
2863     ;; but we only want the doi.
2864     (when (string-match "^http://dx.doi.org/" doi)
2865       (bibtex-beginning-of-entry)
2866       (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2867       (bibtex-kill-field)
2868       (bibtex-make-field "doi")
2869       (backward-char)
2870       (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2871
2872     ;; asap articles often set year to 0, which messes up key
2873     ;; generation. fix that.
2874     (when (string= "0" year)
2875       (bibtex-beginning-of-entry)
2876       (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2877       (bibtex-kill-field)
2878       (bibtex-make-field "year")
2879       (backward-char)
2880       (insert (read-string "Enter year: ")))
2881
2882     ;; fix pages if they are empty if there is an eid to put there.
2883     (when (string= "-" pages)
2884       (when eid
2885         (bibtex-beginning-of-entry)
2886         ;; this seems like a clunky way to set the pages field.But I
2887         ;; cannot find a better way.
2888         (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2889         (bibtex-kill-field)
2890         (bibtex-make-field "pages")
2891         (backward-char)
2892         (insert eid)))
2893
2894     ;; replace naked & with \&
2895     (save-restriction
2896       (bibtex-narrow-to-entry)
2897       (bibtex-beginning-of-entry)
2898       (message "checking &")
2899       (replace-regexp " & " " \\\\& ")
2900       (widen))
2901
2902     ;; generate a key, and if it duplicates an existing key, edit it.
2903     (unless keep-key
2904       (let ((key (bibtex-generate-autokey)))
2905
2906         ;; first we delete the existing key
2907         (bibtex-beginning-of-entry)
2908         (re-search-forward bibtex-entry-maybe-empty-head)
2909         (if (match-beginning bibtex-key-in-head)
2910             (delete-region (match-beginning bibtex-key-in-head)
2911                            (match-end bibtex-key-in-head)))
2912         ;; check if the key is in the buffer
2913         (when (save-excursion
2914                 (bibtex-search-entry key))
2915           (save-excursion
2916             (bibtex-search-entry key)
2917             (bibtex-copy-entry-as-kill)
2918             (switch-to-buffer-other-window "*duplicate entry*")
2919             (bibtex-yank))
2920           (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2921
2922         (insert key)
2923         (kill-new key))) ;; save key for pasting
2924
2925     ;; run hooks. each of these operates on the entry with no arguments.
2926     ;; this did not work like  i thought, it gives a symbolp error.
2927     ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2928     (mapcar (lambda (x)
2929               (save-restriction
2930                 (save-excursion
2931                   (funcall x))))
2932             org-ref-clean-bibtex-entry-hook)
2933
2934     ;; sort fields within entry
2935     (org-ref-sort-bibtex-entry)
2936     ;; check for non-ascii characters
2937     (occur "[^[:ascii:]]")
2938     ))
2939 #+END_SRC
2940
2941 #+RESULTS:
2942 : org-ref-clean-bibtex-entry
2943
2944 ** Sort the entries in a citation link by year
2945 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2946
2947 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2948 (defun org-ref-get-citation-year (key)
2949   "get the year of an entry with key. Returns year as a string."
2950   (interactive)
2951   (let* ((results (org-ref-get-bibtex-key-and-file key))
2952          (bibfile (cdr results)))
2953     (with-temp-buffer
2954       (insert-file-contents bibfile)
2955       (bibtex-search-entry key nil 0)
2956       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2957         ))))
2958
2959 (defun org-ref-sort-citation-link ()
2960  "replace link at point with sorted link by year"
2961  (interactive)
2962  (let* ((object (org-element-context))
2963         (type (org-element-property :type object))
2964         (begin (org-element-property :begin object))
2965         (end (org-element-property :end object))
2966         (link-string (org-element-property :path object))
2967         keys years data)
2968   (setq keys (org-ref-split-and-strip-string link-string))
2969   (setq years (mapcar 'org-ref-get-citation-year keys))
2970   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2971   (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2972   ;; now get the keys separated by commas
2973   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2974   ;; and replace the link with the sorted keys
2975   (cl--set-buffer-substring begin end (concat type ":" keys))))
2976 #+END_SRC
2977
2978 ** Sort entries in citation links with shift-arrow keys
2979 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2980 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2981 (defun org-ref-swap-keys (i j keys)
2982  "swap the keys in a list with index i and j"
2983  (let ((tempi (nth i keys)))
2984    (setf (nth i keys) (nth j keys))
2985    (setf (nth j keys) tempi))
2986   keys)
2987
2988 (defun org-ref-swap-citation-link (direction)
2989  "move citation at point in direction +1 is to the right, -1 to the left"
2990  (interactive)
2991  (let* ((object (org-element-context))
2992         (type (org-element-property :type object))
2993         (begin (org-element-property :begin object))
2994         (end (org-element-property :end object))
2995         (link-string (org-element-property :path object))
2996         key keys i)
2997    ;;   We only want this to work on citation links
2998    (when (-contains? org-ref-cite-types type)
2999         (setq key (org-ref-get-bibtex-key-under-cursor))
3000         (setq keys (org-ref-split-and-strip-string link-string))
3001         (setq i (index key keys))  ;; defined in org-ref
3002         (if (> direction 0) ;; shift right
3003             (org-ref-swap-keys i (+ i 1) keys)
3004           (org-ref-swap-keys i (- i 1) keys))
3005         (setq keys (mapconcat 'identity keys ","))
3006         ;; and replace the link with the sorted keys
3007         (cl--set-buffer-substring begin end (concat type ":" keys " "))
3008         ;; now go forward to key so we can move with the key
3009         (re-search-forward key)
3010         (goto-char (match-beginning 0)))))
3011
3012 ;; add hooks to make it work
3013 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
3014 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
3015 #+END_SRC
3016
3017 ** Lightweight messages about links
3018 To get a lighter weight message about the label, ref and cite links, we define a function that gives us the minibuffer message, without the menu. We run this in an idle timer.
3019
3020 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3021 (defun org-ref-get-label-context (label)
3022   "Return a string of context around a label."
3023   (save-excursion
3024     (catch 'result
3025       (goto-char (point-min))
3026       (when (re-search-forward
3027              (format "label:%s\\b" label) nil t)
3028         (throw 'result (buffer-substring
3029                         (progn
3030                           (previous-line)
3031                           (beginning-of-line)
3032                           (point))
3033                         (progn
3034                           (forward-line 4)
3035                           (point)))))
3036
3037       (goto-char (point-min))
3038       (when (re-search-forward
3039              (format "\\label{%s}" label) nil t)
3040         (throw 'result (buffer-substring
3041                         (progn
3042                           (previous-line)
3043                           (beginning-of-line)
3044                           (point))
3045                         (progn
3046                           (forward-line 4)
3047                           (point)))))
3048
3049       (goto-char (point-min))
3050       (when (re-search-forward
3051              (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
3052         (throw 'result (buffer-substring
3053                         (progn
3054                           (previous-line)
3055                           (beginning-of-line)
3056                           (point))
3057                         (progn
3058                           (forward-line 4)
3059                           (point)))))
3060
3061       (goto-char (point-min))
3062       (when (re-search-forward
3063              (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
3064         (throw 'result (buffer-substring
3065                         (progn
3066                           (previous-line)
3067                           (beginning-of-line)
3068                           (point))
3069                         (progn
3070                           (forward-line 4)
3071                           (point)))))
3072
3073       ;; maybe we have a CUSTOM-ID
3074       (org-map-entries
3075        (lambda () (when (string=
3076                          label
3077                          (org-entry-get (point) "CUSTOM_ID"))
3078                     (throw 'result (org-get-heading)))))
3079       (beep)
3080       (throw 'result "!!! NO CONTEXT FOUND !!!"))))
3081
3082
3083 (defun org-ref-link-message ()
3084   "Print a minibuffer message about the link that point is on."
3085   (interactive)
3086   (when (eq major-mode 'org-mode)
3087     (let* ((object (org-element-context))
3088            (type (org-element-property :type object)))
3089       (save-excursion
3090         (cond
3091          ;; cite links
3092          ((-contains? org-ref-cite-types type)
3093           (message (org-ref-get-citation-string-at-point)))
3094
3095          ;; message some context about the label we are referring to
3096          ((string= type "ref")
3097           (message (org-ref-get-label-context
3098                     (org-element-property :path object))))
3099
3100          ((string= type "eqref")
3101           (message (org-ref-get-label-context
3102                     (org-element-property :path object))))
3103
3104          ;; message the count
3105          ((string= type "label")
3106           (let ((count (org-ref-count-labels
3107                         (org-element-property :path object))))
3108             ;; get plurality on occurrence correct
3109             (when (> count 1) (beep))
3110             (message (concat
3111                       (number-to-string count)
3112                       " occurence"
3113                       (when (or (= count 0)
3114                                 (> count 1))
3115                         "s")))))
3116
3117          ;; check if the bibliography files exist.
3118          ((string= type "bibliography")
3119           (let* ((bibfile)
3120                  ;; object is the link you clicked on
3121                  (object (org-element-context))
3122                  (link-string (org-element-property :path object))
3123                  (link-string-beginning)
3124                  (link-string-end))
3125             (save-excursion
3126               (goto-char (org-element-property :begin object))
3127               (search-forward link-string nil nil 1)
3128               (setq link-string-beginning (match-beginning 0))
3129               (setq link-string-end (match-end 0)))
3130
3131              ;; make sure we are in link and not before the :
3132             (when (> link-string-beginning (point))
3133               (goto-char link-string-beginning))
3134
3135             ;; now if we have comma separated bibliographies
3136             ;; we find the one clicked on. we want to
3137             ;; search forward to next comma from point
3138             (save-excursion
3139               (if (search-forward "," link-string-end 1 1)
3140                   (setq key-end (- (match-end 0) 1)) ; we found a match
3141                 (setq key-end (point)))) ; no comma found so take the point
3142
3143             ;; and backward to previous comma from point
3144             (save-excursion
3145               (if (search-backward "," link-string-beginning 1 1)
3146                   (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
3147                 (setq key-beginning (point)))) ; no match found
3148             ;; save the key we clicked on.
3149             (setq bibfile
3150                   (org-ref-strip-string
3151                    (buffer-substring key-beginning key-end)))
3152             (if (file-exists-p bibfile)
3153                 (message "%s exists." bibfile)
3154               (beep)
3155               (message "!!! %s NOT FOUND !!!" bibfile))))
3156          )))))
3157 #+END_SRC
3158
3159 * Aliases
3160 I like convenience. Here are some aliases for faster typing.
3161
3162 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3163 (defalias 'oro 'org-ref-open-citation-at-point)
3164 (defalias 'orc 'org-ref-citation-at-point)
3165 (defalias 'orp 'org-ref-open-pdf-at-point)
3166 (defalias 'oru 'org-ref-open-url-at-point)
3167 (defalias 'orn 'org-ref-open-notes-at-point)
3168 (defalias 'ornr 'org-ref-open-notes-from-reftex)
3169
3170 (defalias 'orib 'org-ref-insert-bibliography-link)
3171 (defalias 'oric 'org-ref-insert-cite-link)
3172 (defalias 'orir 'org-ref-insert-ref-link)
3173 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
3174
3175 (defalias 'orcb 'org-ref-clean-bibtex-entry)
3176 #+END_SRC
3177 * Helm interface
3178 [[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.
3179
3180 1. Make the default action to insert selected keys.
3181 2. Make open entry second action
3182 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3183 (setq helm-source-bibtex
3184       '((name                                      . "BibTeX entries")
3185         (init                                      . helm-bibtex-init)
3186         (candidates                                . helm-bibtex-candidates)
3187         (filtered-candidate-transformer            . helm-bibtex-candidates-formatter)
3188         (action . (("Insert citation"              . helm-bibtex-insert-citation)
3189                    ("Show entry"                   . helm-bibtex-show-entry)
3190                    ("Open PDF file (if present)"   . helm-bibtex-open-pdf)
3191                    ("Open URL or DOI in browser"   . helm-bibtex-open-url-or-doi)
3192                    ("Insert reference"             . helm-bibtex-insert-reference)
3193                    ("Insert BibTeX key"            . helm-bibtex-insert-key)
3194                    ("Insert BibTeX entry"          . helm-bibtex-insert-bibtex)
3195                    ("Attach PDF to email"          . helm-bibtex-add-PDF-attachment)
3196                    ("Edit notes"                   . helm-bibtex-edit-notes)
3197                    ))))
3198 #+END_SRC
3199
3200 Now, let us define a function that inserts the cite links:
3201 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3202 (defun helm-bibtex-format-org-ref (keys)
3203   "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3204 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.
3205
3206 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3207
3208 C-u C-u will change the key at point to the selected keys.
3209 "
3210   (let* ((object (org-element-context))
3211          (last-char (save-excursion
3212                       (goto-char (org-element-property :end object))
3213                       (backward-char)
3214                       (if (looking-at " ")
3215                           " "
3216                         ""))))
3217     (cond
3218      ;; case where we are in a link
3219      ((and (equal (org-element-type object) 'link)
3220            (-contains?
3221             org-ref-cite-types
3222             (org-element-property :type object)))
3223       (cond
3224        ;; no prefix. append keys
3225        ((equal helm-current-prefix-arg nil)
3226         (goto-char (org-element-property :end object))
3227         (while (looking-back " ") (backward-char))
3228         (insert (concat "," (mapconcat 'identity keys ","))))
3229        ;; double prefix, replace key at point
3230        ((equal helm-current-prefix-arg '(16))
3231         (setf (buffer-substring
3232                (org-element-property :begin object)
3233                (org-element-property :end object))
3234               (concat
3235                (replace-regexp-in-string
3236                 (car (org-ref-get-bibtex-key-and-file)) ; key
3237                 (mapconcat 'identity keys ",")          ; new keys
3238                 (org-element-property :raw-link object)
3239                 )
3240                ;; replace space at end to avoid collapsing into next word.
3241                last-char)))
3242        (t
3243         (message "Not found"))))
3244
3245      ;; We are next to a link, and we want to append
3246      ;; next to a link means one character back is on a link.
3247      ((save-excursion
3248         (backward-char)
3249         (and (equal (org-element-type (org-element-context)) 'link)
3250              (-contains?
3251               org-ref-cite-types
3252               (org-element-property :type (org-element-context)))))
3253       (while (looking-back " ") (backward-char))
3254       (insert (concat "," (mapconcat 'identity keys ","))))
3255
3256      ;; insert fresh link
3257      (t
3258       ;;(message-box "fresh link")
3259       (insert
3260        (concat (if (equal helm-current-prefix-arg '(4))
3261                    (helm :sources `((name . "link types")
3262                                     (candidates . ,org-ref-cite-types)
3263                                     (action . (lambda (x) x))))
3264                org-ref-default-citation-link)
3265                ":"
3266                (s-join "," keys))))))
3267   ;; return empty string for helm
3268   "")
3269
3270 (setq helm-bibtex-format-citation-functions
3271       '((org-mode . helm-bibtex-format-org-ref)))
3272
3273 (defun org-ref-helm-insert-cite-link (arg)
3274   "org-ref function to use helm-bibtex to insert a citation link.
3275 With one prefix arg, insert a ref link.
3276 With two prefix args, insert a label link."
3277   (interactive "P")
3278   (cond
3279    ((equal arg nil)
3280      (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3281        (helm-bibtex)))
3282    ((equal arg '(4))
3283     (org-ref-helm-insert-ref-link))
3284    ((equal arg '(16))
3285     (org-ref-helm-insert-label-link))))
3286
3287 (require 'helm-bibtex)
3288
3289 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3290 (setq helm-bibtex-fallback-options
3291       (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3292
3293 (setq helm-bibtex-fallback-options
3294       (-insert-at
3295        1
3296        '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3297        helm-bibtex-fallback-options))
3298
3299 (setq helm-bibtex-fallback-options
3300       (-insert-at 1 '("Open Web of Science" . (lambda () (browse-url "http://apps.webofknowledge.com")))
3301                   helm-bibtex-fallback-options))
3302 #+END_SRC
3303
3304 ** A helm click menu
3305 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.
3306 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3307 (defun org-ref-get-citation-string-at-point ()
3308   "Get a string of a formatted citation"
3309   (interactive)
3310   (let* ((results (org-ref-get-bibtex-key-and-file))
3311          (key (car results))
3312          (bibfile (cdr results)))
3313     (if bibfile
3314         (save-excursion
3315           (with-temp-buffer
3316             (insert-file-contents bibfile)
3317             (bibtex-search-entry key)
3318             (org-ref-bib-citation)))
3319       (beep)
3320       "!!! No entry found !!!" )))
3321
3322 (defun org-ref-cite-candidates ()
3323   "Generate the list of possible candidates for click actions on a cite link.
3324 Checks for pdf and doi, and add appropriate functions."
3325   (interactive)
3326   (let* ((results (org-ref-get-bibtex-key-and-file))
3327          (key (car results))
3328          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3329          (bibfile (cdr results))
3330          (url (save-excursion
3331                 (with-temp-buffer
3332                   (insert-file-contents bibfile)
3333                   (bibtex-search-entry key)
3334                   (bibtex-autokey-get-field "url"))))
3335          (doi (save-excursion
3336                 (with-temp-buffer
3337                   (insert-file-contents bibfile)
3338                   (bibtex-search-entry key)
3339                   ;; I like this better than bibtex-url which does not always find
3340                   ;; the urls
3341                   (bibtex-autokey-get-field "doi"))))
3342          (candidates `(("Quit" . org-ref-citation-at-point)
3343                        ("Open bibtex entry" . org-ref-open-citation-at-point))))
3344     ;; for some reason, when there is no doi or url, they are returned as "". I
3345     ;; prefer nil so we correct this here.
3346     (when (string= doi "") (setq doi nil))
3347     (when (string= url "") (setq url nil))
3348
3349     ;; Conditional pdf functions
3350     (if (file-exists-p pdf-file)
3351         (add-to-list
3352          'candidates
3353          '("Open pdf" . org-ref-open-pdf-at-point)
3354          t)
3355       (add-to-list
3356        'candidates
3357        '("Try to get pdf" . (lambda ()
3358                               (save-window-excursion
3359                                 (org-ref-open-citation-at-point)
3360                                 (bibtex-beginning-of-entry)
3361                                 (doi-utils-get-bibtex-entry-pdf))))
3362        t))
3363
3364
3365     (add-to-list
3366      'candidates
3367      '("Open notes" . org-ref-open-notes-at-point)
3368      t)
3369
3370     ;; conditional url and doi functions
3371     (when (or url doi)
3372       (add-to-list
3373        'candidates
3374        '("Open in browser" . org-ref-open-url-at-point)
3375        t))
3376
3377     (when doi
3378       (mapc (lambda (x)
3379               (add-to-list 'candidates x t))
3380             `(("WOS" . org-ref-wos-at-point)
3381               ("Related articles in WOS" . org-ref-wos-related-at-point)
3382               ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3383               ("Google Scholar" . org-ref-google-scholar-at-point)
3384               ("Pubmed" . org-ref-pubmed-at-point)
3385               ("Crossref" . org-ref-crossref-at-point)
3386               )))
3387
3388     (add-to-list
3389      'candidates
3390      '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3391      t)
3392
3393     (add-to-list
3394      'candidates
3395      '("Copy key to clipboard" . (lambda ()
3396                                   (kill-new
3397                                    (car (org-ref-get-bibtex-key-and-file)))))
3398      t)
3399
3400     (add-to-list
3401      'candidates
3402      '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3403      t)
3404
3405     (add-to-list
3406      'candidates
3407      '("Email bibtex entry and pdf" . (lambda ()
3408                   (save-excursion
3409                     (org-ref-open-citation-at-point)
3410                     (email-bibtex-entry))))
3411      t)
3412   ;; finally return a numbered list of the candidates
3413   (loop for i from 0
3414         for cell in candidates
3415         collect (cons (format "%2s. %s" i (car cell))
3416                       (cdr cell)))))
3417
3418
3419 (defvar org-ref-helm-user-candidates '()
3420   "List of user-defined candidates to act when clicking on a cite link.
3421 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.
3422 ")
3423
3424 ;; example of adding your own function
3425 (add-to-list
3426  'org-ref-helm-user-candidates
3427  '("Example" . (lambda () (message-box "You did it!")))
3428  t)
3429
3430 (defun org-ref-cite-click-helm (key)
3431   "subtle points.
3432 1. get name and candidates before entering helm because we need the org-buffer.
3433 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer."
3434   (interactive)
3435   (let ((name (org-ref-get-citation-string-at-point))
3436         (candidates (org-ref-cite-candidates))
3437         (cb (current-buffer)))
3438
3439     (helm :sources `(((name . ,name)
3440                       (candidates . ,candidates)
3441                       (action . (lambda (f)
3442                                   (switch-to-buffer cb)
3443                                   (funcall f))))
3444                      ((name . "User functions")
3445                       (candidates . ,org-ref-helm-user-candidates)
3446                       (action . (lambda (f)
3447                                   (switch-to-buffer cb)
3448                                   (funcall f))))
3449                      ))))
3450 #+END_SRC
3451
3452 #+RESULTS:
3453 : org-ref-cite-click-helm
3454
3455 * End of code
3456 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3457 (provide 'org-ref)
3458 #+END_SRC
3459
3460 * Build                                                            :noexport:
3461 This code will tangle the elisp code out to org-ref.el and load it.
3462
3463 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
3464
3465 Alternatively you may use:
3466
3467 [[elisp:(org-babel-load-file "org-ref.org")]]