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