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