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