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