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