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