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