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