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