]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.org
97d047247574cdef8d8697ad4fcbd5c9c28c55f9
[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.
42 ;; also sets up reftex for org-mode. The links are clickable and do
43 ;; things that are useful. You should really read org-ref.org for details.
44 ;;
45 ;; Package-Requires: ((dash))
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 #+END_SRC
55
56 ** Custom variables
57 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.
58
59 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
60 (defgroup org-ref nil
61   "customization group for org-ref")
62
63 (defcustom org-ref-bibliography-notes
64   nil
65   "filename to where you will put all your notes about an entry in
66   the default bibliography."
67   :type 'file
68   :group 'org-ref)
69
70 (defcustom org-ref-default-bibliography
71   nil
72   "list of bibtex files to search for. You should use full-paths for each file."
73   :type '(repeat :tag "List of bibtex files" file)
74   :group 'org-ref)
75
76 (defcustom org-ref-pdf-directory
77   nil
78   "directory where pdfs are stored by key. put a trailing / in"
79   :type 'directory
80   :group 'org-ref)
81
82 (defcustom org-ref-default-citation-link
83   "cite"
84   "The default type of citation link to use"
85   :type 'string
86   :group 'org-ref)
87
88 (defcustom org-ref-insert-cite-key
89   "C-c ]"
90   "Keyboard shortcut to insert a citation."
91   :type 'string
92   :group 'org-ref)
93
94 (defcustom org-ref-bibliography-entry-format
95   '(("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>.")
96
97     ("book" . "%a, %t, %u (%y).")
98
99     ("proceedings" . "%e, %t in %S, %u (%y).")
100
101     ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
102
103   "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."
104   :type 'string
105   :group 'org-ref)
106 #+END_SRC
107
108 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.
109
110 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
111 (defcustom org-ref-cite-types
112   '("cite" "nocite" ;; the default latex cite commands
113     ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
114     "citet" "citet*" "citep" "citep*"
115     "citealt" "citealt*" "citealp" "citealp*"
116     "citenum" "citetext"
117     "citeauthor" "citeauthor*"
118     "citeyear" "citeyear*"
119     "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
120     ;; biblatex commands
121     ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
122     "Cite"
123     "parencite" "Parencite"
124     "footcite" "footcitetext"
125     "textcite" "Textcite"
126     "smartcite" "Smartcite"
127     "cite*" "parencite*" "supercite"
128     "autocite" "Autocite" "autocite*" "Autocite*"
129     "Citeauthor*"
130     "citetitle" "citetitle*"
131     "citedate" "citedate*"
132     "citeurl"
133     "fullcite" "footfullcite"
134     ;; "volcite" "Volcite" cannot support the syntax
135     "notecite" "Notecite"
136     "pnotecite" "Pnotecite"
137     "fnotecite"
138     ;; multicites. Very limited support for these.
139     "cites" "Cites" "parencites" "Parencites"
140     "footcites" "footcitetexts"
141     "smartcites" "Smartcites" "textcites" "Textcites"
142     "supercites" "autocites" "Autocites"
143     )
144   "List of citation types known in org-ref"
145   :type '(repeat :tag "List of citation types" string)
146   :group 'org-ref)
147 #+END_SRC
148
149 We need a hook variable to store user-defined bibtex entry cleaning functions
150 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
151 (defcustom org-ref-clean-bibtex-entry-hook nil
152   "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
153   :group 'org-ref
154   :type 'hook)
155 #+END_SRC
156
157 ** Program variables
158 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
159 (defvar org-ref-bibliography-files
160   nil
161   "variable to hold bibliography files to be searched")
162 #+END_SRC
163
164 ** org-mode / reftex setup
165
166 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.
167
168 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
169 (defun org-mode-reftex-setup ()
170     (load-library "reftex")
171     (and (buffer-file-name)
172          (file-exists-p (buffer-file-name))
173          (global-auto-revert-mode t)
174          (reftex-parse-all))
175     (make-local-variable 'reftex-cite-format)
176     (setq reftex-cite-format 'org)
177     (define-key org-mode-map (kbd org-ref-insert-cite-key) 'org-ref-insert-cite-link))
178
179 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
180
181 (eval-after-load 'reftex-vars
182   '(progn
183       (add-to-list 'reftex-cite-format-builtin
184                    '(org "Org-mode citation"
185                          ((?\C-m . "cite:%l")     ; default
186                           (?d . ",%l")            ; for appending
187                           (?a . "autocite:%l")
188                           (?t . "citet:%l")
189                           (?T . "citet*:%l")
190                           (?p . "citep:%l")
191                           (?P . "citep*:%l")
192                           (?h . "citeauthor:%l")
193                           (?H . "citeauthor*:%l")
194                           (?y . "citeyear:%l")
195                           (?x . "citetext:%l")
196                           (?n . "nocite:%l")
197                           )))))
198 #+END_SRC
199
200 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. 
201
202 #+BEGIN_SRC emacs-lisp :tangle no
203 ;; add new format
204 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
205       (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W  . "textcite:%l")
206             (?z  . "newcite:%l"))))
207 #+END_SRC
208
209 You can define a new citation link like this:
210 #+BEGIN_SRC emacs-lisp :tangle no
211 (org-ref-define-citation-link "citez" ?z)
212 #+END_SRC
213
214 * Links
215 Most of this library is the creation of functional links to help with references and citations.
216 ** General utilities
217 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.
218
219 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
220 (defun org-ref-strip-string (string)
221   "strip leading and trailing whitespace from the string"
222   (replace-regexp-in-string
223    (concat search-whitespace-regexp "$" ) ""
224    (replace-regexp-in-string
225     (concat "^" search-whitespace-regexp ) "" string)))
226 #+END_SRC
227
228 It is helpful to make the previous function operate on a list of strings here.
229
230 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
231 (defun org-ref-split-and-strip-string (string)
232   "split key-string and strip keys. Assumes the key-string is comma delimited"
233   (mapcar 'org-ref-strip-string (split-string string ",")))
234 #+END_SRC
235
236 ** bibliography and bibliographystyle
237 *** An html bibliography
238
239 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.
240
241 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
242 (defun org-ref-reftex-get-bib-field (field entry &optional format)
243   "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
244   (let ((result))
245     (setq result (reftex-get-bib-field field entry format))
246     (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
247       (setq result (substring result 1 -1)))
248     (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
249       (setq result (substring result 1 -1)))    
250       result))
251
252 (defun org-ref-reftex-format-citation (entry format)
253   "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
254 to the format argument. The format is a string with these percent escapes.
255
256 In the format, the following percent escapes will be expanded.
257
258 %l   The BibTeX label of the citation.
259 %a   List of author names, see also `reftex-cite-punctuation'.
260 %2a  Like %a, but abbreviate more than 2 authors like Jones et al.
261 %A   First author name only.
262 %e   Works like %a, but on list of editor names. (%2e and %E work a well)
263
264 It is also possible to access all other BibTeX database fields:
265 %b booktitle     %c chapter        %d edition    %h howpublished
266 %i institution   %j journal        %k key        %m month
267 %n number        %o organization   %p pages      %P first page
268 %r address       %s school         %u publisher  %t title
269 %v volume        %y year
270 %B booktitle, abbreviated          %T title, abbreviated
271 %U url
272 %D doi
273 %S series
274
275 Usually, only %l is needed.  The other stuff is mainly for the echo area
276 display, and for (setq reftex-comment-citations t).
277
278 %< as a special operator kills punctuation and space around it after the
279 string has been formatted.
280
281 A pair of square brackets indicates an optional argument, and RefTeX
282 will prompt for the values of these arguments.
283
284 Beware that all this only works with BibTeX database files.  When
285 citations are made from the \bibitems in an explicit thebibliography
286 environment, only %l is available."
287   ;; Format a citation from the info in the BibTeX ENTRY
288
289   (unless (stringp format) (setq format "\\cite{%l}"))
290
291   (if (and reftex-comment-citations
292            (string-match "%l" reftex-cite-comment-format))
293       (error "reftex-cite-comment-format contains invalid %%l"))
294
295   (while (string-match
296           "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
297           format)
298     (let ((n (string-to-number (match-string 4 format)))
299           (l (string-to-char (match-string 5 format)))
300           rpl b e)
301       (save-match-data
302         (setq rpl
303               (cond
304                ((= l ?l) (concat
305                           (org-ref-reftex-get-bib-field "&key" entry)
306                           (if reftex-comment-citations
307                               reftex-cite-comment-format
308                             "")))
309                ((= l ?a) (reftex-format-names
310                           (reftex-get-bib-names "author" entry)
311                           (or n 2)))
312                ((= l ?A) (car (reftex-get-bib-names "author" entry)))
313                ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
314                ((= l ?B) (reftex-abbreviate-title
315                           (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
316                ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
317                ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
318                ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
319                ((= l ?e) (reftex-format-names
320                           (reftex-get-bib-names "editor" entry)
321                           (or n 2)))
322                ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
323                ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
324                ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
325                ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
326                ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
327                ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
328                ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
329                ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
330                ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
331                ((= l ?P) (car (split-string
332                                (org-ref-reftex-get-bib-field "pages" entry)
333                                "[- .]+")))
334                ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
335                ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
336                ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
337                ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
338                ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
339                ;; strip enclosing brackets from title if they are there
340                ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
341                ((= l ?T) (reftex-abbreviate-title
342                           (org-ref-reftex-get-bib-field "title" entry)))
343                ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
344                ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
345
346       (if (string= rpl "")
347           (setq b (match-beginning 2) e (match-end 2))
348         (setq b (match-beginning 3) e (match-end 3)))
349       (setq format (concat (substring format 0 b) rpl (substring format e)))))
350   (while (string-match "%%" format)
351     (setq format (replace-match "%" t t format)))
352   (while (string-match "[ ,.;:]*%<" format)
353     (setq format (replace-match "" t t format)))
354   ;; also replace carriage returns, tabs, and multiple whitespaces
355   (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
356   format)
357
358 (defun org-ref-get-bibtex-entry-citation (key)
359   "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
360
361   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
362         (file) (entry) (bibtex-entry) (entry-type) (format))
363
364     (setq file (catch 'result
365                  (loop for file in org-ref-bibliography-files do
366                        (if (org-ref-key-in-file-p key (file-truename file)) 
367                            (throw 'result file)
368                          (message "%s not found in %s" key (file-truename file))))))
369
370     (with-temp-buffer
371       (insert-file-contents file)
372       (bibtex-search-entry key nil 0)
373       (setq bibtex-entry (bibtex-parse-entry))
374       (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
375       (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
376       (if format
377           (setq entry  (org-ref-reftex-format-citation bibtex-entry format))
378         (save-restriction
379           (bibtex-narrow-to-entry)
380           (setq entry (buffer-string)))))      
381     entry))
382 #+END_SRC
383
384 #+RESULTS:
385 : org-ref-reftex-format-citation
386
387 Here is how to use the function. You call it with point in an entry in a bibtex file.
388
389 #+BEGIN_SRC emacs-lisp :tangle no
390 (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>."))
391   (org-ref-get-bibtex-entry-citation  "armiento-2014-high"))
392 #+END_SRC
393 #+RESULTS:
394 : 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>.
395
396 I am not sure why full author names are not used.
397
398 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
399
400 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
401 (defun org-ref-get-bibtex-keys ()
402   "return a list of unique keys in the buffer."
403   (let ((keys '()))
404     (org-element-map (org-element-parse-buffer) 'link
405       (lambda (link)       
406         (let ((plist (nth 1 link)))                          
407           (when (-contains? org-ref-cite-types (plist-get plist ':type))
408             (dolist 
409                 (key 
410                  (org-ref-split-and-strip-string (plist-get plist ':path)))
411               (when (not (-contains? keys key))
412                 (setq keys (append keys (list key)))))))))
413     ;; Sort keys alphabetically
414     (setq keys (cl-sort keys 'string-lessp :key 'downcase))
415     keys))
416 #+END_SRC
417
418 This function gets the html for one entry.
419
420 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
421 (defun org-ref-get-bibtex-entry-html (key)
422   "returns an html string for the bibliography entry corresponding to key"
423
424   (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
425 #+END_SRC
426
427 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
428
429 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
430 (defun org-ref-get-html-bibliography ()
431   "Create an html bibliography when there are keys"
432   (let ((keys (org-ref-get-bibtex-keys)))
433     (when keys
434       (concat "<h1>Bibliography</h1>
435 <ul>"
436               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
437               "\n</ul>"))))
438 #+END_SRC
439
440 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.
441
442 *** An org bibliography
443 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.
444
445 First, we get the string for a single entry.
446 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
447 (defun org-ref-get-bibtex-entry-org (key)
448   "returns an org string for the bibliography entry corresponding to key"
449   (let ((org-ref-bibliography-files (org-ref-find-bibliography))
450         (file) (entry) (bibtex-entry) (entry-type) (format))
451
452     (setq file (catch 'result
453                  (loop for file in org-ref-bibliography-files do
454                        (if (org-ref-key-in-file-p key (file-truename file)) 
455                            (throw 'result file)
456                          (message "%s not found in %s" key (file-truename file))))))
457
458     (with-temp-buffer
459       (insert-file-contents file)
460       (bibtex-search-entry key nil 0)
461       (setq entry (bibtex-parse-entry))
462       (format "** %s - %s
463   :PROPERTIES:
464   %s
465   :END:
466 " (org-ref-reftex-get-bib-field "author" entry)
467 (org-ref-reftex-get-bib-field "title" entry)
468 (concat "   :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
469         (mapconcat (lambda (element) (format "   :%s: %s"
470                                              (upcase (car element))
471                                              (cdr element)))
472                    entry
473                    "\n"))))))
474 #+END_SRC
475
476 Now, we loop over the keys, and combine all the entries into a bibliography.
477 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
478 (defun org-ref-get-org-bibliography ()
479   "Create an org bibliography when there are keys"
480   (let ((keys (org-ref-get-bibtex-keys)))
481     (when keys
482       (concat "* Bibliography
483 "
484               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
485               "\n"))))
486 #+END_SRC
487
488 *** An ascii bibliography
489
490 This function gets the html for one entry.
491
492 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
493 (defun org-ref-get-bibtex-entry-ascii (key)
494   "returns an ascii string for the bibliography entry corresponding to key"
495
496   (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
497 #+END_SRC
498
499 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
500
501 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
502 (defun org-ref-get-ascii-bibliography ()
503   "Create an html bibliography when there are keys"
504   (let ((keys (org-ref-get-bibtex-keys)))
505     (when keys
506       (concat 
507 "Bibliography
508 =============
509 "
510               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
511               "\n"))))
512 #+END_SRC
513
514
515 *** the links
516 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.
517
518 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
519 (org-add-link-type "bibliography"
520                    ;; this code is run on clicking. The bibliography
521                    ;; may contain multiple files. this code finds the
522                    ;; one you clicked on and opens it.
523                    (lambda (link-string)        
524                        ;; get link-string boundaries
525                        ;; we have to go to the beginning of the line, and then search forward
526                        
527                      (let* ((bibfile)
528                             ;; object is the link you clicked on
529                             (object (org-element-context))
530  
531                             (link-string-beginning) 
532                             (link-string-end))
533
534                      (save-excursion
535                        (goto-char (org-element-property :begin object))
536                        (search-forward link-string nil nil 1)
537                        (setq link-string-beginning (match-beginning 0))
538                        (setq link-string-end (match-end 0)))
539
540                        ;; We set the reftex-default-bibliography
541                        ;; here. it should be a local variable only in
542                        ;; the current buffer. We need this for using
543                        ;; reftex to do citations.
544                        (set (make-local-variable 'reftex-default-bibliography) 
545                             (split-string (org-element-property :path object) ","))
546
547                        ;; now if we have comma separated bibliographies
548                        ;; we find the one clicked on. we want to
549                        ;; search forward to next comma from point
550                        (save-excursion
551                          (if (search-forward "," link-string-end 1 1)
552                              (setq key-end (- (match-end 0) 1)) ; we found a match
553                            (setq key-end (point)))) ; no comma found so take the point
554                        ;; and backward to previous comma from point
555                        (save-excursion
556                          (if (search-backward "," link-string-beginning 1 1)
557                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
558                            (setq key-beginning (point)))) ; no match found
559                        ;; save the key we clicked on.
560                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
561                        (find-file bibfile))) ; open file on click
562
563                      ;; formatting code
564                    (lambda (keyword desc format)
565                      (cond
566                       ((eq format 'org) (org-ref-get-org-bibliography))
567                       ((eq format 'ascii) (org-ref-get-ascii-bibliography))
568                       ((eq format 'html) (org-ref-get-html-bibliography))
569                       ((eq format 'latex)
570                          ;; write out the latex bibliography command
571                        (format "\\bibliography{%s}" (replace-regexp-in-string  "\\.bib" "" (expand-file-name keyword)))))))
572 #+END_SRC
573
574 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
575 (org-add-link-type "printbibliography"
576                    (lambda (arg) (message "Nothing implemented for clicking here."))
577                    (lambda (keyword desc format)
578                      (cond
579                       ((eq format 'org) (org-ref-get-org-bibliography))
580                       ((eq format 'html) (org-ref-get-html-bibliography))
581                       ((eq format 'latex)
582                        ;; write out the biblatex bibliography command
583                        "\\printbibliography"))
584 ))
585 #+END_SRC
586
587 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, ...
588
589 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
590 (org-add-link-type "bibliographystyle"
591                    (lambda (arg) (message "Nothing implemented for clicking here."))
592                    (lambda (keyword desc format)
593                      (cond
594                       ((eq format 'latex)
595                        ;; write out the latex bibliography command
596                        (format "\\bibliographystyle{%s}" keyword)))))
597 #+END_SRC
598
599 *** Completion for bibliography link
600 It would be nice 
601
602 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
603 (defun org-bibliography-complete-link (&optional arg)
604  (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
605
606 (defun org-ref-insert-bibliography-link ()
607   "insert a bibliography with completion"
608   (interactive)
609   (insert (org-bibliography-complete-link)))
610 #+END_SRC
611
612 ** addbibresource
613 This is apparently used for biblatex.
614 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
615 (org-add-link-type "addbibresource"
616                    ;; this code is run on clicking. The addbibresource
617                    ;; may contain multiple files. this code finds the
618                    ;; one you clicked on and opens it.
619                    (lambda (link-string)        
620                        ;; get link-string boundaries
621                        ;; we have to go to the beginning of the line, and then search forward
622                        
623                      (let* ((bibfile)
624                             ;; object is the link you clicked on
625                             (object (org-element-context))
626  
627                             (link-string-beginning) 
628                             (link-string-end))
629
630                      (save-excursion
631                        (goto-char (org-element-property :begin object))
632                        (search-forward link-string nil nil 1)
633                        (setq link-string-beginning (match-beginning 0))
634                        (setq link-string-end (match-end 0)))
635
636                        ;; We set the reftex-default-addbibresource
637                        ;; here. it should be a local variable only in
638                        ;; the current buffer. We need this for using
639                        ;; reftex to do citations.
640                        (set (make-local-variable 'reftex-default-addbibresource) 
641                             (split-string (org-element-property :path object) ","))
642
643                        ;; now if we have comma separated bibliographies
644                        ;; we find the one clicked on. we want to
645                        ;; search forward to next comma from point
646                        (save-excursion
647                          (if (search-forward "," link-string-end 1 1)
648                              (setq key-end (- (match-end 0) 1)) ; we found a match
649                            (setq key-end (point)))) ; no comma found so take the point
650                        ;; and backward to previous comma from point
651                        (save-excursion
652                          (if (search-backward "," link-string-beginning 1 1)
653                              (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
654                            (setq key-beginning (point)))) ; no match found
655                        ;; save the key we clicked on.
656                        (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
657                        (find-file bibfile))) ; open file on click
658
659                      ;; formatting code
660                    (lambda (keyword desc format)
661                      (cond
662                       ((eq format 'html) (format "")); no output for html
663                       ((eq format 'latex)
664                          ;; write out the latex addbibresource command
665                        (format "\\addbibresource{%s}" keyword)))))
666 #+END_SRC
667
668 ** List of Figures
669
670 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.
671
672 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
673 (defun org-ref-list-of-figures (&optional arg)
674   "Generate buffer with list of figures in them"
675   (interactive)
676   (save-excursion (widen)
677   (let* ((c-b (buffer-name))
678          (counter 0)
679          (list-of-figures 
680           (org-element-map (org-element-parse-buffer) 'link
681             (lambda (link) 
682               "create a link for to the figure"
683               (when 
684                   (and (string= (org-element-property :type link) "file")
685                        (string-match-p  
686                         "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
687                         (org-element-property :path link)))                   
688                 (incf counter)
689                 
690                 (let* ((start (org-element-property :begin link))
691                        (parent (car (cdr (org-element-property :parent link))))
692                        (caption (caaar (plist-get parent :caption)))
693                        (name (plist-get parent :name)))
694                   (if caption 
695                       (format 
696                        "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n" 
697                        c-b start counter (or name "") caption)
698                     (format 
699                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n" 
700                      c-b start counter (or name "")))))))))
701     (switch-to-buffer "*List of Figures*")
702     (setq buffer-read-only nil)
703     (org-mode)
704     (erase-buffer)
705     (insert (mapconcat 'identity list-of-figures ""))
706     (setq buffer-read-only t)
707     (use-local-map (copy-keymap org-mode-map))
708     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
709
710 (org-add-link-type 
711  "list-of-figures"
712  'org-ref-list-of-figures ; on click
713  (lambda (keyword desc format)
714    (cond
715     ((eq format 'latex)
716      (format "\\listoffigures")))))
717 #+END_SRC
718
719 ** List of Tables
720
721 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
722 (defun org-ref-list-of-tables (&optional arg)
723   "Generate a buffer with a list of tables"
724   (interactive)
725   (save-excursion
726   (widen)
727   (let* ((c-b (buffer-name))
728          (counter 0)
729          (list-of-tables 
730           (org-element-map (org-element-parse-buffer 'element) 'table
731             (lambda (table) 
732               "create a link for to the table"
733               (incf counter)
734               (let ((start (org-element-property :begin table))
735                     (name  (org-element-property :name table))
736                     (caption (caaar (org-element-property :caption table))))
737                 (if caption 
738                     (format 
739                      "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n" 
740                      c-b start counter (or name "") caption)
741                   (format 
742                    "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n" 
743                    c-b start counter (or name ""))))))))
744     (switch-to-buffer "*List of Tables*")
745     (setq buffer-read-only nil)
746     (org-mode)
747     (erase-buffer)
748     (insert (mapconcat 'identity list-of-tables ""))
749     (setq buffer-read-only t)
750     (use-local-map (copy-keymap org-mode-map))
751     (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
752
753 (org-add-link-type 
754  "list-of-tables"
755  'org-ref-list-of-tables
756  (lambda (keyword desc format)
757    (cond
758     ((eq format 'latex)
759      (format "\\listoftables")))))
760 #+END_SRC
761 ** label
762
763 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.
764 *************** TODO search tblnames, custom_ids and check for case sensitivity
765 *************** END
766
767 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
768 (org-add-link-type
769  "label"
770  (lambda (label)
771    "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
772    (message (format "%s occurences"
773                     (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
774                        ;; for tblname, it is not enough to get word boundary
775                        ;; tab-little and tab-little-2 match then.
776                        (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
777                        (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
778                        ;; this is the org-format #+label:
779                        (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))))
780  (lambda (keyword desc format)
781    (cond
782     ((eq format 'html) (format "(<label>%s</label>)" path))
783     ((eq format 'latex)
784      (format "\\label{%s}" keyword)))))
785 #+END_SRC
786
787 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.
788
789 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
790 (defun org-label-store-link ()
791   "store a link to a label. The output will be a ref to that label"
792   ;; First we have to make sure we are on a label link. 
793   (let* ((object (org-element-context)))
794     (when (and (equal (org-element-type object) 'link) 
795                (equal (org-element-property :type object) "label"))
796       (org-store-link-props
797        :type "ref"
798        :link (concat "ref:" (org-element-property :path object))))
799
800     ;; Store link on table
801     (when (equal (org-element-type object) 'table)
802       (org-store-link-props
803        :type "ref"
804        :link (concat "ref:" (org-element-property :name object))))
805
806 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
807     ;; store link on heading with custom_id
808 ;    (when (and (equal (org-element-type object) 'headline)
809 ;              (org-entry-get (point) "CUSTOM_ID"))
810 ;      (org-store-link-props
811 ;       :type "ref"
812 ;       :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
813
814     ;; and to #+label: lines
815     (when (and (equal (org-element-type object) 'paragraph)
816                (org-element-property :name object))
817       (org-store-link-props
818        :type "ref"
819        :link (concat "ref:" (org-element-property :name object))))
820 ))
821
822 (add-hook 'org-store-link-functions 'org-label-store-link)
823 #+END_SRC
824 ** ref
825
826 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. 
827
828 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
829
830 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
831 (org-add-link-type
832  "ref"
833  (lambda (label)
834    "on clicking goto the label. Navigate back with C-c &"
835    (org-mark-ring-push)
836    ;; next search from beginning of the buffer
837
838    ;; it is possible you would not find the label if narrowing is in effect
839    (widen)
840
841    (unless
842        (or
843         ;; our label links
844         (progn 
845           (goto-char (point-min))
846           (re-search-forward (format "label:%s\\b" label) nil t))
847
848         ;; a latex label
849         (progn
850           (goto-char (point-min))
851           (re-search-forward (format "\\label{%s}" label) nil t))
852
853         ;; #+label: name  org-definition
854         (progn
855           (goto-char (point-min))
856           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
857         
858         ;; org tblname
859         (progn
860           (goto-char (point-min))
861           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
862
863 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
864 ;; you need [[#label]] links.
865         ;; CUSTOM_ID
866 ;       (progn
867 ;         (goto-char (point-min))
868 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
869         )
870      ;; we did not find anything, so go back to where we came
871      (org-mark-ring-goto)
872      (error "%s not found" label))
873    (message "go back with (org-mark-ring-goto) `C-c &`"))
874  ;formatting
875  (lambda (keyword desc format)
876    (cond
877     ((eq format 'html) (format "(<ref>%s</ref>)" path))
878     ((eq format 'latex)
879      (format "\\ref{%s}" keyword)))))
880 #+END_SRC
881
882 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 labels, custom_ids, and table names as potential items to make a ref link to.
883
884 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
885 (defun org-ref-get-custom-ids ()
886  "return a list of custom_id properties in the buffer"
887  (let ((results '()) custom_id)
888    (org-map-entries 
889     (lambda () 
890       (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
891         (when (not (null custom_id))
892           (setq results (append results (list custom_id)))))))
893 results))
894 #+END_SRC
895
896 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
897 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
898 (defun org-ref-get-latex-labels ()
899 (save-excursion
900     (goto-char (point-min))
901     (let ((matches '()))
902       (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
903         (add-to-list 'matches (match-string-no-properties 1) t))
904 matches)))
905 #+END_SRC
906
907 Finally, we get the table names.
908
909 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
910 (defun org-ref-get-tblnames ()
911   (org-element-map (org-element-parse-buffer 'element) 'table
912     (lambda (table) 
913       (org-element-property :name table))))
914 #+END_SRC
915
916 Now, we can put all the labels together which will give us a list of candidates.
917
918 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
919 (defun org-ref-get-labels ()
920   "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
921   (save-excursion
922     (save-restriction
923       (widen)
924       (goto-char (point-min))
925       (let ((matches '()))
926         (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
927           (add-to-list 'matches (match-string-no-properties 1) t))
928         (append matches (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
929 #+END_SRC
930
931 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.
932
933 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
934 (defun org-ref-complete-link (&optional arg)
935   "Completion function for ref links"
936   (let ((label))
937     (setq label (completing-read "label: " (org-ref-get-labels)))
938     (format "ref:%s" label)))
939 #+END_SRC
940
941 Alternatively, you may want to just call a function that inserts a link with completion:
942
943 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
944 (defun org-ref-insert-ref-link ()
945  (interactive)
946  (insert (org-ref-complete-link)))
947 #+END_SRC
948
949 ** pageref
950
951 This refers to the page of a label in LaTeX.
952
953 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
954 (org-add-link-type
955  "pageref"
956  (lambda (label)
957    "on clicking goto the label. Navigate back with C-c &"
958    (org-mark-ring-push)
959    ;; next search from beginning of the buffer
960    (widen)
961    (unless
962        (or
963         ;; our label links
964         (progn 
965           (goto-char (point-min))
966           (re-search-forward (format "label:%s\\b" label) nil t))
967
968         ;; a latex label
969         (progn
970           (goto-char (point-min))
971           (re-search-forward (format "\\label{%s}" label) nil t))
972
973         ;; #+label: name  org-definition
974         (progn
975           (goto-char (point-min))
976           (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
977         
978         ;; org tblname
979         (progn
980           (goto-char (point-min))
981           (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
982
983 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
984 ;; you need [[#label]] links.
985         ;; CUSTOM_ID
986 ;       (progn
987 ;         (goto-char (point-min))
988 ;         (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
989         )
990      ;; we did not find anything, so go back to where we came
991      (org-mark-ring-goto)
992      (error "%s not found" label))
993    (message "go back with (org-mark-ring-goto) `C-c &`"))
994  ;formatting
995  (lambda (keyword desc format)
996    (cond
997     ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
998     ((eq format 'latex)
999      (format "\\pageref{%s}" keyword)))))
1000 #+END_SRC
1001
1002 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1003 (defun org-pageref-complete-link (&optional arg)
1004   "Completion function for ref links"
1005   (let ((label))
1006     (setq label (completing-read "label: " (org-ref-get-labels)))
1007     (format "ref:%s" label)))
1008 #+END_SRC
1009
1010 Alternatively, you may want to just call a function that inserts a link with completion:
1011
1012 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1013 (defun org-pageref-insert-ref-link ()
1014  (interactive)
1015  (insert (org-pageref-complete-link)))
1016 #+END_SRC
1017
1018 ** nameref
1019
1020 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.
1021
1022 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1023 (org-add-link-type
1024  "nameref"
1025  (lambda (label)
1026    "on clicking goto the label. Navigate back with C-c &"
1027    (org-mark-ring-push)
1028    ;; next search from beginning of the buffer
1029    (widen)
1030    (unless
1031        (or
1032         ;; a latex label
1033         (progn
1034           (goto-char (point-min))
1035           (re-search-forward (format "\\label{%s}" label) nil t))
1036         )
1037      ;; we did not find anything, so go back to where we came
1038      (org-mark-ring-goto)
1039      (error "%s not found" label))
1040    (message "go back with (org-mark-ring-goto) `C-c &`"))
1041  ;formatting
1042  (lambda (keyword desc format)
1043    (cond
1044     ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1045     ((eq format 'latex)
1046      (format "\\nameref{%s}" keyword)))))
1047 #+END_SRC
1048
1049 ** eqref
1050 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1051  
1052 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1053 (org-add-link-type
1054  "eqref"
1055  (lambda (label)
1056    "on clicking goto the label. Navigate back with C-c &"
1057    (org-mark-ring-push)
1058    ;; next search from beginning of the buffer
1059    (widen)
1060    (goto-char (point-min))
1061    (unless
1062        (or
1063         ;; search forward for the first match
1064         ;; our label links
1065         (re-search-forward (format "label:%s" label) nil t)
1066         ;; a latex label
1067         (re-search-forward (format "\\label{%s}" label) nil t)
1068         ;; #+label: name  org-definition
1069         (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1070      (org-mark-ring-goto)
1071      (error "%s not found" label))
1072    (message "go back with (org-mark-ring-goto) `C-c &`"))
1073  ;formatting
1074  (lambda (keyword desc format)
1075    (cond
1076     ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1077     ((eq format 'latex)
1078      (format "\\eqref{%s}" keyword)))))
1079 #+END_SRC
1080
1081
1082 ** cite
1083 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.
1084
1085 *** Implementing the click actions of cite
1086
1087 **** Getting the key we clicked on
1088 The first thing we need is to get the bibtex key we clicked on.
1089
1090 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1091 (defun org-ref-get-bibtex-key-under-cursor ()
1092   "returns key under the bibtex cursor. We search forward from
1093 point to get a comma, or the end of the link, and then backwards
1094 to get a comma, or the beginning of the link. that delimits the
1095 keyword we clicked on. We also strip the text properties."
1096   (interactive)
1097   (let* ((object (org-element-context))  
1098          (link-string (org-element-property :path object)))
1099
1100     (if (not (org-element-property :contents-begin object))
1101         ;; this means no description in the link
1102         (progn    
1103           ;; we need the link path start and end
1104           (save-excursion
1105             (goto-char (org-element-property :begin object))
1106             (search-forward link-string nil nil 1)
1107             (setq link-string-beginning (match-beginning 0))
1108             (setq link-string-end (match-end 0)))
1109
1110           ;; The key is the text between commas, or the link boundaries
1111           (save-excursion
1112             (if (search-forward "," link-string-end t 1)
1113                 (setq key-end (- (match-end 0) 1)) ; we found a match
1114               (setq key-end link-string-end))) ; no comma found so take the end
1115           ;; and backward to previous comma from point which defines the start character
1116           (save-excursion
1117             (if (search-backward "," link-string-beginning 1 1)
1118                 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1119               (setq key-beginning link-string-beginning))) ; no match found
1120           ;; save the key we clicked on.
1121           (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1122           (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1123           bibtex-key)
1124       ;; link with description. assume only one key
1125       link-string)))
1126 #+END_SRC
1127
1128 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.
1129
1130 **** Getting the bibliographies
1131 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1132 (defun org-ref-find-bibliography ()
1133   "find the bibliography in the buffer.
1134 This function sets and returns cite-bibliography-files, which is a list of files
1135 either from bibliography:f1.bib,f2.bib
1136 \bibliography{f1,f2}
1137 internal bibliographies
1138
1139 falling back to what the user has set in org-ref-default-bibliography
1140 "
1141   (interactive)
1142   (catch 'result
1143     (save-excursion
1144       (goto-char (point-min))
1145       ;;  look for a bibliography link
1146       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1147         (setq org-ref-bibliography-files
1148               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1149         (throw 'result org-ref-bibliography-files))
1150
1151       
1152       ;; we did not find a bibliography link. now look for \bibliography
1153       (goto-char (point-min))
1154       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1155         ;; split, and add .bib to each file
1156         (setq org-ref-bibliography-files
1157               (mapcar (lambda (x) (concat x ".bib"))
1158                       (mapcar 'org-ref-strip-string 
1159                               (split-string (match-string 1) ","))))
1160         (throw 'result org-ref-bibliography-files))
1161
1162       ;; no bibliography found. maybe we need a biblatex addbibresource
1163       (goto-char (point-min))
1164       ;;  look for a bibliography link
1165       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1166         (setq org-ref-bibliography-files
1167               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1168         (throw 'result org-ref-bibliography-files))
1169           
1170       ;; we did not find anything. use defaults
1171       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1172
1173     ;; set reftex-default-bibliography so we can search
1174     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1175     org-ref-bibliography-files)
1176 #+END_SRC
1177
1178 **** Finding the bibliography file a key is in
1179 Now, we can see if an entry is in a file. 
1180
1181 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1182 (defun org-ref-key-in-file-p (key filename)
1183   "determine if the key is in the file"
1184   (interactive "skey: \nsFile: ")
1185   (save-current-buffer
1186     (let ((bibtex-files (list filename)))
1187       (bibtex-search-entry key t))))
1188 #+END_SRC
1189
1190 Finally, we want to know which file the key is in.
1191
1192 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1193 (defun org-ref-get-bibtex-key-and-file (&optional key)
1194   "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1195  (interactive)
1196  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1197        (file))
1198    (unless key
1199      (setq key (org-ref-get-bibtex-key-under-cursor)))
1200    (setq file     (catch 'result
1201                     (loop for file in org-ref-bibliography-files do
1202                           (if (org-ref-key-in-file-p key (file-truename file)) 
1203                               (throw 'result file)))))
1204    (cons key file)))
1205 #+END_SRC
1206
1207 **** Creating the menu for when we click on a key
1208      :PROPERTIES:
1209      :ID:       d7b7530b-802f-42b1-b61e-1e77da33e278
1210      :END:
1211 When we click on a cite link, we want to get a menu in the minibuffer. We need to create a string for this. We want a citation, and some options that depend on the key. We want to know if the key is found, if there is a pdf, if etc... Here we create that string.
1212
1213 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1214 (defun org-ref-get-menu-options ()
1215   "returns a dynamically determined string of options for the citation under point.
1216
1217 we check to see if there is pdf, and if the key actually exists in the bibliography"
1218   (interactive)
1219   (let* ((results (org-ref-get-bibtex-key-and-file))
1220          (key (car results))
1221          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1222          (bibfile (cdr results))
1223          m1 m2 m3 m4 m5 menu-string)
1224     (setq m1 (if bibfile                 
1225                  "(o)pen"
1226                "(No key found)"))
1227
1228     (setq m3 (if (file-exists-p pdf-file)
1229                  "(p)df"
1230                      "(No pdf found)"))
1231
1232     (setq m4 (if (not
1233                   (and bibfile
1234                        (string= (catch 'url
1235                                   (progn
1236
1237                                     (with-temp-buffer
1238                                       (insert-file-contents bibfile)
1239                                       (bibtex-search-entry key)
1240                                       (when (not
1241                                              (string= (setq url (bibtex-autokey-get-field "url")) ""))
1242                                         (throw 'url url))
1243
1244                                       (when (not
1245                                              (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1246                                         (throw 'url url))))) "")))
1247                "(u)rl" "(no url found)"))
1248     (setq m5 "(n)otes")
1249     (setq m2 (if bibfile
1250                  (progn
1251                    (setq citation (progn
1252                                     (with-temp-buffer
1253                                       (insert-file-contents bibfile)
1254                                       (bibtex-search-entry key)
1255                                       (org-ref-bib-citation))))
1256                    citation)
1257                "no key found"))
1258
1259     (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") "  "))
1260     menu-string))
1261 #+END_SRC
1262
1263 **** convenience functions to act on citation at point
1264      :PROPERTIES:
1265      :ID:       af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1266      :END:
1267 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.
1268
1269 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1270 (defun org-ref-open-pdf-at-point ()
1271   "open the pdf for bibtex key under point if it exists"
1272   (interactive)
1273   (let* ((results (org-ref-get-bibtex-key-and-file))
1274          (key (car results))
1275          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1276     (if (file-exists-p pdf-file)
1277         (org-open-file pdf-file)
1278 (message "no pdf found for %s" key))))
1279
1280
1281 (defun org-ref-open-url-at-point ()
1282   "open the url for bibtex key under point."
1283   (interactive)
1284   (let* ((results (org-ref-get-bibtex-key-and-file))
1285          (key (car results))
1286          (bibfile (cdr results)))
1287     (save-excursion
1288       (with-temp-buffer
1289         (insert-file-contents bibfile)
1290         (bibtex-search-entry key)
1291         ;; I like this better than bibtex-url which does not always find
1292         ;; the urls
1293         (catch 'done
1294           (let ((url (bibtex-autokey-get-field "url")))
1295             (when  url
1296               (browse-url url)
1297               (throw 'done nil)))
1298
1299           (let ((doi (bibtex-autokey-get-field "doi")))
1300             (when doi
1301               (if (string-match "^http" doi)
1302                   (browse-url doi)
1303                 (browse-url (format "http://dx.doi.org/%s" doi)))
1304               (throw 'done nil))))))))
1305
1306 (defun org-ref-open-notes-at-point ()
1307   "open the notes for bibtex key under point."
1308   (interactive)
1309   (let* ((results (org-ref-get-bibtex-key-and-file))
1310          (key (car results))
1311          (bibfile (cdr results)))
1312     (save-excursion
1313       (with-temp-buffer
1314         (insert-file-contents bibfile)
1315         (bibtex-search-entry key)
1316         (org-ref-open-bibtex-notes)))))
1317
1318 (defun org-ref-citation-at-point ()
1319   "give message of current citation at point"
1320   (interactive)
1321   (let* ((cb (current-buffer))
1322         (results (org-ref-get-bibtex-key-and-file))
1323         (key (car results))
1324         (bibfile (cdr results)))        
1325     (message "%s" (progn
1326                     (with-temp-buffer
1327                       (insert-file-contents bibfile)
1328                       (bibtex-search-entry key)
1329                       (org-ref-bib-citation))))))
1330
1331 (defun org-ref-open-citation-at-point ()
1332   "open bibtex file to key at point"
1333   (interactive)
1334   (let* ((cb (current-buffer))
1335         (results (org-ref-get-bibtex-key-and-file))
1336         (key (car results))
1337         (bibfile (cdr results)))
1338     (find-file bibfile)
1339     (bibtex-search-entry key)))
1340 #+END_SRC
1341
1342 **** the actual minibuffer menu
1343 Now, we create the menu.
1344
1345 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1346 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1347   "use a minibuffer to select options for the citation under point.
1348
1349 you select your option with a single key press."
1350   (interactive)
1351   (let* ((choice (read-char (org-ref-get-menu-options)))
1352          (results (org-ref-get-bibtex-key-and-file))
1353          (key (car results))
1354          (cb (current-buffer))
1355          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1356          (bibfile (cdr results)))
1357
1358     (cond
1359      ;; open
1360      ((= choice ?o)
1361       (find-file bibfile)
1362        (bibtex-search-entry key))
1363
1364      ;; cite
1365      ((= choice ?c)
1366       (org-ref-citation-at-point))
1367       
1368
1369      ;; quit
1370      ((or 
1371       (= choice ?q) ; q
1372       (= choice ?\ )) ; space
1373       ;; this clears the minibuffer
1374       (message ""))
1375
1376      ;; pdf
1377      ((= choice ?p)
1378       (org-ref-open-pdf-at-point))
1379
1380      ;; notes
1381      ((= choice ?n)
1382       (org-ref-open-notes-at-point))
1383
1384      ;; url
1385      ((= choice ?u)
1386       (org-ref-open-url-at-point))
1387
1388      ;; anything else we just quit.
1389      (t (message "")))))
1390     
1391 #+END_SRC
1392
1393 *** A function to format a cite link
1394
1395 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.
1396
1397 #+BEGIN_SRC emacs-lisp  :tangle no
1398 ;(defun org-ref-cite-link-format (keyword desc format)
1399 ;   (cond
1400 ;    ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1401 ;    ((eq format 'latex)
1402 ;     (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1403 ;            (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1404 ;            "}"))))
1405 #+END_SRC
1406
1407 *** The actual cite link
1408 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1409
1410 #+BEGIN_SRC emacs-lisp :tangle no
1411 ;(org-add-link-type
1412 ; "cite"
1413 ; 'org-ref-cite-onclick-minibuffer-menu
1414 ; 'org-ref-cite-link-format)
1415 #+END_SRC
1416
1417 *** Automatic definition of the cite links
1418 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. 
1419
1420 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1421 (defmacro org-ref-make-completion-function (type)
1422   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1423      (interactive)
1424      (format "%s:%s" 
1425              ,type
1426              (completing-read 
1427               "bibtex key: " 
1428               (let ((bibtex-files (org-ref-find-bibliography)))
1429                 (bibtex-global-key-alist))))))
1430 #+END_SRC
1431
1432 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.
1433
1434 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1435 (defmacro org-ref-make-format-function (type)
1436   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1437      (cond
1438       ((eq format 'org)
1439        (mapconcat
1440         (lambda (key)
1441           (format "[[#%s][%s]]" key key))
1442         (org-ref-split-and-strip-string keyword) ","))
1443
1444       ((eq format 'ascii)
1445        (concat "["
1446                (mapconcat
1447                 (lambda (key)
1448                   (format "%s" key))
1449                 (org-ref-split-and-strip-string keyword) ",") "]"))
1450         
1451       ((eq format 'html) 
1452        (mapconcat 
1453         (lambda (key) 
1454           (format "<a href=\"#%s\">%s</a>" key key))
1455         (org-ref-split-and-strip-string keyword) ","))
1456
1457       ((eq format 'latex)
1458        (if (string= (substring type -1) "s")
1459            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1460            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1461                                          (org-ref-split-and-strip-string keyword) ""))
1462          ;; bibtex format
1463        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1464                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1465                "}"))))))
1466 #+END_SRC
1467
1468
1469
1470 We create the links by mapping the function onto the list of defined link types. 
1471
1472 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1473 (defun org-ref-format-citation-description (desc)
1474   "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 ::."
1475   (interactive)
1476   (cond
1477    ((string-match "::" desc)
1478     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1479    (t (format "[%s]" desc))))
1480
1481 (defun org-ref-define-citation-link (type &optional key)
1482   "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1483 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z, 
1484 and the completion function."
1485   (interactive "sCitation Type: \ncKey: ")
1486
1487   ;; create the formatting function
1488   (eval `(org-ref-make-format-function ,type))
1489
1490   (eval-expression 
1491    `(org-add-link-type 
1492      ,type
1493      'org-ref-cite-onclick-minibuffer-menu
1494      (quote ,(intern (format "org-ref-format-%s" type)))))
1495
1496   ;; create the completion function
1497   (eval `(org-ref-make-completion-function ,type))
1498   
1499   ;; store new type so it works with adding citations, which checks
1500   ;; for existence in this list
1501   (add-to-list 'org-ref-cite-types type)
1502
1503   ;; and finally if a key is specified, we modify the reftex menu
1504   (when key
1505     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1506           (append (nth 2 (assoc 'org reftex-cite-format-builtin)) 
1507                   `((,key  . ,(concat type ":%l")))))))
1508
1509 ;; create all the link types and their completion functions
1510 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1511 #+END_SRC
1512
1513 *** org-ref-insert-cite-link
1514 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.
1515
1516 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1517 (defun org-ref-insert-cite-link (alternative-cite)
1518   "Insert a default citation link using reftex. If you are on a link, it
1519 appends to the end of the link, otherwise, a new link is
1520 inserted. Use a prefix arg to get a menu of citation types."
1521   (interactive "P")
1522   (org-ref-find-bibliography)
1523   (let* ((object (org-element-context))
1524          (link-string-beginning (org-element-property :begin object))
1525          (link-string-end (org-element-property :end object))
1526          (path (org-element-property :path object)))  
1527
1528     (if (not alternative-cite)
1529         
1530         (cond
1531          ;; case where we are in a link
1532          ((and (equal (org-element-type object) 'link) 
1533                (-contains? org-ref-cite-types (org-element-property :type object)))
1534           (goto-char link-string-end)
1535           ;; sometimes there are spaces at the end of the link
1536           ;; this code moves point pack until no spaces are there
1537           (while (looking-back " ") (backward-char))  
1538           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1539
1540          ;; We are next to a link, and we want to append
1541          ((save-excursion 
1542             (backward-char)
1543             (and (equal (org-element-type (org-element-context)) 'link) 
1544                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1545           (while (looking-back " ") (backward-char))  
1546           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1547
1548          ;; insert fresh link
1549          (t 
1550           (insert 
1551            (concat org-ref-default-citation-link 
1552                    ":" 
1553                    (mapconcat 'identity (reftex-citation t) ",")))))
1554
1555       ;; you pressed a C-u so we run this code
1556       (reftex-citation)))
1557   )
1558 #+END_SRC
1559
1560 #+RESULTS:
1561 : org-ref-insert-cite-link
1562
1563 *** Completion in cite links
1564 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.
1565
1566 #+BEGIN_SRC emacs-lisp  :tangle no
1567 (defun org-cite-complete-link (&optional arg)
1568   "Completion function for cite links"
1569   (format "%s:%s" 
1570           org-ref-default-citation-link
1571           (completing-read 
1572            "bibtex key: " 
1573            (let ((bibtex-files (org-ref-find-bibliography)))
1574              (bibtex-global-key-alist)))))
1575 #+END_SRC
1576
1577 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1578
1579 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1580 (defun org-ref-insert-cite-with-completion (type)
1581   "Insert a cite link with completion"
1582   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1583   (insert (funcall (intern (format "org-%s-complete-link" type)))))
1584 #+END_SRC
1585
1586 ** Storing links to a bibtex entry
1587 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.
1588
1589 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1590 (defun org-ref-store-bibtex-entry-link ()
1591   "Save a citation link to the current bibtex entry. Saves in the default link type."
1592   (interactive)
1593   (let ((link (concat org-ref-default-citation-link 
1594                  ":"   
1595                  (save-excursion
1596                    (bibtex-beginning-of-entry)
1597                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1598     (message "saved %s" link)
1599     (push (list link) org-stored-links)
1600     (car org-stored-links)))
1601 #+END_SRC
1602
1603
1604 * Utilities
1605 ** create simple text citation from bibtex entry
1606
1607 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1608 (defun org-ref-bib-citation ()
1609   "from a bibtex entry, create and return a simple citation string."
1610
1611   (bibtex-beginning-of-entry)
1612   (let* ((cb (current-buffer))
1613          (bibtex-expand-strings t)
1614          (entry (loop for (key . value) in (bibtex-parse-entry t)
1615                       collect (cons (downcase key) value)))
1616          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1617          (year  (reftex-get-bib-field "year" entry))
1618          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1619          (key (reftex-get-bib-field "=key=" entry))
1620          (journal (reftex-get-bib-field "journal" entry))
1621          (volume (reftex-get-bib-field "volume" entry))
1622          (pages (reftex-get-bib-field "pages" entry))
1623          (doi (reftex-get-bib-field "doi" entry))
1624          (url (reftex-get-bib-field "url" entry))
1625          )
1626     ;;authors, "title", Journal, vol(iss):pages (year).
1627     (format "%s, \"%s\", %s, %s:%s (%s)"
1628             author title journal  volume pages year)))
1629 #+END_SRC
1630
1631 #+RESULTS:
1632 : org-ref-bib-citation
1633
1634
1635 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1636 (defun org-ref-bib-html-citation ()
1637   "from a bibtex entry, create and return a simple citation with html links."
1638
1639   (bibtex-beginning-of-entry)
1640   (let* ((cb (current-buffer))
1641          (bibtex-expand-strings t)
1642          (entry (loop for (key . value) in (bibtex-parse-entry t)
1643                       collect (cons (downcase key) value)))
1644          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1645          (year  (reftex-get-bib-field "year" entry))
1646          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1647          (key (reftex-get-bib-field "=key=" entry))
1648          (journal (reftex-get-bib-field "journal" entry))
1649          (volume (reftex-get-bib-field "volume" entry))
1650          (pages (reftex-get-bib-field "pages" entry))
1651          (doi (reftex-get-bib-field "doi" entry))
1652          (url (reftex-get-bib-field "url" entry))
1653          )
1654     ;;authors, "title", Journal, vol(iss):pages (year).
1655     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1656                     author title journal  volume pages year)
1657             (when url (format " <a href=\"%s\">link</a>" url))
1658             (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1659     ))
1660 #+END_SRC
1661
1662 ** open pdf from bibtex
1663 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1664 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1665 (defun org-ref-open-bibtex-pdf ()
1666   "open pdf for a bibtex entry, if it exists. assumes point is in
1667 the entry of interest in the bibfile. but does not check that."
1668   (interactive)
1669   (save-excursion
1670     (bibtex-beginning-of-entry)
1671     (let* ((bibtex-expand-strings t)
1672            (entry (bibtex-parse-entry t))
1673            (key (reftex-get-bib-field "=key=" entry))
1674            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1675       (message "%s" pdf)
1676       (if (file-exists-p pdf)
1677           (org-open-link-from-string (format "[[file:%s]]" pdf))
1678         (ding)))))
1679 #+END_SRC
1680
1681 ** open notes from bibtex
1682 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1683
1684 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1685 (defun org-ref-open-bibtex-notes ()
1686   "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1687
1688 I never did figure out how to use reftex to make this happen
1689 non-interactively. the reftex-format-citation function did not
1690 work perfectly; there were carriage returns in the strings, and
1691 it did not put the key where it needed to be. so, below I replace
1692 the carriage returns and extra spaces with a single space and
1693 construct the heading by hand."
1694   (interactive)
1695
1696   (bibtex-beginning-of-entry)
1697   (let* ((cb (current-buffer))
1698          (bibtex-expand-strings t)
1699          (entry (loop for (key . value) in (bibtex-parse-entry t)
1700                       collect (cons (downcase key) value)))
1701          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1702          (year  (reftex-get-bib-field "year" entry))
1703          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1704          (key (reftex-get-bib-field "=key=" entry))
1705          (journal (reftex-get-bib-field "journal" entry))
1706          (volume (reftex-get-bib-field "volume" entry))
1707          (pages (reftex-get-bib-field "pages" entry))
1708          (doi (reftex-get-bib-field "doi" entry))
1709          (url (reftex-get-bib-field "url" entry))
1710          )
1711
1712     ;; save key to clipboard to make saving pdf later easier by pasting.
1713     (with-temp-buffer
1714       (insert key)
1715       (kill-ring-save (point-min) (point-max)))
1716     
1717     ;; now look for entry in the notes file
1718     (if  org-ref-bibliography-notes
1719         (find-file org-ref-bibliography-notes)
1720       (error "org-ref-bib-bibliography-notes is not set to anything"))
1721     
1722     (goto-char (point-min))
1723     ;; put new entry in notes if we don't find it.
1724     (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1725         (progn
1726           (org-show-entry)
1727           (outline-previous-visible-heading 1)
1728           (recenter-top-bottom 0))
1729       ;; no entry found, so add one     
1730       (insert (format "\n** TODO %s - %s" year title))
1731       (insert (format"
1732  :PROPERTIES:
1733   :Custom_ID: %s
1734   :AUTHOR: %s
1735   :JOURNAL: %s
1736   :YEAR: %s
1737   :VOLUME: %s
1738   :PAGES: %s
1739   :DOI: %s
1740   :URL: %s
1741  :END:
1742 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1743 key author journal year volume pages doi url key org-ref-pdf-directory key))
1744 (save-buffer))))
1745 #+END_SRC
1746
1747 ** open url in browser from bibtex
1748
1749 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1750
1751 + 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.
1752
1753 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1754 (defun org-ref-open-in-browser ()
1755   "Open the bibtex entry at point in a browser using the url field or doi field"
1756 (interactive)
1757 (save-excursion
1758   (bibtex-beginning-of-entry)
1759   (catch 'done
1760     (let ((url (bibtex-autokey-get-field "url")))
1761       (when  url
1762         (browse-url url)
1763         (throw 'done nil)))
1764
1765     (let ((doi (bibtex-autokey-get-field "doi")))
1766       (when doi
1767         (if (string-match "^http" doi)
1768             (browse-url doi)
1769           (browse-url (format "http://dx.doi.org/%s" doi)))
1770         (throw 'done nil)))
1771     (message "No url or doi found"))))
1772 #+END_SRC
1773
1774 ** citeulike
1775    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.
1776
1777 *** function to upload bibtex to citeulike
1778
1779 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1780 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1781   "with point in  a bibtex entry get bibtex string and submit to citeulike.
1782
1783 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1784   (interactive)
1785   (message "uploading to citeulike")
1786   (save-restriction
1787     (bibtex-narrow-to-entry)
1788     (let ((startpos (point-min))
1789           (endpos (point-max))
1790           (bibtex-string (buffer-string))
1791           (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1792       (with-temp-buffer (insert bibtex-string)
1793                         (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1794 #+END_SRC
1795
1796 *** The upload script
1797 Here is the python script for uploading. 
1798
1799 *************** TODO document how to get the cookies
1800 *************** END
1801
1802
1803 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1804 #!python
1805 import pickle, requests, sys
1806
1807 # reload cookies
1808 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1809     cookies = pickle.load(f)
1810
1811 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1812
1813 bibtex = sys.stdin.read()
1814
1815 data = {'pasted':bibtex,
1816         'to_read':2,
1817         'tag_parsing':'simple',
1818         'strip_brackets':'no',
1819         'update_id':'bib-key',
1820         'btn_bibtex':'Import BibTeX file ...'}
1821
1822 headers = {'content-type': 'multipart/form-data',
1823            'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1824
1825 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1826 print r
1827 #+END_SRC
1828
1829 ** Build a pdf from a bibtex file
1830    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.
1831
1832 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1833 (defun org-ref-build-full-bibliography ()
1834   "build pdf of all bibtex entries, and open it."
1835   (interactive)
1836   (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1837         (bib-base (file-name-sans-extension bibfile))
1838         (texfile (concat bib-base ".tex"))
1839         (pdffile (concat bib-base ".pdf")))
1840     (find-file texfile)
1841     (erase-buffer)
1842     (insert (format "\\documentclass[12pt]{article}
1843 \\usepackage[version=3]{mhchem}
1844 \\usepackage{url}
1845 \\usepackage[numbers]{natbib}
1846 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1847 \\usepackage{doi}
1848 \\begin{document}
1849 \\nocite{*}
1850 \\bibliographystyle{unsrtnat}
1851 \\bibliography{%s}
1852 \\end{document}" bib-base))
1853     (save-buffer)
1854     (shell-command (concat "pdflatex " bib-base))
1855     (shell-command (concat "bibtex " bib-base))
1856     (shell-command (concat "pdflatex " bib-base))
1857     (shell-command (concat "pdflatex " bib-base))
1858     (kill-buffer texfile)
1859     (org-open-file pdffile)
1860     )) 
1861 #+END_SRC
1862
1863 ** Extract bibtex entries cited in an org-file
1864 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.
1865
1866 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1867 (defun org-ref-extract-bibtex-entries ()
1868   "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1869
1870 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1871   (interactive)
1872   (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1873          (tempname (make-temp-file "extract-bib"))
1874          (contents (buffer-string))
1875          (cb (current-buffer))
1876          basename texfile bibfile results)
1877     
1878     ;; open tempfile and insert org-buffer contents
1879     (find-file tempname)
1880     (insert contents)
1881     (setq basename (file-name-sans-extension 
1882                     (file-name-nondirectory buffer-file-name))
1883           texfile (concat tempname ".tex")
1884           bibfile (concat tempname ".bib"))
1885     
1886     ;; see if we have a bibliography, and insert the default one if not.
1887     (save-excursion
1888       (goto-char (point-min))
1889       (unless (re-search-forward "^bibliography:" (point-max) 'end)
1890         (insert (format "\nbibliography:%s" 
1891                         (mapconcat 'identity reftex-default-bibliography ",")))))
1892     (save-buffer)
1893
1894     ;; get a latex file and extract the references
1895     (org-latex-export-to-latex)
1896     (find-file texfile)
1897     (reftex-parse-all)
1898     (reftex-create-bibtex-file bibfile)
1899     (save-buffer)
1900     ;; save results of the references
1901     (setq results (buffer-string))
1902
1903     ;; kill buffers. these are named by basename, not full path
1904     (kill-buffer (concat basename ".bib"))
1905     (kill-buffer (concat basename ".tex"))
1906     (kill-buffer basename)
1907
1908     (delete-file bibfile)
1909     (delete-file texfile)
1910     (delete-file tempname)
1911
1912     ;; Now back to the original org buffer and insert the results
1913     (switch-to-buffer cb)
1914     (when (not (string= "" results))
1915       (save-excursion
1916         (goto-char (point-max))
1917         (insert "\n\n")
1918         (org-insert-heading)
1919         (insert (format " Bibtex entries
1920
1921 ,#+BEGIN_SRC text :tangle %s
1922 %s
1923 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
1924 #+END_SRC
1925
1926 ** Find bad cite links
1927 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.
1928
1929 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1930 (require 'cl)
1931
1932 (defun index (substring list)
1933   "return the index of string in a list of strings"
1934   (let ((i 0)
1935         (found nil))
1936     (dolist (arg list i)
1937       (if (string-match (concat "^" substring "$") arg)
1938           (progn 
1939             (setq found t)
1940             (return i)))
1941       (setq i (+ i 1)))
1942     ;; return counter if found, otherwise return nil
1943     (if found i nil)))
1944
1945
1946 (defun org-ref-find-bad-citations ()
1947   "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
1948
1949 Makes a new buffer with clickable links."
1950   (interactive)
1951   ;; generate the list of bibtex-keys and cited keys
1952   (let* ((bibtex-files (org-ref-find-bibliography))
1953          (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
1954          (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
1955          (bad-citations '()))
1956
1957     (org-element-map (org-element-parse-buffer) 'link
1958       (lambda (link)       
1959         (let ((plist (nth 1 link)))                          
1960           (when (equal (plist-get plist ':type) "cite")
1961             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
1962               (when (not (index key bibtex-keys))
1963                 (setq bad-citations (append bad-citations
1964                                             `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
1965                                                        key (buffer-name)(plist-get plist ':begin)))))
1966                 ))))))
1967
1968     (if bad-citations
1969       (progn
1970         (switch-to-buffer-other-window "*Missing citations*")
1971         (org-mode)
1972         (erase-buffer)
1973         (insert "* List of bad cite links\n")
1974         (insert (mapconcat 'identity bad-citations ""))
1975                                         ;(setq buffer-read-only t)
1976         (use-local-map (copy-keymap org-mode-map))
1977         (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
1978
1979       (when (get-buffer "*Missing citations*")
1980           (kill-buffer "*Missing citations*"))
1981       (message "No bad cite links found"))))
1982 #+END_SRC
1983
1984 ** Finding non-ascii characters
1985 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them. 
1986
1987 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1988 (defun org-ref-find-non-ascii-characters ()
1989   "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
1990   (interactive)
1991   (occur "[^[:ascii:]]"))
1992 #+END_SRC
1993
1994 ** Resort a bibtex entry
1995 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.
1996
1997 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1998 (defun org-ref-sort-bibtex-entry ()
1999   "sort fields of entry in standard order and downcase them"
2000   (interactive)
2001   (bibtex-beginning-of-entry)
2002   (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2003          (entry (bibtex-parse-entry))
2004          (entry-fields)
2005          (other-fields)
2006          (type (cdr (assoc "=type=" entry)))
2007          (key (cdr (assoc "=key=" entry))))
2008
2009     ;; these are the fields we want to order that are in this entry
2010     (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2011     ;; we do not want to reenter these fields
2012     (setq entry-fields (remove "=key=" entry-fields))
2013     (setq entry-fields (remove "=type=" entry-fields))
2014
2015     ;;these are the other fields in the entry
2016     (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2017
2018     (cond
2019      ;; right now we only resort articles
2020      ((string= (downcase type) "article") 
2021       (bibtex-kill-entry)
2022       (insert
2023        (concat "@article{" key ",\n" 
2024                (mapconcat  
2025                 (lambda (field) 
2026                   (when (member field entry-fields)
2027                     (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2028                (mapconcat 
2029                 (lambda (field) 
2030                   (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2031                "\n}\n\n"))
2032       (bibtex-find-entry key)
2033       (bibtex-fill-entry)
2034       (bibtex-clean-entry)
2035        ))))
2036 #+END_SRC
2037
2038 ** Clean a bibtex entry
2039    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.
2040 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.
2041 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2042 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2043   "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"
2044   (interactive "P")
2045   (bibtex-beginning-of-entry) 
2046 (end-of-line)
2047   ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2048   (unless (string-match ",$" (thing-at-point 'line))
2049     (end-of-line)
2050     (insert ","))
2051
2052   ;; check for empty pages, and put eid or article id in its place
2053   (let ((entry (bibtex-parse-entry))
2054         (pages (bibtex-autokey-get-field "pages"))
2055         (year (bibtex-autokey-get-field "year"))
2056         (doi  (bibtex-autokey-get-field "doi"))
2057         ;; The Journal of Chemical Physics uses eid
2058         (eid (bibtex-autokey-get-field "eid")))
2059
2060     ;; replace http://dx.doi.org/ in doi. some journals put that in,
2061     ;; but we only want the doi.
2062     (when (string-match "^http://dx.doi.org/" doi)
2063       (bibtex-beginning-of-entry)
2064       (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2065       (bibtex-kill-field)
2066       (bibtex-make-field "doi")
2067       (backward-char)
2068       (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2069
2070     ;; asap articles often set year to 0, which messes up key
2071     ;; generation. fix that.
2072     (when (string= "0" year)  
2073       (bibtex-beginning-of-entry)
2074       (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2075       (bibtex-kill-field)
2076       (bibtex-make-field "year")
2077       (backward-char)
2078       (insert (read-string "Enter year: ")))
2079
2080     ;; fix pages if they are empty if there is an eid to put there.
2081     (when (string= "-" pages)
2082       (when eid   
2083         (bibtex-beginning-of-entry)
2084         ;; this seems like a clunky way to set the pages field.But I
2085         ;; cannot find a better way.
2086         (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2087         (bibtex-kill-field)
2088         (bibtex-make-field "pages")
2089         (backward-char)
2090         (insert eid)))
2091
2092     ;; replace naked & with \&
2093     (save-restriction
2094       (bibtex-narrow-to-entry)
2095       (bibtex-beginning-of-entry)
2096       (message "checking &")
2097       (replace-regexp " & " " \\\\& ")
2098       (widen))
2099
2100     ;; generate a key, and if it duplicates an existing key, edit it.
2101     (unless keep-key
2102       (let ((key (bibtex-generate-autokey)))
2103
2104         ;; first we delete the existing key
2105         (bibtex-beginning-of-entry)
2106         (re-search-forward bibtex-entry-maybe-empty-head)
2107         (if (match-beginning bibtex-key-in-head)
2108             (delete-region (match-beginning bibtex-key-in-head)
2109                            (match-end bibtex-key-in-head)))
2110         ;; check if the key is in the buffer
2111         (when (save-excursion
2112                 (bibtex-search-entry key))
2113           (save-excursion
2114             (bibtex-search-entry key)
2115             (bibtex-copy-entry-as-kill)
2116             (switch-to-buffer-other-window "*duplicate entry*")
2117             (bibtex-yank))
2118           (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2119
2120         (insert key)
2121         (kill-new key))) ;; save key for pasting            
2122
2123     ;; run hooks. each of these operates on the entry with no arguments.
2124     ;; this did not work like  i thought, it gives a symbolp error.
2125     ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2126     (mapcar (lambda (x)
2127               (save-restriction
2128                 (save-excursion
2129                   (funcall x))))
2130             org-ref-clean-bibtex-entry-hook)
2131     
2132     ;; sort fields within entry
2133     (org-ref-sort-bibtex-entry)
2134     ;; check for non-ascii characters
2135     (occur "[^[:ascii:]]")
2136     ))
2137 #+END_SRC
2138
2139 #+RESULTS:
2140 : org-ref-clean-bibtex-entry
2141
2142 ** Sort the entries in a citation link by year
2143 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2144
2145 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2146 (defun org-ref-get-citation-year (key)
2147   "get the year of an entry with key. Returns year as a string."
2148   (interactive)
2149   (let* ((results (org-ref-get-bibtex-key-and-file key))
2150          (bibfile (cdr results)))
2151     (with-temp-buffer
2152       (insert-file-contents bibfile)
2153       (bibtex-search-entry key nil 0)
2154       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2155         ))))
2156
2157 (defun org-ref-sort-citation-link ()
2158  "replace link at point with sorted link by year"
2159  (interactive)
2160  (let* ((object (org-element-context))   
2161         (type (org-element-property :type object))
2162         (begin (org-element-property :begin object))
2163         (end (org-element-property :end object))
2164         (link-string (org-element-property :path object))
2165         keys years data)
2166   (setq keys (org-ref-split-and-strip-string link-string))
2167   (setq years (mapcar 'org-ref-get-citation-year keys)) 
2168   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2169   (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2170   ;; now get the keys separated by commas
2171   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2172   ;; and replace the link with the sorted keys
2173   (cl--set-buffer-substring begin end (concat type ":" keys))))
2174 #+END_SRC
2175
2176 ** Sort entries in citation links with shift-arrow keys
2177 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2178 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2179 (defun org-ref-swap-keys (i j keys)
2180  "swap the keys in a list with index i and j"
2181  (let ((tempi (nth i keys)))
2182    (setf (nth i keys) (nth j keys))
2183    (setf (nth j keys) tempi))
2184   keys)
2185
2186 (defun org-ref-swap-citation-link (direction)
2187  "move citation at point in direction +1 is to the right, -1 to the left"
2188  (interactive)
2189  (let* ((object (org-element-context))   
2190         (type (org-element-property :type object))
2191         (begin (org-element-property :begin object))
2192         (end (org-element-property :end object))
2193         (link-string (org-element-property :path object))
2194         key keys i)
2195    ;;   We only want this to work on citation links
2196    (when (-contains? org-ref-cite-types type)
2197         (setq key (org-ref-get-bibtex-key-under-cursor))
2198         (setq keys (org-ref-split-and-strip-string link-string))
2199         (setq i (index key keys))  ;; defined in org-ref
2200         (if (> direction 0) ;; shift right
2201             (org-ref-swap-keys i (+ i 1) keys)
2202           (org-ref-swap-keys i (- i 1) keys))   
2203         (setq keys (mapconcat 'identity keys ","))
2204         ;; and replace the link with the sorted keys
2205         (cl--set-buffer-substring begin end (concat type ":" keys))
2206         ;; now go forward to key so we can move with the key
2207         (re-search-forward key) 
2208         (goto-char (match-beginning 0)))))
2209
2210 ;; add hooks to make it work
2211 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2212 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2213 #+END_SRC
2214 * Aliases
2215 I like convenience. Here are some aliases for faster typing.
2216
2217 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2218 (defalias 'oro 'org-ref-open-citation-at-point)
2219 (defalias 'orc 'org-ref-citation-at-point)
2220 (defalias 'orp 'org-ref-open-pdf-at-point)
2221 (defalias 'oru 'org-ref-open-url-at-point)
2222 (defalias 'orn 'org-ref-open-notes-at-point)
2223
2224 (defalias 'orib 'org-ref-insert-bibliography-link)
2225 (defalias 'oric 'org-ref-insert-cite-link)
2226 (defalias 'orir 'org-ref-insert-ref-link)
2227 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2228
2229 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2230 #+END_SRC
2231 * End of code
2232 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2233 (provide 'org-ref)
2234 #+END_SRC
2235
2236
2237 * Build                                                            :noexport:
2238
2239 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2240
2241 [[elisp:(org-babel-load-file "org-ref.org")]]
2242
2243
2244