]> git.donarmstrong.com Git - org-ref.git/blob - org-ref.org
add org directory
[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     ;; we need the link path start and end
1008     (save-excursion
1009       (goto-char (org-element-property :begin object))
1010       (search-forward link-string nil nil 1)
1011       (setq link-string-beginning (match-beginning 0))
1012       (setq link-string-end (match-end 0)))
1013
1014     ;; The key is the text between commas, or the link boundaries
1015     (save-excursion
1016       (if (search-forward "," link-string-end t 1)
1017           (setq key-end (- (match-end 0) 1)) ; we found a match
1018         (setq key-end link-string-end))) ; no comma found so take the end
1019     ;; and backward to previous comma from point which defines the start character
1020     (save-excursion
1021       (if (search-backward "," link-string-beginning 1 1)
1022           (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1023         (setq key-beginning link-string-beginning))) ; no match found
1024     ;; save the key we clicked on.
1025     (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1026     (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1027     bibtex-key
1028     ))
1029 #+END_SRC
1030
1031 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.
1032
1033 **** Getting the bibliographies
1034 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1035 (defun org-ref-find-bibliography ()
1036   "find the bibliography in the buffer.
1037 This function sets and returns cite-bibliography-files, which is a list of files
1038 either from bibliography:f1.bib,f2.bib
1039 \bibliography{f1,f2}
1040 internal bibliographies
1041
1042 falling back to what the user has set in org-ref-default-bibliography
1043 "
1044   (interactive)
1045   (catch 'result
1046     (save-excursion
1047       (goto-char (point-min))
1048       ;;  look for a bibliography link
1049       (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1050         (setq org-ref-bibliography-files
1051               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1052         (throw 'result org-ref-bibliography-files))
1053
1054       
1055       ;; we did not find a bibliography link. now look for \bibliography
1056       (goto-char (point-min))
1057       (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1058         ;; split, and add .bib to each file
1059         (setq org-ref-bibliography-files
1060               (mapcar (lambda (x) (concat x ".bib"))
1061                       (mapcar 'org-ref-strip-string 
1062                               (split-string (match-string 1) ","))))
1063         (throw 'result org-ref-bibliography-files))
1064
1065       ;; no bibliography found. maybe we need a biblatex addbibresource
1066       (goto-char (point-min))
1067       ;;  look for a bibliography link
1068       (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1069         (setq org-ref-bibliography-files
1070               (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1071         (throw 'result org-ref-bibliography-files))
1072           
1073       ;; we did not find anything. use defaults
1074       (setq org-ref-bibliography-files org-ref-default-bibliography)))
1075
1076     ;; set reftex-default-bibliography so we can search
1077     (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1078     org-ref-bibliography-files)
1079 #+END_SRC
1080
1081 **** Finding the bibliography file a key is in
1082 Now, we can see if an entry is in a file. 
1083
1084 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1085 (defun org-ref-key-in-file-p (key filename)
1086   "determine if the key is in the file"
1087   (interactive "skey: \nsFile: ")
1088
1089   (with-temp-buffer
1090     (insert-file-contents filename)
1091     (prog1
1092         (bibtex-search-entry key nil 0))))
1093 #+END_SRC
1094
1095 Finally, we want to know which file the key is in.
1096
1097 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1098 (defun org-ref-get-bibtex-key-and-file (&optional key)
1099   "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1100  (interactive)
1101  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1102        (file))
1103    (unless key
1104      (setq key (org-ref-get-bibtex-key-under-cursor)))
1105    (setq file     (catch 'result
1106                     (loop for file in org-ref-bibliography-files do
1107                           (if (org-ref-key-in-file-p key (file-truename file)) 
1108                               (throw 'result file)))))
1109    (cons key file)))
1110 #+END_SRC
1111
1112 **** Creating the menu for when we click on a key
1113      :PROPERTIES:
1114      :ID:       d7b7530b-802f-42b1-b61e-1e77da33e278
1115      :END:
1116 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.
1117
1118 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1119 (defun org-ref-get-menu-options ()
1120   "returns a dynamically determined string of options for the citation under point.
1121
1122 we check to see if there is pdf, and if the key actually exists in the bibliography"
1123   (interactive)
1124   (let* ((results (org-ref-get-bibtex-key-and-file))
1125          (key (car results))
1126          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1127          (bibfile (cdr results))
1128          m1 m2 m3 m4 m5 menu-string)
1129     (setq m1 (if bibfile                 
1130                  "(o)pen"
1131                "(No key found)"))
1132
1133     (setq m3 (if (file-exists-p pdf-file)
1134                  "(p)df"
1135                      "(No pdf found)"))
1136
1137     (setq m4 (if (not
1138                   (and bibfile
1139                        (string= (catch 'url
1140                                   (progn
1141
1142                                     (with-temp-buffer
1143                                       (insert-file-contents bibfile)
1144                                       (bibtex-search-entry key)
1145                                       (when (not
1146                                              (string= (setq url (bibtex-autokey-get-field "url")) ""))
1147                                         (throw 'url url))
1148
1149                                       (when (not
1150                                              (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1151                                         (throw 'url url))))) "")))
1152                "(u)rl" "(no url found)"))
1153     (setq m5 "(n)otes")
1154     (setq m2 (if bibfile
1155                  (progn
1156                    (setq citation (progn
1157                                     (with-temp-buffer
1158                                       (insert-file-contents bibfile)
1159                                       (bibtex-search-entry key)
1160                                       (org-ref-bib-citation))))
1161                    citation)
1162                "no key found"))
1163
1164     (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") "  "))
1165     menu-string))
1166 #+END_SRC
1167
1168 **** convenience functions to act on citation at point
1169      :PROPERTIES:
1170      :ID:       af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1171      :END:
1172 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.
1173
1174 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1175 (defun org-ref-open-pdf-at-point ()
1176   "open the pdf for bibtex key under point if it exists"
1177   (interactive)
1178   (let* ((results (org-ref-get-bibtex-key-and-file))
1179          (key (car results))
1180          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1181     (if (file-exists-p pdf-file)
1182         (org-open-file pdf-file)
1183 (message "no pdf found for %s" key))))
1184
1185
1186 (defun org-ref-open-url-at-point ()
1187   "open the url for bibtex key under point."
1188   (interactive)
1189   (let* ((results (org-ref-get-bibtex-key-and-file))
1190          (key (car results))
1191          (bibfile (cdr results)))
1192     (save-excursion
1193       (with-temp-buffer
1194         (insert-file-contents bibfile)
1195         (bibtex-search-entry key)
1196         ;; I like this better than bibtex-url which does not always find
1197         ;; the urls
1198         (catch 'done
1199           (let ((url (bibtex-autokey-get-field "url")))
1200             (when  url
1201               (browse-url url)
1202               (throw 'done nil)))
1203
1204           (let ((doi (bibtex-autokey-get-field "doi")))
1205             (when doi
1206               (if (string-match "^http" doi)
1207                   (browse-url doi)
1208                 (browse-url (format "http://dx.doi.org/%s" doi)))
1209               (throw 'done nil))))))))
1210
1211 (defun org-ref-open-notes-at-point ()
1212   "open the notes for bibtex key under point."
1213   (interactive)
1214   (let* ((results (org-ref-get-bibtex-key-and-file))
1215          (key (car results))
1216          (bibfile (cdr results)))
1217     (save-excursion
1218       (with-temp-buffer
1219         (insert-file-contents bibfile)
1220         (bibtex-search-entry key)
1221         (org-ref-open-bibtex-notes)))))
1222
1223 (defun org-ref-citation-at-point ()
1224   "give message of current citation at point"
1225   (interactive)
1226   (let* ((cb (current-buffer))
1227         (results (org-ref-get-bibtex-key-and-file))
1228         (key (car results))
1229         (bibfile (cdr results)))        
1230     (message "%s" (progn
1231                     (with-temp-buffer
1232                       (insert-file-contents bibfile)
1233                       (bibtex-search-entry key)
1234                       (org-ref-bib-citation))))))
1235
1236 (defun org-ref-open-citation-at-point ()
1237   "open bibtex file to key at point"
1238   (interactive)
1239   (let* ((cb (current-buffer))
1240         (results (org-ref-get-bibtex-key-and-file))
1241         (key (car results))
1242         (bibfile (cdr results)))
1243     (find-file bibfile)
1244     (bibtex-search-entry key)))
1245 #+END_SRC
1246
1247 **** the actual minibuffer menu
1248 Now, we create the menu.
1249
1250 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1251 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1252   "use a minibuffer to select options for the citation under point.
1253
1254 you select your option with a single key press."
1255   (interactive)
1256   (let* ((choice (read-char (org-ref-get-menu-options)))
1257          (results (org-ref-get-bibtex-key-and-file))
1258          (key (car results))
1259          (cb (current-buffer))
1260          (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1261          (bibfile (cdr results)))
1262
1263     (cond
1264      ;; open
1265      ((= choice ?o)
1266       (find-file bibfile)
1267        (bibtex-search-entry key))
1268
1269      ;; cite
1270      ((= choice ?c)
1271       (org-ref-citation-at-point))
1272       
1273
1274      ;; quit
1275      ((or 
1276       (= choice ?q) ; q
1277       (= choice ?\ )) ; space
1278       ;; this clears the minibuffer
1279       (message ""))
1280
1281      ;; pdf
1282      ((= choice ?p)
1283       (org-ref-open-pdf-at-point))
1284
1285      ;; notes
1286      ((= choice ?n)
1287       (org-ref-open-notes-at-point))
1288
1289      ;; url
1290      ((= choice ?u)
1291       (org-ref-open-url-at-point))
1292
1293      ;; anything else we just quit.
1294      (t (message "")))))
1295     
1296 #+END_SRC
1297
1298 *** A function to format a cite link
1299
1300 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.
1301
1302 #+BEGIN_SRC emacs-lisp  :tangle no
1303 ;(defun org-ref-cite-link-format (keyword desc format)
1304 ;   (cond
1305 ;    ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1306 ;    ((eq format 'latex)
1307 ;     (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1308 ;            (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1309 ;            "}"))))
1310 #+END_SRC
1311
1312 *** The actual cite link
1313 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1314
1315 #+BEGIN_SRC emacs-lisp :tangle no
1316 ;(org-add-link-type
1317 ; "cite"
1318 ; 'org-ref-cite-onclick-minibuffer-menu
1319 ; 'org-ref-cite-link-format)
1320 #+END_SRC
1321
1322 *** Automatic definition of the cite links
1323 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. 
1324
1325 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1326 (defmacro org-ref-make-completion-function (type)
1327   `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1328      (interactive)
1329      (format "%s:%s" 
1330              ,type
1331              (completing-read 
1332               "bibtex key: " 
1333               (let ((bibtex-files (org-ref-find-bibliography)))
1334                 (bibtex-global-key-alist))))))
1335 #+END_SRC
1336
1337 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.
1338
1339 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1340 (defmacro org-ref-make-format-function (type)
1341   `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1342      (cond
1343       ((eq format 'html) 
1344        (mapconcat 
1345         (lambda (key) 
1346           (format "<a href=\"#%s\">%s</a>" key key))
1347         (org-ref-split-and-strip-string keyword) ","))
1348
1349       ((eq format 'latex)
1350        (if (string= (substring type -1) "s")
1351            ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1352            (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}"  key))
1353                                          (org-ref-split-and-strip-string keyword) ""))
1354          ;; bibtex format
1355        (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1356                (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1357                "}"))))))
1358 #+END_SRC
1359
1360
1361
1362 We create the links by mapping the function onto the list of defined link types. 
1363
1364 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1365 (defun org-ref-format-citation-description (desc)
1366   "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 ::."
1367   (interactive)
1368   (cond
1369    ((string-match "::" desc)
1370     (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1371    (t (format "[%s]" desc))))
1372
1373 (defun org-ref-define-citation-link (type &optional key)
1374   "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1375 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z, 
1376 and the completion function."
1377   (interactive "sCitation Type: \ncKey: ")
1378
1379   ;; create the formatting function
1380   (eval `(org-ref-make-format-function ,type))
1381
1382   (eval-expression 
1383    `(org-add-link-type 
1384      ,type
1385      'org-ref-cite-onclick-minibuffer-menu
1386      (quote ,(intern (format "org-ref-format-%s" type)))))
1387
1388   ;; create the completion function
1389   (eval `(org-ref-make-completion-function ,type))
1390   
1391   ;; store new type so it works with adding citations, which checks
1392   ;; for existence in this list
1393   (add-to-list 'org-ref-cite-types type)
1394
1395   ;; and finally if a key is specified, we modify the reftex menu
1396   (when key
1397     (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1398           (append (nth 2 (assoc 'org reftex-cite-format-builtin)) 
1399                   `((,key  . ,(concat type ":%l")))))))
1400
1401 ;; create all the link types and their completion functions
1402 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1403 #+END_SRC
1404
1405 *** org-ref-insert-cite-link
1406 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.
1407
1408 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1409 (defun org-ref-insert-cite-link (alternative-cite)
1410   "Insert a default citation link using reftex. If you are on a link, it
1411 appends to the end of the link, otherwise, a new link is
1412 inserted. Use a prefix arg to get a menu of citation types."
1413   (interactive "P")
1414   (org-ref-find-bibliography)
1415   (let* ((object (org-element-context))
1416          (link-string-beginning (org-element-property :begin object))
1417          (link-string-end (org-element-property :end object))
1418          (path (org-element-property :path object)))  
1419
1420     (if (not alternative-cite)
1421         
1422         (cond
1423          ;; case where we are in a link
1424          ((and (equal (org-element-type object) 'link) 
1425                (-contains? org-ref-cite-types (org-element-property :type object)))
1426           (goto-char link-string-end)
1427           ;; sometimes there are spaces at the end of the link
1428           ;; this code moves point pack until no spaces are there
1429           (while (looking-back " ") (backward-char))  
1430           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1431
1432          ;; We are next to a link, and we want to append
1433          ((save-excursion 
1434             (backward-char)
1435             (and (equal (org-element-type (org-element-context)) 'link) 
1436                  (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1437           (while (looking-back " ") (backward-char))  
1438           (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1439
1440          ;; insert fresh link
1441          (t 
1442           (insert 
1443            (concat org-ref-default-citation-link 
1444                    ":" 
1445                    (mapconcat 'identity (reftex-citation t) ",")))))
1446
1447       ;; you pressed a C-u so we run this code
1448       (reftex-citation)))
1449   )
1450 #+END_SRC
1451
1452 #+RESULTS:
1453 : org-ref-insert-cite-link
1454
1455 *** Completion in cite links
1456 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.
1457
1458 #+BEGIN_SRC emacs-lisp  :tangle no
1459 (defun org-cite-complete-link (&optional arg)
1460   "Completion function for cite links"
1461   (format "%s:%s" 
1462           org-ref-default-citation-link
1463           (completing-read 
1464            "bibtex key: " 
1465            (let ((bibtex-files (org-ref-find-bibliography)))
1466              (bibtex-global-key-alist)))))
1467 #+END_SRC
1468
1469 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1470
1471 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1472 (defun org-ref-insert-cite-with-completion (type)
1473   "Insert a cite link with completion"
1474   (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1475   (insert (funcall (intern (format "org-%s-complete-link" type)))))
1476 #+END_SRC
1477
1478 ** Storing links to a bibtex entry
1479 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.
1480
1481 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1482 (defun org-ref-store-bibtex-entry-link ()
1483   "Save a citation link to the current bibtex entry. Saves in the default link type."
1484   (interactive)
1485   (let ((link (concat org-ref-default-citation-link 
1486                  ":"   
1487                  (save-excursion
1488                    (bibtex-beginning-of-entry)
1489                    (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1490     (message "saved %s" link)
1491     (push (list link) org-stored-links)
1492     (car org-stored-links)))
1493 #+END_SRC
1494
1495 ** An html bibliography
1496 This code provides some functions to generate a simple bibliography in html.
1497
1498 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1499 (defun org-ref-get-bibtex-keys ()
1500   "return a list of unique keys in the buffer"
1501   (interactive)
1502   (let ((keys '()))
1503     (org-element-map (org-element-parse-buffer) 'link
1504       (lambda (link)       
1505         (let ((plist (nth 1 link)))                          
1506           (when (-contains? org-ref-cite-types (plist-get plist ':type))
1507             (dolist 
1508                 (key 
1509                  (org-ref-split-and-strip-string (plist-get plist ':path)))
1510               (when (not (-contains? keys key))
1511                 (setq keys (append keys (list key)))))))))
1512     keys))
1513 #+END_SRC
1514
1515
1516 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1517 (defun org-ref-get-bibtex-entry-html (key)
1518  (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1519        (file) (entry))
1520
1521    (setq file (catch 'result
1522                 (loop for file in org-ref-bibliography-files do
1523                       (if (org-ref-key-in-file-p key (file-truename file)) 
1524                           (throw 'result file)))))
1525    (if file (with-temp-buffer
1526               (insert-file-contents file)
1527               (prog1
1528                   (bibtex-search-entry key nil 0)
1529                 (setq entry  (org-ref-bib-html-citation)))
1530               (format "<li><a id=\"%s\">[%s] %s</a></li>" key key entry)))))
1531 #+END_SRC
1532
1533
1534 #+BEGIN_SRC emacs-lisp :tangle org-ref.el 
1535 (defun org-ref-get-html-bibliography ()
1536   "Create an html bibliography when there are keys"
1537   (let ((keys (org-ref-get-bibtex-keys)))
1538     (when keys
1539       (concat "<h1>Bibliography</h1>
1540 <ul>"
1541               (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
1542               "\n</ul>"))))
1543 #+END_SRC
1544
1545 * Utilities
1546 ** create simple text citation from bibtex entry
1547
1548 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1549 (defun org-ref-bib-citation ()
1550   "from a bibtex entry, create and return a simple citation string."
1551
1552   (bibtex-beginning-of-entry)
1553   (let* ((cb (current-buffer))
1554          (bibtex-expand-strings t)
1555          (entry (loop for (key . value) in (bibtex-parse-entry t)
1556                       collect (cons (downcase key) value)))
1557          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1558          (year  (reftex-get-bib-field "year" entry))
1559          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1560          (key (reftex-get-bib-field "=key=" entry))
1561          (journal (reftex-get-bib-field "journal" entry))
1562          (volume (reftex-get-bib-field "volume" entry))
1563          (pages (reftex-get-bib-field "pages" entry))
1564          (doi (reftex-get-bib-field "doi" entry))
1565          (url (reftex-get-bib-field "url" entry))
1566          )
1567     ;;authors, "title", Journal, vol(iss):pages (year).
1568     (format "%s, \"%s\", %s, %s:%s (%s)"
1569             author title journal  volume pages year)))
1570 #+END_SRC
1571
1572 #+RESULTS:
1573 : org-ref-bib-citation
1574
1575
1576 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1577 (defun org-ref-bib-html-citation ()
1578   "from a bibtex entry, create and return a simple citation with html links."
1579
1580   (bibtex-beginning-of-entry)
1581   (let* ((cb (current-buffer))
1582          (bibtex-expand-strings t)
1583          (entry (loop for (key . value) in (bibtex-parse-entry t)
1584                       collect (cons (downcase key) value)))
1585          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1586          (year  (reftex-get-bib-field "year" entry))
1587          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1588          (key (reftex-get-bib-field "=key=" entry))
1589          (journal (reftex-get-bib-field "journal" entry))
1590          (volume (reftex-get-bib-field "volume" entry))
1591          (pages (reftex-get-bib-field "pages" entry))
1592          (doi (reftex-get-bib-field "doi" entry))
1593          (url (reftex-get-bib-field "url" entry))
1594          )
1595     ;;authors, "title", Journal, vol(iss):pages (year).
1596     (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1597                     author title journal  volume pages year)
1598             (when url (format " <a href=\"%s\">link</a>" url))
1599             (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1600     ))
1601 #+END_SRC
1602
1603 ** open pdf from bibtex
1604 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1605 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1606 (defun org-ref-open-bibtex-pdf ()
1607   "open pdf for a bibtex entry, if it exists. assumes point is in
1608 the entry of interest in the bibfile. but does not check that."
1609   (interactive)
1610   (save-excursion
1611     (bibtex-beginning-of-entry)
1612     (let* ((bibtex-expand-strings t)
1613            (entry (bibtex-parse-entry t))
1614            (key (reftex-get-bib-field "=key=" entry))
1615            (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1616       (message "%s" pdf)
1617       (if (file-exists-p pdf)
1618           (org-open-link-from-string (format "[[file:%s]]" pdf))
1619         (ding)))))
1620 #+END_SRC
1621
1622 ** open notes from bibtex
1623 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1624
1625 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1626 (defun org-ref-open-bibtex-notes ()
1627   "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1628
1629 I never did figure out how to use reftex to make this happen
1630 non-interactively. the reftex-format-citation function did not
1631 work perfectly; there were carriage returns in the strings, and
1632 it did not put the key where it needed to be. so, below I replace
1633 the carriage returns and extra spaces with a single space and
1634 construct the heading by hand."
1635   (interactive)
1636
1637   (bibtex-beginning-of-entry)
1638   (let* ((cb (current-buffer))
1639          (bibtex-expand-strings t)
1640          (entry (loop for (key . value) in (bibtex-parse-entry t)
1641                       collect (cons (downcase key) value)))
1642          (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1643          (year  (reftex-get-bib-field "year" entry))
1644          (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1645          (key (reftex-get-bib-field "=key=" entry))
1646          (journal (reftex-get-bib-field "journal" entry))
1647          (volume (reftex-get-bib-field "volume" entry))
1648          (pages (reftex-get-bib-field "pages" entry))
1649          (doi (reftex-get-bib-field "doi" entry))
1650          (url (reftex-get-bib-field "url" entry))
1651          )
1652
1653     ;; save key to clipboard to make saving pdf later easier by pasting.
1654     (with-temp-buffer
1655       (insert key)
1656       (kill-ring-save (point-min) (point-max)))
1657     
1658     ;; now look for entry in the notes file
1659     (if  org-ref-bibliography-notes
1660         (find-file org-ref-bibliography-notes)
1661       (error "org-ref-bib-bibliography-notes is not set to anything"))
1662     
1663     (goto-char (point-min))
1664     ;; put new entry in notes if we don't find it.
1665     (unless (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1666       (insert (format "\n** TODO %s - %s" year title))
1667       (insert (format"
1668  :PROPERTIES:
1669   :Custom_ID: %s
1670   :AUTHOR: %s
1671   :JOURNAL: %s
1672   :YEAR: %s
1673   :VOLUME: %s
1674   :PAGES: %s
1675   :DOI: %s
1676   :URL: %s
1677  :END:
1678 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1679 key author journal year volume pages doi url key org-ref-pdf-directory key))
1680 (save-buffer))))
1681 #+END_SRC
1682
1683 ** open url in browser from bibtex
1684
1685 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1686
1687 + 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.
1688
1689 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1690 (defun org-ref-open-in-browser ()
1691   "Open the bibtex entry at point in a browser using the url field or doi field"
1692 (interactive)
1693 (save-excursion
1694   (bibtex-beginning-of-entry)
1695   (catch 'done
1696     (let ((url (bibtex-autokey-get-field "url")))
1697       (when  url
1698         (browse-url url)
1699         (throw 'done nil)))
1700
1701     (let ((doi (bibtex-autokey-get-field "doi")))
1702       (when doi
1703         (if (string-match "^http" doi)
1704             (browse-url doi)
1705           (browse-url (format "http://dx.doi.org/%s" doi)))
1706         (throw 'done nil)))
1707     (message "No url or doi found"))))
1708 #+END_SRC
1709
1710 ** citeulike
1711    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.
1712
1713 *** function to upload bibtex to citeulike
1714
1715 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1716 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1717   "with point in  a bibtex entry get bibtex string and submit to citeulike.
1718
1719 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1720   (interactive)
1721   (message "uploading to citeulike")
1722   (save-restriction
1723     (bibtex-narrow-to-entry)
1724     (let ((startpos (point-min))
1725           (endpos (point-max))
1726           (bibtex-string (buffer-string))
1727           (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1728       (with-temp-buffer (insert bibtex-string)
1729                         (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1730 #+END_SRC
1731
1732 *** The upload script
1733 Here is the python script for uploading. 
1734
1735 *************** TODO document how to get the cookies
1736 *************** END
1737
1738
1739 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1740 #!python
1741 import pickle, requests, sys
1742
1743 # reload cookies
1744 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1745     cookies = pickle.load(f)
1746
1747 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1748
1749 bibtex = sys.stdin.read()
1750
1751 data = {'pasted':bibtex,
1752         'to_read':2,
1753         'tag_parsing':'simple',
1754         'strip_brackets':'no',
1755         'update_id':'bib-key',
1756         'btn_bibtex':'Import BibTeX file ...'}
1757
1758 headers = {'content-type': 'multipart/form-data',
1759            'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1760
1761 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1762 print r
1763 #+END_SRC
1764
1765 ** Build a pdf from a bibtex file
1766    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.
1767
1768 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1769 (defun org-ref-build-full-bibliography ()
1770   "build pdf of all bibtex entries, and open it."
1771   (interactive)
1772   (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1773         (bib-base (file-name-sans-extension bibfile))
1774         (texfile (concat bib-base ".tex"))
1775         (pdffile (concat bib-base ".pdf")))
1776     (find-file texfile)
1777     (erase-buffer)
1778     (insert (format "\\documentclass[12pt]{article}
1779 \\usepackage[version=3]{mhchem}
1780 \\usepackage{url}
1781 \\usepackage[numbers]{natbib}
1782 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1783 \\usepackage{doi}
1784 \\begin{document}
1785 \\nocite{*}
1786 \\bibliographystyle{unsrtnat}
1787 \\bibliography{%s}
1788 \\end{document}" bib-base))
1789     (save-buffer)
1790     (shell-command (concat "pdflatex " bib-base))
1791     (shell-command (concat "bibtex " bib-base))
1792     (shell-command (concat "pdflatex " bib-base))
1793     (shell-command (concat "pdflatex " bib-base))
1794     (kill-buffer texfile)
1795     (org-open-file pdffile)
1796     )) 
1797 #+END_SRC
1798
1799 ** Extract bibtex entries cited in an org-file
1800 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.
1801
1802 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1803 (defun org-ref-extract-bibtex-entries ()
1804   "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1805
1806 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1807   (interactive)
1808   (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1809          (tempname (make-temp-file "extract-bib"))
1810          (contents (buffer-string))
1811          (cb (current-buffer))
1812          basename texfile bibfile results)
1813     
1814     ;; open tempfile and insert org-buffer contents
1815     (find-file tempname)
1816     (insert contents)
1817     (setq basename (file-name-sans-extension 
1818                     (file-name-nondirectory buffer-file-name))
1819           texfile (concat tempname ".tex")
1820           bibfile (concat tempname ".bib"))
1821     
1822     ;; see if we have a bibliography, and insert the default one if not.
1823     (save-excursion
1824       (goto-char (point-min))
1825       (unless (re-search-forward "^bibliography:" (point-max) 'end)
1826         (insert (format "\nbibliography:%s" 
1827                         (mapconcat 'identity reftex-default-bibliography ",")))))
1828     (save-buffer)
1829
1830     ;; get a latex file and extract the references
1831     (org-latex-export-to-latex)
1832     (find-file texfile)
1833     (reftex-parse-all)
1834     (reftex-create-bibtex-file bibfile)
1835     (save-buffer)
1836     ;; save results of the references
1837     (setq results (buffer-string))
1838
1839     ;; kill buffers. these are named by basename, not full path
1840     (kill-buffer (concat basename ".bib"))
1841     (kill-buffer (concat basename ".tex"))
1842     (kill-buffer basename)
1843
1844     (delete-file bibfile)
1845     (delete-file texfile)
1846     (delete-file tempname)
1847
1848     ;; Now back to the original org buffer and insert the results
1849     (switch-to-buffer cb)
1850     (when (not (string= "" results))
1851       (save-excursion
1852         (goto-char (point-max))
1853         (insert "\n\n")
1854         (org-insert-heading)
1855         (insert (format " Bibtex entries
1856
1857 ,#+BEGIN_SRC text :tangle %s
1858 %s
1859 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
1860 #+END_SRC
1861
1862 ** Find bad cite links
1863 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.
1864
1865 #+BEGIN_SRC emacs-lisp  :tangle org-ref.el
1866 (require 'cl)
1867
1868 (defun index (substring list)
1869   "return the index of string in a list of strings"
1870   (let ((i 0)
1871         (found nil))
1872     (dolist (arg list i)
1873       (if (string-match (concat "^" substring "$") arg)
1874           (progn 
1875             (setq found t)
1876             (return i)))
1877       (setq i (+ i 1)))
1878     ;; return counter if found, otherwise return nil
1879     (if found i nil)))
1880
1881
1882 (defun org-ref-find-bad-citations ()
1883   "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
1884
1885 Makes a new buffer with clickable links."
1886   (interactive)
1887   ;; generate the list of bibtex-keys and cited keys
1888   (let* ((bibtex-files (org-ref-find-bibliography))
1889          (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
1890          (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
1891          (bad-citations '()))
1892
1893     (org-element-map (org-element-parse-buffer) 'link
1894       (lambda (link)       
1895         (let ((plist (nth 1 link)))                          
1896           (when (equal (plist-get plist ':type) "cite")
1897             (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
1898               (when (not (index key bibtex-keys))
1899                 (setq bad-citations (append bad-citations
1900                                             `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
1901                                                        key (buffer-name)(plist-get plist ':begin)))))
1902                 ))))))
1903
1904     (if bad-citations
1905       (progn
1906         (switch-to-buffer-other-window "*Missing citations*")
1907         (org-mode)
1908         (erase-buffer)
1909         (insert "* List of bad cite links\n")
1910         (insert (mapconcat 'identity bad-citations ""))
1911                                         ;(setq buffer-read-only t)
1912         (use-local-map (copy-keymap org-mode-map))
1913         (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
1914
1915       (when (get-buffer "*Missing citations*")
1916           (kill-buffer "*Missing citations*"))
1917       (message "No bad cite links found"))))
1918 #+END_SRC
1919
1920 ** Finding non-ascii characters
1921 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them. 
1922
1923 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1924 (defun org-ref-find-non-ascii-characters ()
1925   "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
1926   (interactive)
1927   (occur "[^[:ascii:]]"))
1928 #+END_SRC
1929
1930 ** Resort a bibtex entry
1931 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.
1932
1933 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1934 (defun org-ref-sort-bibtex-entry ()
1935   "sort fields of entry in standard order and downcase them"
1936   (interactive)
1937   (bibtex-beginning-of-entry)
1938   (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
1939          (entry (bibtex-parse-entry))
1940          (entry-fields)
1941          (other-fields)
1942          (type (cdr (assoc "=type=" entry)))
1943          (key (cdr (assoc "=key=" entry))))
1944
1945     ;; these are the fields we want to order that are in this entry
1946     (setq entry-fields (mapcar (lambda (x) (car x)) entry))
1947     ;; we do not want to reenter these fields
1948     (setq entry-fields (remove "=key=" entry-fields))
1949     (setq entry-fields (remove "=type=" entry-fields))
1950
1951     ;;these are the other fields in the entry
1952     (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
1953
1954     (cond
1955      ;; right now we only resort articles
1956      ((string= (downcase type) "article") 
1957       (bibtex-kill-entry)
1958       (insert
1959        (concat "@article{" key ",\n" 
1960                (mapconcat  
1961                 (lambda (field) 
1962                   (when (member field entry-fields)
1963                     (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
1964                (mapconcat 
1965                 (lambda (field) 
1966                   (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
1967                "\n}\n\n"))
1968       (bibtex-find-entry key)
1969       (bibtex-fill-entry)
1970       (bibtex-clean-entry)
1971        ))))
1972 #+END_SRC
1973
1974 ** Clean a bibtex entry
1975    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.
1976 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.
1977 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1978 (defun org-ref-clean-bibtex-entry(&optional keep-key)
1979   "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"
1980   (interactive "P")
1981   (bibtex-beginning-of-entry) 
1982 (end-of-line)
1983   ;; some entries do not have a key or comma in first line. We check and add it, if needed.
1984   (unless (string-match ",$" (thing-at-point 'line))
1985     (end-of-line)
1986     (insert ","))
1987
1988   ;; check for empty pages, and put eid or article id in its place
1989   (let ((entry (bibtex-parse-entry))
1990         (pages (bibtex-autokey-get-field "pages"))
1991         (year (bibtex-autokey-get-field "year"))
1992         (doi  (bibtex-autokey-get-field "doi"))
1993         ;; The Journal of Chemical Physics uses eid
1994         (eid (bibtex-autokey-get-field "eid")))
1995
1996     ;; replace http://dx.doi.org/ in doi. some journals put that in,
1997     ;; but we only want the doi.
1998     (when (string-match "^http://dx.doi.org/" doi)
1999       (bibtex-beginning-of-entry)
2000       (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2001       (bibtex-kill-field)
2002       (bibtex-make-field "doi")
2003       (backward-char)
2004       (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2005
2006     ;; asap articles often set year to 0, which messes up key
2007     ;; generation. fix that.
2008     (when (string= "0" year)  
2009       (bibtex-beginning-of-entry)
2010       (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2011       (bibtex-kill-field)
2012       (bibtex-make-field "year")
2013       (backward-char)
2014       (insert (read-string "Enter year: ")))
2015
2016     ;; fix pages if they are empty if there is an eid to put there.
2017     (when (string= "-" pages)
2018       (when eid   
2019         (bibtex-beginning-of-entry)
2020         ;; this seems like a clunky way to set the pages field.But I
2021         ;; cannot find a better way.
2022         (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2023         (bibtex-kill-field)
2024         (bibtex-make-field "pages")
2025         (backward-char)
2026         (insert eid)))
2027
2028     ;; replace naked & with \&
2029     (save-restriction
2030       (bibtex-narrow-to-entry)
2031       (bibtex-beginning-of-entry)
2032       (message "checking &")
2033       (replace-regexp " & " " \\\\& ")
2034       (widen))
2035
2036     ;; generate a key, and if it duplicates an existing key, edit it.
2037     (unless keep-key
2038       (let ((key (bibtex-generate-autokey)))
2039
2040         ;; first we delete the existing key
2041         (bibtex-beginning-of-entry)
2042         (re-search-forward bibtex-entry-maybe-empty-head)
2043         (if (match-beginning bibtex-key-in-head)
2044             (delete-region (match-beginning bibtex-key-in-head)
2045                            (match-end bibtex-key-in-head)))
2046         ;; check if the key is in the buffer
2047         (when (save-excursion
2048                 (bibtex-search-entry key))
2049           (save-excursion
2050             (bibtex-search-entry key)
2051             (bibtex-copy-entry-as-kill)
2052             (switch-to-buffer-other-window "*duplicate entry*")
2053             (bibtex-yank))
2054           (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2055
2056         (insert key)
2057         (kill-new key))) ;; save key for pasting            
2058
2059     ;; run hooks. each of these operates on the entry with no arguments.
2060     ;; this did not work like  i thought, it gives a symbolp error.
2061     ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2062     (mapcar (lambda (x)
2063               (save-restriction
2064                 (save-excursion
2065                   (funcall x))))
2066             org-ref-clean-bibtex-entry-hook)
2067     
2068     ;; sort fields within entry
2069     (org-ref-sort-bibtex-entry)
2070     ;; check for non-ascii characters
2071     (occur "[^[:ascii:]]")
2072     ))
2073 #+END_SRC
2074
2075 #+RESULTS:
2076 : org-ref-clean-bibtex-entry
2077
2078 ** Sort the entries in a citation link by year
2079 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2080
2081 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2082 (defun org-ref-get-citation-year (key)
2083   "get the year of an entry with key. Returns year as a string."
2084   (interactive)
2085   (let* ((results (org-ref-get-bibtex-key-and-file key))
2086          (bibfile (cdr results)))
2087     (with-temp-buffer
2088       (insert-file-contents bibfile)
2089       (bibtex-search-entry key nil 0)
2090       (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2091         ))))
2092
2093 (defun org-ref-sort-citation-link ()
2094  "replace link at point with sorted link by year"
2095  (interactive)
2096  (let* ((object (org-element-context))   
2097         (type (org-element-property :type object))
2098         (begin (org-element-property :begin object))
2099         (end (org-element-property :end object))
2100         (link-string (org-element-property :path object))
2101         keys years data)
2102   (setq keys (org-ref-split-and-strip-string link-string))
2103   (setq years (mapcar 'org-ref-get-citation-year keys)) 
2104   (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2105   (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2106   ;; now get the keys separated by commas
2107   (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2108   ;; and replace the link with the sorted keys
2109   (cl--set-buffer-substring begin end (concat type ":" keys))))
2110 #+END_SRC
2111
2112 ** Sort entries in citation links with shift-arrow keys
2113 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2114 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2115 (defun org-ref-swap-keys (i j keys)
2116  "swap the keys in a list with index i and j"
2117  (let ((tempi (nth i keys)))
2118    (setf (nth i keys) (nth j keys))
2119    (setf (nth j keys) tempi))
2120   keys)
2121
2122 (defun org-ref-swap-citation-link (direction)
2123  "move citation at point in direction +1 is to the right, -1 to the left"
2124  (interactive)
2125  (let* ((object (org-element-context))   
2126         (type (org-element-property :type object))
2127         (begin (org-element-property :begin object))
2128         (end (org-element-property :end object))
2129         (link-string (org-element-property :path object))
2130         key keys i)
2131    ;;   We only want this to work on citation links
2132    (when (-contains? org-ref-cite-types type)
2133         (setq key (org-ref-get-bibtex-key-under-cursor))
2134         (setq keys (org-ref-split-and-strip-string link-string))
2135         (setq i (index key keys))  ;; defined in org-ref
2136         (if (> direction 0) ;; shift right
2137             (org-ref-swap-keys i (+ i 1) keys)
2138           (org-ref-swap-keys i (- i 1) keys))   
2139         (setq keys (mapconcat 'identity keys ","))
2140         ;; and replace the link with the sorted keys
2141         (cl--set-buffer-substring begin end (concat type ":" keys))
2142         ;; now go forward to key so we can move with the key
2143         (re-search-forward key) 
2144         (goto-char (match-beginning 0)))))
2145
2146 ;; add hooks to make it work
2147 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2148 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2149 #+END_SRC
2150 * Aliases
2151 I like convenience. Here are some aliases for faster typing.
2152
2153 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2154 (defalias 'oro 'org-ref-open-citation-at-point)
2155 (defalias 'orc 'org-ref-citation-at-point)
2156 (defalias 'orp 'org-ref-open-pdf-at-point)
2157 (defalias 'oru 'org-ref-open-url-at-point)
2158 (defalias 'orn 'org-ref-open-notes-at-point)
2159
2160 (defalias 'orib 'org-ref-insert-bibliography-link)
2161 (defalias 'oric 'org-ref-insert-cite-link)
2162 (defalias 'orir 'org-ref-insert-ref-link)
2163 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2164
2165 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2166 #+END_SRC
2167 * End of code
2168 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2169 (provide 'org-ref)
2170 #+END_SRC
2171
2172
2173 * Build                                                            :noexport:
2174
2175 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2176
2177 [[elisp:(org-babel-load-file "org-ref.org")]]
2178
2179
2180