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