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