1 #+TITLE: Org-ref - The best reference handling for org-mode
7 This document is an experiment at creating a literate program to provide similar features as reftex for org-mode referencing. These features include:
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
15 Some additional features include
16 1. Get minibuffer messages for the cite/ref/label link under point
18 With helm integration (default) you can:
20 1. C-c ] to insert a citation link
22 - Enter to insert or append citation(s)
23 - C-u Enter to insert an alternative cite link
24 - C-u C-u Enter to replace the citation at point
25 2. C-u C-c ] to insert a ref link with helm completion
26 3. C-u C-u C-c ] to insert a label with completion
27 4. M-x org-ref to get a helm completion buffer with link checks, utilities and export options
30 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
31 ;;; org-ref.el --- setup bibliography, cite, ref and label org-mode links.
33 ;; Copyright(C) 2014 John Kitchin
35 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
36 ;; This file is not currently part of GNU Emacs.
38 ;; This program is free software; you can redistribute it and/or
39 ;; modify it under the terms of the GNU General Public License as
40 ;; published by the Free Software Foundation; either version 2, or (at
41 ;; your option) any later version.
43 ;; This program is distributed in the hope that it will be useful, but
44 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
45 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
46 ;; General Public License for more details.
48 ;; You should have received a copy of the GNU General Public License
49 ;; along with this program ; see the file COPYING. If not, write to
50 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
51 ;; Boston, MA 02111-1307, USA.
55 ;; Lisp code to setup bibliography cite, ref and label org-mode links. also
56 ;; sets up reftex and helm for org-mode citations. The links are clickable and
57 ;; do things that are useful. You should really read org-ref.org for details.
59 ;; Package-Requires: ((dash) (helm) (helm-bibtex))
63 The only external require is reftex-cite
65 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
66 (require 'reftex-cite)
69 (require 'helm-bibtex)
73 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.
75 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
77 "customization group for org-ref")
79 (defcustom org-ref-bibliography-notes
81 "filename to where you will put all your notes about an entry in
82 the default bibliography."
86 (defcustom org-ref-default-bibliography
88 "list of bibtex files to search for. You should use full-paths for each file."
89 :type '(repeat :tag "List of bibtex files" file)
92 (defcustom org-ref-pdf-directory
94 "directory where pdfs are stored by key. put a trailing / in"
98 (defcustom org-ref-default-citation-link
100 "The default type of citation link to use"
104 (defcustom org-ref-insert-cite-key
106 "Keyboard shortcut to insert a citation."
110 (defcustom org-ref-bibliography-entry-format
111 '(("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>.")
113 ("book" . "%a, %t, %u (%y).")
115 ("proceedings" . "%e, %t in %S, %u (%y).")
117 ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
119 "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."
123 (defcustom org-ref-open-notes-function
129 ;;(org-tree-to-indirect-buffer)
130 (outline-previous-visible-heading 1)
131 (recenter-top-bottom 0))
132 "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"
137 (defcustom org-ref-open-pdf-function
138 'org-ref-open-pdf-at-point
139 "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'."
144 (defcustom org-ref-insert-cite-function
145 'org-ref-helm-insert-cite-link
146 "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."
151 (defcustom org-ref-cite-onclick-function
152 'org-ref-cite-click-helm
153 "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."
157 (defcustom org-ref-show-citation-on-enter t
158 "If non-nil add a hook function to show the citation summary in
159 the minibuffer just by putting the cursor in a link"
164 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.
166 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
167 (defcustom org-ref-cite-types
168 '("cite" "nocite" ;; the default latex cite commands
169 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
170 "citet" "citet*" "citep" "citep*"
171 "citealt" "citealt*" "citealp" "citealp*"
173 "citeauthor" "citeauthor*"
174 "citeyear" "citeyear*"
175 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
177 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
179 "parencite" "Parencite"
180 "footcite" "footcitetext"
181 "textcite" "Textcite"
182 "smartcite" "Smartcite"
183 "cite*" "parencite*" "supercite"
184 "autocite" "Autocite" "autocite*" "Autocite*"
186 "citetitle" "citetitle*"
187 "citedate" "citedate*"
189 "fullcite" "footfullcite"
190 ;; "volcite" "Volcite" cannot support the syntax
191 "notecite" "Notecite"
192 "pnotecite" "Pnotecite"
194 ;; multicites. Very limited support for these.
195 "cites" "Cites" "parencites" "Parencites"
196 "footcites" "footcitetexts"
197 "smartcites" "Smartcites" "textcites" "Textcites"
198 "supercites" "autocites" "Autocites"
199 ;; for the bibentry package
202 "List of citation types known in org-ref"
203 :type '(repeat :tag "List of citation types" string)
207 We need a hook variable to store user-defined bibtex entry cleaning functions
208 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
209 (defcustom org-ref-clean-bibtex-entry-hook nil
210 "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
216 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
217 (defvar org-ref-bibliography-files
219 "variable to hold bibliography files to be searched")
222 ** org-mode / reftex setup
224 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.
226 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
228 (defun org-mode-reftex-setup ()
229 (and (buffer-file-name)
230 (file-exists-p (buffer-file-name))
231 (global-auto-revert-mode t)
232 ;; I do not remember why I put this next line in. It doesn't
233 ;; work for org-files. Nothing very bad happens, but it gives
234 ;; an annoying error. Commenting it out for now.
237 (make-local-variable 'reftex-cite-format)
238 (setq reftex-cite-format 'org))
240 ;; define key for inserting citations
241 (define-key org-mode-map
242 (kbd org-ref-insert-cite-key)
243 org-ref-insert-cite-function)
245 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
247 (eval-after-load 'reftex-vars
249 (add-to-list 'reftex-cite-format-builtin
250 '(org "Org-mode citation"
251 ((?\C-m . "cite:%l") ; default
252 (?d . ",%l") ; for appending
258 (?h . "citeauthor:%l")
259 (?H . "citeauthor*:%l")
266 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.
268 #+BEGIN_SRC emacs-lisp :tangle no
270 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
271 (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l")
272 (?z . "newcite:%l"))))
275 You can define a new citation link like this:
276 #+BEGIN_SRC emacs-lisp :tangle no
277 (org-ref-define-citation-link "citez" ?z)
280 ** Messages for link at cursor
281 Here we setup code that shows you a context message for the element under the cursor when emacs is idle.
282 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
283 (defvar org-ref-message-timer nil
284 "Variable to store the link message timer in.")
287 (defun org-ref-show-link-messages ()
288 "Turn on link messages. You will see a message in the
289 minibuffer when on a cite, ref or label link."
291 (or org-ref-message-timer
292 (setq org-ref-message-timer
293 (run-with-idle-timer 0.5 t 'org-ref-link-message))))
296 (defun org-ref-cancel-link-messages ()
297 "Stop showing messages in minibuffer when on a link."
299 (cancel-timer org-ref-message-timer)
300 (setq org-ref-message-timer nil))
303 (when org-ref-show-citation-on-enter
304 (org-ref-show-link-messages))
306 ;; this approach caused the selected region to not be highlighted any more.
307 ; (add-hook 'post-command-hook 'org-ref-link-message))
308 ; (remove-hook 'post-command-hook 'org-ref-link-message))
311 ** Messages for context under mouse pointer
312 Sometimes, when reading a document, I actually use the mouse more than the cursor. This code enables the mouse cursor to trigger a message in the minibuffer about what is under the cursor. I run this on a timer.
314 The basic idea here is to get the mouse position, and if we can determine there is a character that (point) can move to, we move (point) and run the org-ref-link-message function. Since this runs on a timer, we store the last mouse position, and only run the function when the mouse has moved to avoid getting messages every time the timer runs.
316 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
317 (defvar org-ref-last-mouse-pos nil
318 "Stores last mouse position for use in `org-ref-mouse-message'.")
320 (defun org-ref-can-move-p ()
321 "See if a character is under the mouse. If so return the position for `goto-char'."
322 (let* ((line (cddr org-ref-last-mouse-pos))
323 (col (cadr org-ref-last-mouse-pos)))
325 (goto-char (window-start))
328 (> (- (line-end-position) (line-beginning-position)) col)
329 (progn (forward-char col) (point))
333 (defun org-ref-mouse-message ()
334 "Display message for link under mouse cursor"
336 (when (not (equal (mouse-position) org-ref-last-mouse-pos))
337 (setq org-ref-last-mouse-pos (mouse-position))
338 (let ((p (org-ref-can-move-p)))
342 (org-ref-link-message))))))
345 (defvar org-ref-message-timer-mouse nil
346 "Store mouse timer.")
349 (defvar org-ref-mouse-message-interval 0.5
350 "How often to run the mouse message timer in seconds")
353 (defun org-ref-mouse-messages-on ()
354 "Turn on mouse messages."
356 (or org-ref-message-timer-mouse
357 (setq org-ref-message-timer-mouse
358 (run-at-time "0.5 sec"
359 org-ref-mouse-message-interval
360 'org-ref-mouse-message))))
363 (defun org-ref-mouse-messages-off ()
364 "Turn off mouse messages"
366 (cancel-timer org-ref-message-timer-mouse)
367 (setq org-ref-message-timer-mouse nil)
368 (message "Mouse messages are off"))
372 : org-ref-mouse-messages-off
375 Here we make the org-ref links a different color.
383 cite:sokalski-2012-optim-ta,zhang-2011-spatial-tio2,li-2012-heter-ceram,li-2013-photoc
385 cite*:sokalski-2012-optim-ta,zhang-2011-spatial-tio2,li-2012-heter-ceram,li-2013-photoc
387 citenum:sokalski-2012-optim-ta,zhang-2011-spatial-tio2,li-2012-heter-ceram,li-2013-photoc
393 #+BEGIN_SRC emacs-lisp
394 (defcustom org-ref-colorize-links
396 "When non-nil, change colors of links"
400 (defcustom org-ref-cite-color
402 "Color of cite like links"
406 (defcustom org-ref-ref-color
408 "Color of ref like links"
412 (defcustom org-ref-label-color
414 "Color of label links"
418 (defvar org-ref-cite-re nil
419 "regexp for cite links")
422 (setq org-ref-cite-re
423 (concat "\\(" (mapconcat 'identity org-ref-cite-types "\\|") "\\)"
424 ":\\([a-zA-Z0-9-_:]*,?\\)*"))
427 (setq org-ref-label-re
428 "label:\\([a-zA-Z0-9-_:]*,?\\)*")
432 "ref:\\([a-zA-Z0-9-_:]*,?\\)*")
435 (defface org-ref-cite-face
436 `((t (:inherit org-link :foreground ,org-ref-cite-color)))
437 "Color for cite links")
439 (defface org-ref-label-face
440 `((t (:inherit org-link :foreground ,org-ref-label-color)))
441 "Color for cite links")
443 (defface org-ref-ref-face
444 `((t (:inherit org-link :foreground ,org-ref-ref-color)))
445 "Color for cite links")
447 (when org-ref-colorize-links
448 (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
449 (highlight-regexp org-ref-label-re 'org-ref-label-face)
450 (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
457 Most of this library is the creation of functional links to help with references and citations.
459 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.
461 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
462 (defun org-ref-strip-string (string)
463 "strip leading and trailing whitespace from the string"
464 (replace-regexp-in-string
465 (concat search-whitespace-regexp "$" ) ""
466 (replace-regexp-in-string
467 (concat "^" search-whitespace-regexp ) "" string)))
470 It is helpful to make the previous function operate on a list of strings here.
472 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
473 (defun org-ref-split-and-strip-string (string)
474 "split key-string and strip keys. Assumes the key-string is comma delimited"
475 (mapcar 'org-ref-strip-string (split-string string ",")))
478 ** bibliography and bibliographystyle
479 *** An html bibliography
481 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.
483 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
484 (defun org-ref-reftex-get-bib-field (field entry &optional format)
485 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
487 (setq result (reftex-get-bib-field field entry format))
488 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
489 (setq result (substring result 1 -1)))
490 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
491 (setq result (substring result 1 -1)))
494 (defun org-ref-reftex-format-citation (entry format)
495 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
496 to the format argument. The format is a string with these percent escapes.
498 In the format, the following percent escapes will be expanded.
500 %l The BibTeX label of the citation.
501 %a List of author names, see also `reftex-cite-punctuation'.
502 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
503 %A First author name only.
504 %e Works like %a, but on list of editor names. (%2e and %E work a well)
506 It is also possible to access all other BibTeX database fields:
507 %b booktitle %c chapter %d edition %h howpublished
508 %i institution %j journal %k key %m month
509 %n number %o organization %p pages %P first page
510 %r address %s school %u publisher %t title
512 %B booktitle, abbreviated %T title, abbreviated
517 Usually, only %l is needed. The other stuff is mainly for the echo area
518 display, and for (setq reftex-comment-citations t).
520 %< as a special operator kills punctuation and space around it after the
521 string has been formatted.
523 A pair of square brackets indicates an optional argument, and RefTeX
524 will prompt for the values of these arguments.
526 Beware that all this only works with BibTeX database files. When
527 citations are made from the \bibitems in an explicit thebibliography
528 environment, only %l is available."
529 ;; Format a citation from the info in the BibTeX ENTRY
531 (unless (stringp format) (setq format "\\cite{%l}"))
533 (if (and reftex-comment-citations
534 (string-match "%l" reftex-cite-comment-format))
535 (error "reftex-cite-comment-format contains invalid %%l"))
538 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
540 (let ((n (string-to-number (match-string 4 format)))
541 (l (string-to-char (match-string 5 format)))
547 (org-ref-reftex-get-bib-field "&key" entry)
548 (if reftex-comment-citations
549 reftex-cite-comment-format
551 ((= l ?a) (reftex-format-names
552 (reftex-get-bib-names "author" entry)
554 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
555 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
556 ((= l ?B) (reftex-abbreviate-title
557 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
558 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
559 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
560 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
561 ((= l ?e) (reftex-format-names
562 (reftex-get-bib-names "editor" entry)
564 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
565 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
566 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
567 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
568 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
569 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
570 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
571 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
572 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
573 ((= l ?P) (car (split-string
574 (org-ref-reftex-get-bib-field "pages" entry)
576 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
577 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
578 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
579 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
580 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
581 ;; strip enclosing brackets from title if they are there
582 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
583 ((= l ?T) (reftex-abbreviate-title
584 (org-ref-reftex-get-bib-field "title" entry)))
585 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
586 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
589 (setq b (match-beginning 2) e (match-end 2))
590 (setq b (match-beginning 3) e (match-end 3)))
591 (setq format (concat (substring format 0 b) rpl (substring format e)))))
592 (while (string-match "%%" format)
593 (setq format (replace-match "%" t t format)))
594 (while (string-match "[ ,.;:]*%<" format)
595 (setq format (replace-match "" t t format)))
596 ;; also replace carriage returns, tabs, and multiple whitespaces
597 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
600 (defun org-ref-get-bibtex-entry-citation (key)
601 "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
603 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
604 (file) (entry) (bibtex-entry) (entry-type) (format))
606 (setq file (catch 'result
607 (loop for file in org-ref-bibliography-files do
608 (if (org-ref-key-in-file-p key (file-truename file))
610 (message "%s not found in %s" key (file-truename file))))))
613 (insert-file-contents file)
614 (bibtex-search-entry key nil 0)
615 (setq bibtex-entry (bibtex-parse-entry))
616 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
617 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
619 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
621 (bibtex-narrow-to-entry)
622 (setq entry (buffer-string)))))
627 : org-ref-reftex-format-citation
629 Here is how to use the function. You call it with point in an entry in a bibtex file.
631 #+BEGIN_SRC emacs-lisp :tangle no
632 (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>."))
633 (org-ref-get-bibtex-entry-citation "armiento-2014-high"))
636 : 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>.
638 I am not sure why full author names are not used.
640 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
642 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
643 (defun org-ref-get-bibtex-keys ()
644 "Return a list of unique keys in the buffer."
646 (org-element-map (org-element-parse-buffer) 'link
648 (let ((plist (nth 1 link)))
649 (when (-contains? org-ref-cite-types (plist-get plist ':type))
652 (org-ref-split-and-strip-string (plist-get plist ':path)))
653 (when (not (-contains? keys key))
654 (setq keys (append keys (list key))))))))
655 ;; set with-affiliated to get keys in captions
657 ;; Sort keys alphabetically
658 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
662 This function gets the html for one entry.
664 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
665 (defun org-ref-get-bibtex-entry-html (key)
666 "returns an html string for the bibliography entry corresponding to key"
668 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
671 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
673 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
674 (defun org-ref-get-html-bibliography ()
675 "Create an html bibliography when there are keys"
676 (let ((keys (org-ref-get-bibtex-keys)))
678 (concat "<h1>Bibliography</h1>
680 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
684 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.
686 *** An org bibliography
687 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.
689 First, we get the string for a single entry.
690 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
691 (defun org-ref-get-bibtex-entry-org (key)
692 "returns an org string for the bibliography entry corresponding to key"
693 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
694 (file) (entry) (bibtex-entry) (entry-type) (format))
696 (setq file (catch 'result
697 (loop for file in org-ref-bibliography-files do
698 (if (org-ref-key-in-file-p key (file-truename file))
700 (message "%s not found in %s" key (file-truename file))))))
703 (insert-file-contents file)
704 (bibtex-search-entry key nil 0)
705 (setq entry (bibtex-parse-entry))
710 " (org-ref-reftex-get-bib-field "author" entry)
711 (org-ref-reftex-get-bib-field "title" entry)
712 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
713 (mapconcat (lambda (element) (format " :%s: %s"
714 (upcase (car element))
720 Now, we loop over the keys, and combine all the entries into a bibliography.
721 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
722 (defun org-ref-get-org-bibliography ()
723 "Create an org bibliography when there are keys"
724 (let ((keys (org-ref-get-bibtex-keys)))
726 (concat "* Bibliography
728 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
732 *** An ascii bibliography
734 This function gets the html for one entry.
736 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
737 (defun org-ref-get-bibtex-entry-ascii (key)
738 "returns an ascii string for the bibliography entry corresponding to key"
740 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
743 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
745 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
746 (defun org-ref-get-ascii-bibliography ()
747 "Create an html bibliography when there are keys"
748 (let ((keys (org-ref-get-bibtex-keys)))
754 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
760 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.
762 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
763 (org-add-link-type "bibliography"
764 ;; this code is run on clicking. The bibliography
765 ;; may contain multiple files. this code finds the
766 ;; one you clicked on and opens it.
767 (lambda (link-string)
768 ;; get link-string boundaries
769 ;; we have to go to the beginning of the line, and then search forward
772 ;; object is the link you clicked on
773 (object (org-element-context))
774 (link-string-beginning)
778 (goto-char (org-element-property :begin object))
779 (search-forward link-string nil nil 1)
780 (setq link-string-beginning (match-beginning 0))
781 (setq link-string-end (match-end 0)))
783 ;; We set the reftex-default-bibliography
784 ;; here. it should be a local variable only in
785 ;; the current buffer. We need this for using
786 ;; reftex to do citations.
787 (set (make-local-variable 'reftex-default-bibliography)
788 (split-string (org-element-property :path object) ","))
790 ;; now if we have comma separated bibliographies
791 ;; we find the one clicked on. we want to
792 ;; search forward to next comma from point
794 (if (search-forward "," link-string-end 1 1)
795 (setq key-end (- (match-end 0) 1)) ; we found a match
796 (setq key-end (point)))) ; no comma found so take the point
797 ;; and backward to previous comma from point
799 (if (search-backward "," link-string-beginning 1 1)
800 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
801 (setq key-beginning (point)))) ; no match found
802 ;; save the key we clicked on.
803 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
804 (find-file bibfile))) ; open file on click
807 (lambda (keyword desc format)
809 ((eq format 'org) (org-ref-get-org-bibliography))
810 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
811 ((eq format 'html) (org-ref-get-html-bibliography))
813 ;; write out the latex bibliography command
814 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
815 (mapcar 'expand-file-name
816 (split-string keyword ","))
821 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.
824 \input{project-description.bbl}
827 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.
829 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
830 (org-add-link-type "nobibliography"
831 ;; this code is run on clicking. The bibliography
832 ;; may contain multiple files. this code finds the
833 ;; one you clicked on and opens it.
834 (lambda (link-string)
835 ;; get link-string boundaries
836 ;; we have to go to the beginning of the line, and then search forward
839 ;; object is the link you clicked on
840 (object (org-element-context))
842 (link-string-beginning)
846 (goto-char (org-element-property :begin object))
847 (search-forward link-string nil nil 1)
848 (setq link-string-beginning (match-beginning 0))
849 (setq link-string-end (match-end 0)))
851 ;; We set the reftex-default-bibliography
852 ;; here. it should be a local variable only in
853 ;; the current buffer. We need this for using
854 ;; reftex to do citations.
855 (set (make-local-variable 'reftex-default-bibliography)
856 (split-string (org-element-property :path object) ","))
858 ;; now if we have comma separated bibliographies
859 ;; we find the one clicked on. we want to
860 ;; search forward to next comma from point
862 (if (search-forward "," link-string-end 1 1)
863 (setq key-end (- (match-end 0) 1)) ; we found a match
864 (setq key-end (point)))) ; no comma found so take the point
865 ;; and backward to previous comma from point
867 (if (search-backward "," link-string-beginning 1 1)
868 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
869 (setq key-beginning (point)))) ; no match found
870 ;; save the key we clicked on.
871 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
872 (find-file bibfile))) ; open file on click
875 (lambda (keyword desc format)
877 ((eq format 'org) (org-ref-get-org-bibliography))
878 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
879 ((eq format 'html) (org-ref-get-html-bibliography))
881 ;; write out the latex bibliography command
883 ; (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
884 ; (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
885 ; (mapcar 'expand-file-name
886 ; (split-string keyword ","))
889 (format "\\nobibliography{%s}"
890 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
891 (mapcar 'expand-file-name
892 (split-string keyword ","))
898 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
899 (org-add-link-type "printbibliography"
900 (lambda (arg) (message "Nothing implemented for clicking here."))
901 (lambda (keyword desc format)
903 ((eq format 'org) (org-ref-get-org-bibliography))
904 ((eq format 'html) (org-ref-get-html-bibliography))
906 ;; write out the biblatex bibliography command
907 "\\printbibliography"))
911 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, ...
913 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
914 (org-add-link-type "bibliographystyle"
915 (lambda (arg) (message "Nothing implemented for clicking here."))
916 (lambda (keyword desc format)
919 ;; write out the latex bibliography command
920 (format "\\bibliographystyle{%s}" keyword)))))
923 *** Completion for bibliography link
926 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
927 (defun org-bibliography-complete-link (&optional arg)
928 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
930 (defun org-ref-insert-bibliography-link ()
931 "insert a bibliography with completion"
933 (insert (org-bibliography-complete-link)))
937 This is apparently used for biblatex.
938 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
939 (org-add-link-type "addbibresource"
940 ;; this code is run on clicking. The addbibresource
941 ;; may contain multiple files. this code finds the
942 ;; one you clicked on and opens it.
943 (lambda (link-string)
944 ;; get link-string boundaries
945 ;; we have to go to the beginning of the line, and then search forward
948 ;; object is the link you clicked on
949 (object (org-element-context))
951 (link-string-beginning)
955 (goto-char (org-element-property :begin object))
956 (search-forward link-string nil nil 1)
957 (setq link-string-beginning (match-beginning 0))
958 (setq link-string-end (match-end 0)))
960 ;; We set the reftex-default-addbibresource
961 ;; here. it should be a local variable only in
962 ;; the current buffer. We need this for using
963 ;; reftex to do citations.
964 (set (make-local-variable 'reftex-default-addbibresource)
965 (split-string (org-element-property :path object) ","))
967 ;; now if we have comma separated bibliographies
968 ;; we find the one clicked on. we want to
969 ;; search forward to next comma from point
971 (if (search-forward "," link-string-end 1 1)
972 (setq key-end (- (match-end 0) 1)) ; we found a match
973 (setq key-end (point)))) ; no comma found so take the point
974 ;; and backward to previous comma from point
976 (if (search-backward "," link-string-beginning 1 1)
977 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
978 (setq key-beginning (point)))) ; no match found
979 ;; save the key we clicked on.
980 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
981 (find-file bibfile))) ; open file on click
984 (lambda (keyword desc format)
986 ((eq format 'html) (format "")); no output for html
988 ;; write out the latex addbibresource command
989 (format "\\addbibresource{%s}" keyword)))))
994 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.
996 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
997 (defun org-ref-list-of-figures (&optional arg)
998 "Generate buffer with list of figures in them"
1000 (save-excursion (widen)
1001 (let* ((c-b (buffer-name))
1004 (org-element-map (org-element-parse-buffer) 'link
1006 "create a link for to the figure"
1008 (and (string= (org-element-property :type link) "file")
1010 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
1011 (org-element-property :path link)))
1014 (let* ((start (org-element-property :begin link))
1015 (parent (car (cdr (org-element-property :parent link))))
1016 (caption (caaar (plist-get parent :caption)))
1017 (name (plist-get parent :name)))
1020 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
1021 c-b start counter (or name "") caption)
1023 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
1024 c-b start counter (or name "")))))))))
1025 (switch-to-buffer "*List of Figures*")
1026 (setq buffer-read-only nil)
1029 (insert (mapconcat 'identity list-of-figures ""))
1030 (setq buffer-read-only t)
1031 (use-local-map (copy-keymap org-mode-map))
1032 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
1036 'org-ref-list-of-figures ; on click
1037 (lambda (keyword desc format)
1040 (format "\\listoffigures")))))
1045 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1046 (defun org-ref-list-of-tables (&optional arg)
1047 "Generate a buffer with a list of tables"
1051 (let* ((c-b (buffer-name))
1054 (org-element-map (org-element-parse-buffer 'element) 'table
1056 "create a link for to the table"
1058 (let ((start (org-element-property :begin table))
1059 (name (org-element-property :name table))
1060 (caption (caaar (org-element-property :caption table))))
1063 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
1064 c-b start counter (or name "") caption)
1066 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
1067 c-b start counter (or name ""))))))))
1068 (switch-to-buffer "*List of Tables*")
1069 (setq buffer-read-only nil)
1072 (insert (mapconcat 'identity list-of-tables ""))
1073 (setq buffer-read-only t)
1074 (use-local-map (copy-keymap org-mode-map))
1075 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
1079 'org-ref-list-of-tables
1080 (lambda (keyword desc format)
1083 (format "\\listoftables")))))
1087 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.
1089 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1090 (defun org-ref-count-labels (label)
1091 "Counts number of matches for label in the document"
1092 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
1093 ;; for tblname, it is not enough to get word boundary
1094 ;; tab-little and tab-little-2 match then.
1095 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
1096 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
1097 ;; this is the org-format #+label:
1098 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
1099 (let ((custom-id-count 0))
1102 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
1103 (setq custom-id-count (+ 1 custom-id-count)))))
1109 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
1110 (let ((count (org-ref-count-labels label)))
1111 (message (format "%s occurence%s"
1117 (org-ref-count-labels label))))
1118 (lambda (keyword desc format)
1120 ((eq format 'html) (format "(<label>%s</label>)" path))
1122 (format "\\label{%s}" keyword)))))
1125 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.
1127 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1128 (defun org-label-store-link ()
1129 "store a link to a label. The output will be a ref to that label"
1130 ;; First we have to make sure we are on a label link.
1131 (let* ((object (org-element-context)))
1132 (when (and (equal (org-element-type object) 'link)
1133 (equal (org-element-property :type object) "label"))
1134 (org-store-link-props
1136 :link (concat "ref:" (org-element-property :path object))))
1138 ;; Store link on table
1139 (when (equal (org-element-type object) 'table)
1140 (org-store-link-props
1142 :link (concat "ref:" (org-element-property :name object))))
1144 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
1145 ;; store link on heading with custom_id
1146 ; (when (and (equal (org-element-type object) 'headline)
1147 ; (org-entry-get (point) "CUSTOM_ID"))
1148 ; (org-store-link-props
1150 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
1152 ;; and to #+label: lines
1153 (when (and (equal (org-element-type object) 'paragraph)
1154 (org-element-property :name object))
1155 (org-store-link-props
1157 :link (concat "ref:" (org-element-property :name object))))
1160 (add-hook 'org-store-link-functions 'org-label-store-link)
1164 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.
1166 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
1168 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1172 "on clicking goto the label. Navigate back with C-c &"
1173 (org-mark-ring-push)
1174 ;; next search from beginning of the buffer
1176 ;; it is possible you would not find the label if narrowing is in effect
1183 (goto-char (point-min))
1184 (re-search-forward (format "label:%s\\b" label) nil t))
1188 (goto-char (point-min))
1189 (re-search-forward (format "\\label{%s}" label) nil t))
1191 ;; #+label: name org-definition
1193 (goto-char (point-min))
1194 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1198 (goto-char (point-min))
1199 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1201 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1202 ;; you need [[#label]] links.
1205 ; (goto-char (point-min))
1206 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1208 ;; we did not find anything, so go back to where we came
1209 (org-mark-ring-goto)
1210 (error "%s not found" label))
1212 (message "go back with (org-mark-ring-goto) `C-c &`"))
1214 (lambda (keyword desc format)
1216 ((eq format 'html) (format "(<ref>%s</ref>)" path))
1218 (format "\\ref{%s}" keyword)))))
1221 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.
1223 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1224 (defun org-ref-get-org-labels ()
1225 "Return a list of #+LABEL: labels."
1227 (goto-char (point-min))
1228 (let ((matches '()))
1229 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1230 (add-to-list 'matches (match-string-no-properties 1) t))
1234 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1235 (defun org-ref-get-custom-ids ()
1236 "Return a list of custom_id properties in the buffer."
1237 (let ((results '()) custom_id)
1240 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1241 (when (not (null custom_id))
1242 (setq results (append results (list custom_id)))))))
1246 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
1247 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1248 (defun org-ref-get-latex-labels ()
1250 (goto-char (point-min))
1251 (let ((matches '()))
1252 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1253 (add-to-list 'matches (match-string-no-properties 1) t))
1257 Finally, we get the table names.
1259 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1260 (defun org-ref-get-tblnames ()
1261 "Return list of table names in the buffer."
1262 (org-element-map (org-element-parse-buffer 'element) 'table
1264 (org-element-property :name table))))
1267 Now, we can put all the labels together which will give us a list of candidates.
1269 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1270 (defun org-ref-get-labels ()
1271 "Returns a list of labels in the buffer that you can make a ref link to.
1272 This is used to auto-complete ref links and in helm menus."
1276 (goto-char (point-min))
1277 (let ((matches '()))
1278 ;; these are the label:stuff kinds
1279 (while (re-search-forward "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1280 (add-to-list 'matches (match-string-no-properties 1) t))
1282 (org-ref-get-org-labels)
1283 (org-ref-get-latex-labels)
1284 (org-ref-get-tblnames)
1285 (org-ref-get-custom-ids))))))
1288 Let us make a helm function to insert a label link. This will help you enter unique labels by showing matching labels until they are all gone and you are left with a unique one. If you are on a link, it means you want to replace it.
1289 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1290 (defun org-ref-helm-insert-label-link ()
1291 "Insert a label link. helm just shows you what labels already exist.
1292 If you are on a label link, replace it."
1294 (let* ((labels (org-ref-get-labels))
1295 (cb (current-buffer)))
1296 (helm :sources `(((name . "Existing labels")
1297 (candidates . ,labels)
1298 ;; default action is to open to the label
1299 (action . (lambda (label)
1300 ;; unfortunately I do not have markers here
1301 (org-open-link-from-string (format "ref:%s" label))))
1302 ;; if you select a label, replace current one
1303 (action . (lambda (label)
1304 (switch-to-buffer ,cb)
1306 ;; no prefix or on a link
1307 ((equal helm-current-prefix-arg nil)
1308 (let* ((object (org-element-context))
1309 (last-char (save-excursion
1310 (goto-char (org-element-property :end object))
1312 (if (looking-at " ")
1315 (when (-contains? '("label")
1316 (org-element-property :type object))
1317 ;; we are on a link, so replace it.
1320 (org-element-property :begin object)
1321 (org-element-property :end object))
1323 (replace-regexp-in-string
1324 (org-element-property :path object)
1326 (org-element-property :raw-link object))
1328 ;; no prefix options defined
1330 ;; no matching selection creates a new label
1331 ((name . "Create new label")
1333 ;; default action creates a new label, or replaces old one
1334 (action . (lambda (label)
1335 (switch-to-buffer ,cb)
1336 (let* ((object (org-element-context))
1337 (last-char (save-excursion
1338 (goto-char (org-element-property :end object))
1340 (if (looking-at " ")
1343 (if (-contains? '("label")
1344 (org-element-property :type object))
1345 ;; we are on a link, so replace it.
1348 (org-element-property :begin object)
1349 (org-element-property :end object))
1351 (replace-regexp-in-string
1352 (org-element-property :path object)
1354 (org-element-property :raw-link object))
1361 helm-pattern))))))))))))
1364 Now we create a 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.
1366 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1367 (defun org-ref-complete-link (&optional arg)
1368 "Completion function for ref links"
1370 (setq label (completing-read "label: " (org-ref-get-labels)))
1371 (format "ref:%s" label)))
1374 Alternatively, you may want to just call a function that inserts a link with completion:
1376 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1377 (defun org-ref-insert-ref-link ()
1379 (insert (org-ref-complete-link)))
1382 Another alternative ref insertion is to use helm.
1384 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1385 (defun org-ref-helm-insert-ref-link ()
1386 "Helm menu to insert ref links to labels in the document.
1387 If you are on link, replace with newly selected label.
1388 Use C-u to insert a different kind of ref link.
1389 Use C-u C-u to insert a [[#custom-id]] link
1392 (let* ((labels (org-ref-get-labels))
1393 (bs (buffer-string))
1394 (contexts (with-temp-buffer
1396 (mapcar 'org-ref-get-label-context labels)))
1397 (cb (current-buffer)))
1399 (helm :input (thing-at-point 'word)
1400 :sources `(((name . "Available labels to ref")
1401 (candidates . ,(loop for label in labels
1402 for context in contexts
1403 ;; we do some kludgy adding spaces
1404 ;; and bars to make it "easier" to
1406 collect (cons (concat
1411 (split-string context "\n")
1414 ;; default action to replace or insert ref link.
1415 (action . (lambda (label)
1416 (switch-to-buffer ,cb)
1419 ;; no prefix or on a link
1420 ((equal helm-current-prefix-arg nil)
1421 (let* ((object (org-element-context))
1422 (last-char (save-excursion
1423 (goto-char (org-element-property :end object))
1425 (if (looking-at " ")
1428 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1429 (org-element-property :type object))
1430 ;; we are on a link, so replace it.
1433 (org-element-property :begin object)
1434 (org-element-property :end object))
1436 (replace-regexp-in-string
1437 (org-element-property :path object)
1439 (org-element-property :raw-link object))
1441 ;; insert a new link
1446 ;; one prefix, alternate ref link
1447 ((equal helm-current-prefix-arg '(4))
1450 (helm :sources '((name . "Ref link types")
1451 (candidates . ("ref" "eqref" "pageref" "nameref"))
1452 (action . (lambda (x) x))))
1454 ;; two prefixes, insert section custom-id link
1455 ((equal helm-current-prefix-arg '(16))
1457 (format "[[#%s]]" label)))
1463 : org-ref-helm-insert-ref-link
1467 This refers to the page of a label in LaTeX.
1469 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1473 "on clicking goto the label. Navigate back with C-c &"
1474 (org-mark-ring-push)
1475 ;; next search from beginning of the buffer
1481 (goto-char (point-min))
1482 (re-search-forward (format "label:%s\\b" label) nil t))
1486 (goto-char (point-min))
1487 (re-search-forward (format "\\label{%s}" label) nil t))
1489 ;; #+label: name org-definition
1491 (goto-char (point-min))
1492 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1496 (goto-char (point-min))
1497 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1499 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1500 ;; you need [[#label]] links.
1503 ; (goto-char (point-min))
1504 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1506 ;; we did not find anything, so go back to where we came
1507 (org-mark-ring-goto)
1508 (error "%s not found" label))
1509 (message "go back with (org-mark-ring-goto) `C-c &`"))
1511 (lambda (keyword desc format)
1513 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1515 (format "\\pageref{%s}" keyword)))))
1518 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1519 (defun org-pageref-complete-link (&optional arg)
1520 "Completion function for ref links"
1522 (setq label (completing-read "label: " (org-ref-get-labels)))
1523 (format "ref:%s" label)))
1526 Alternatively, you may want to just call a function that inserts a link with completion:
1528 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1529 (defun org-pageref-insert-ref-link ()
1531 (insert (org-pageref-complete-link)))
1536 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.
1538 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1542 "on clicking goto the label. Navigate back with C-c &"
1543 (org-mark-ring-push)
1544 ;; next search from beginning of the buffer
1550 (goto-char (point-min))
1551 (re-search-forward (format "\\label{%s}" label) nil t))
1553 ;; we did not find anything, so go back to where we came
1554 (org-mark-ring-goto)
1555 (error "%s not found" label))
1556 (message "go back with (org-mark-ring-goto) `C-c &`"))
1558 (lambda (keyword desc format)
1560 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1562 (format "\\nameref{%s}" keyword)))))
1566 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1568 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1572 "on clicking goto the label. Navigate back with C-c &"
1573 (org-mark-ring-push)
1574 ;; next search from beginning of the buffer
1576 (goto-char (point-min))
1579 ;; search forward for the first match
1581 (re-search-forward (format "label:%s" label) nil t)
1583 (re-search-forward (format "\\label{%s}" label) nil t)
1584 ;; #+label: name org-definition
1585 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1586 (org-mark-ring-goto)
1587 (error "%s not found" label))
1588 (message "go back with (org-mark-ring-goto) `C-c &`"))
1590 (lambda (keyword desc format)
1592 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1594 (format "\\eqref{%s}" keyword)))))
1598 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.
1600 *** Implementing the click actions of cite
1602 **** Getting the key we clicked on
1603 The first thing we need is to get the bibtex key we clicked on.
1605 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1606 (defun org-ref-get-bibtex-key-under-cursor ()
1607 "returns key under the bibtex cursor. We search forward from
1608 point to get a comma, or the end of the link, and then backwards
1609 to get a comma, or the beginning of the link. that delimits the
1610 keyword we clicked on. We also strip the text properties."
1612 (let* ((object (org-element-context))
1613 (link-string (org-element-property :path object)))
1614 ;; you may click on the part before the citations. here we make
1615 ;; sure to move to the beginning so you get the first citation.
1617 (goto-char (org-element-property :begin object))
1618 (search-forward link-string (org-element-property :end object))
1619 (goto-char (match-beginning 0))
1620 ;; check if we clicked before the path and move as needed.
1621 (unless (< cp (point))
1624 (if (not (org-element-property :contents-begin object))
1625 ;; this means no description in the link
1627 ;; we need the link path start and end
1629 (goto-char (org-element-property :begin object))
1630 (search-forward link-string nil nil 1)
1631 (setq link-string-beginning (match-beginning 0))
1632 (setq link-string-end (match-end 0)))
1634 ;; The key is the text between commas, or the link boundaries
1636 (if (search-forward "," link-string-end t 1)
1637 (setq key-end (- (match-end 0) 1)) ; we found a match
1638 (setq key-end link-string-end))) ; no comma found so take the end
1639 ;; and backward to previous comma from point which defines the start character
1641 (if (search-backward "," link-string-beginning 1 1)
1642 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1643 (setq key-beginning link-string-beginning))) ; no match found
1644 ;; save the key we clicked on.
1645 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1646 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1648 ;; link with description. assume only one key
1652 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.
1654 **** Getting the bibliographies
1655 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1656 (defun org-ref-find-bibliography ()
1657 "find the bibliography in the buffer.
1658 This function sets and returns cite-bibliography-files, which is a list of files
1659 either from bibliography:f1.bib,f2.bib
1660 \bibliography{f1,f2}
1661 internal bibliographies
1663 falling back to what the user has set in org-ref-default-bibliography
1668 (goto-char (point-min))
1669 ;; look for a bibliography link
1670 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1671 (setq org-ref-bibliography-files
1672 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1673 (throw 'result org-ref-bibliography-files))
1676 ;; we did not find a bibliography link. now look for \bibliography
1677 (goto-char (point-min))
1678 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1679 ;; split, and add .bib to each file
1680 (setq org-ref-bibliography-files
1681 (mapcar (lambda (x) (concat x ".bib"))
1682 (mapcar 'org-ref-strip-string
1683 (split-string (match-string 1) ","))))
1684 (throw 'result org-ref-bibliography-files))
1686 ;; no bibliography found. maybe we need a biblatex addbibresource
1687 (goto-char (point-min))
1688 ;; look for a bibliography link
1689 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1690 (setq org-ref-bibliography-files
1691 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1692 (throw 'result org-ref-bibliography-files))
1694 ;; we did not find anything. use defaults
1695 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1697 ;; set reftex-default-bibliography so we can search
1698 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1699 org-ref-bibliography-files)
1702 **** Finding the bibliography file a key is in
1703 Now, we can see if an entry is in a file.
1705 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1706 (defun org-ref-key-in-file-p (key filename)
1707 "determine if the key is in the file"
1708 (interactive "skey: \nsFile: ")
1709 (save-current-buffer
1710 (let ((bibtex-files (list filename)))
1711 (bibtex-search-entry key t))))
1714 Finally, we want to know which file the key is in.
1716 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1717 (defun org-ref-get-bibtex-key-and-file (&optional key)
1718 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1720 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1723 (setq key (org-ref-get-bibtex-key-under-cursor)))
1724 (setq file (catch 'result
1725 (loop for file in org-ref-bibliography-files do
1726 (if (org-ref-key-in-file-p key (file-truename file))
1727 (throw 'result file)))))
1731 **** convenience functions to act on citation at point
1733 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1735 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.
1737 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1738 (defun org-ref-open-pdf-at-point ()
1739 "open the pdf for bibtex key under point if it exists"
1741 (let* ((results (org-ref-get-bibtex-key-and-file))
1743 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1744 (if (file-exists-p pdf-file)
1745 (org-open-file pdf-file)
1746 (message "no pdf found for %s" key))))
1749 (defun org-ref-open-url-at-point ()
1750 "open the url for bibtex key under point."
1752 (let* ((results (org-ref-get-bibtex-key-and-file))
1754 (bibfile (cdr results)))
1757 (insert-file-contents bibfile)
1758 (bibtex-search-entry key)
1759 ;; I like this better than bibtex-url which does not always find
1762 (let ((url (bibtex-autokey-get-field "url")))
1767 (let ((doi (bibtex-autokey-get-field "doi")))
1769 (if (string-match "^http" doi)
1771 (browse-url (format "http://dx.doi.org/%s" doi)))
1772 (throw 'done nil))))))))
1775 (defun org-ref-open-notes-at-point ()
1776 "open the notes for bibtex key under point."
1778 (let* ((results (org-ref-get-bibtex-key-and-file))
1780 (bibfile (cdr results)))
1783 (insert-file-contents bibfile)
1784 (bibtex-search-entry key)
1785 (org-ref-open-bibtex-notes)))))
1788 (defun org-ref-citation-at-point ()
1789 "give message of current citation at point"
1791 (let* ((cb (current-buffer))
1792 (results (org-ref-get-bibtex-key-and-file))
1794 (bibfile (cdr results)))
1795 (message "%s" (progn
1797 (insert-file-contents bibfile)
1798 (bibtex-search-entry key)
1799 (org-ref-bib-citation))))))
1802 (defun org-ref-open-citation-at-point ()
1803 "open bibtex file to key at point"
1805 (let* ((cb (current-buffer))
1806 (results (org-ref-get-bibtex-key-and-file))
1808 (bibfile (cdr results)))
1810 (bibtex-search-entry key)))
1813 **** the actual minibuffer menu
1814 Now, we create the menu. This is a rewrite of the cite action. This makes the function extendable by users.
1816 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1817 (defvar org-ref-cite-menu-funcs '()
1818 "Functions to run on cite click menu. Each entry is a list of (key menu-name function).
1819 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.")
1822 (defvar org-ref-user-cite-menu-funcs
1823 '(("C" "rossref" org-ref-crossref-at-point)
1824 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1825 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1826 "user-defined functions to run on bibtex key at point.")
1829 (defun org-ref-copy-entry-as-summary ()
1830 "Copy the bibtex entry for the citation at point as a summary."
1832 (save-window-excursion
1833 (org-ref-open-citation-at-point)
1834 (kill-new (org-ref-bib-citation))))
1837 (defun org-ref-copy-entry-at-point-to-file ()
1838 "Copy the bibtex entry for the citation at point to NEW-FILE.
1839 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."
1841 (let ((new-file (ido-completing-read
1843 (append org-ref-default-bibliography
1844 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1845 (key (org-ref-get-bibtex-key-under-cursor)))
1846 (save-window-excursion
1847 (org-ref-open-citation-at-point)
1848 (bibtex-copy-entry-as-kill))
1850 (let ((bibtex-files (list (file-truename new-file))))
1851 (if (assoc key (bibtex-global-key-alist))
1852 (message "That key already exists in %s" new-file)
1854 (save-window-excursion
1855 (find-file new-file)
1856 (goto-char (point-max))
1857 ;; make sure we are at the beginning of a line.
1858 (unless (looking-at "^") (insert "\n\n"))
1863 (defun org-ref-get-doi-at-point ()
1864 "Get doi for key at point."
1866 (let* ((results (org-ref-get-bibtex-key-and-file))
1868 (bibfile (cdr results))
1872 (insert-file-contents bibfile)
1873 (bibtex-search-entry key)
1874 (setq doi (bibtex-autokey-get-field "doi"))
1875 ;; in case doi is a url, remove the url part.
1876 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1879 ;; functions that operate on key at point for click menu
1880 (defun org-ref-wos-at-point ()
1881 "open the doi in wos for bibtex key under point."
1883 (doi-utils-wos (org-ref-get-doi-at-point)))
1886 (defun org-ref-wos-citing-at-point ()
1887 "open the doi in wos citing articles for bibtex key under point."
1889 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1892 (defun org-ref-wos-related-at-point ()
1893 "open the doi in wos related articles for bibtex key under point."
1895 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1898 (defun org-ref-google-scholar-at-point ()
1899 "open the doi in google scholar for bibtex key under point."
1901 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1904 (defun org-ref-pubmed-at-point ()
1905 "open the doi in pubmed for bibtex key under point."
1907 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1910 (defun org-ref-crossref-at-point ()
1911 "open the doi in crossref for bibtex key under point."
1913 (doi-utils-crossref (org-ref-get-doi-at-point)))
1916 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1917 "action when a cite link is clicked on.
1918 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."
1920 (let* ((results (org-ref-get-bibtex-key-and-file))
1922 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1923 (bibfile (cdr results))
1924 (url (save-excursion
1926 (insert-file-contents bibfile)
1927 (bibtex-search-entry key)
1928 (bibtex-autokey-get-field "url"))))
1929 (doi (save-excursion
1931 (insert-file-contents bibfile)
1932 (bibtex-search-entry key)
1933 ;; I like this better than bibtex-url which does not always find
1935 (bibtex-autokey-get-field "doi")))))
1937 (when (string= "" doi) (setq doi nil))
1938 (when (string= "" url) (setq url nil))
1939 (setq org-ref-cite-menu-funcs '())
1945 'org-ref-cite-menu-funcs
1946 '("o" "pen" org-ref-open-citation-at-point)))
1949 (when (file-exists-p pdf-file)
1951 'org-ref-cite-menu-funcs
1952 `("p" "df" ,org-ref-open-pdf-function) t))
1956 'org-ref-cite-menu-funcs
1957 '("n" "otes" org-ref-open-notes-at-point) t)
1962 'org-ref-cite-menu-funcs
1963 '("u" "rl" org-ref-open-url-at-point) t))
1968 'org-ref-cite-menu-funcs
1969 '("w" "os" org-ref-wos-at-point) t)
1972 'org-ref-cite-menu-funcs
1973 '("c" "iting" org-ref-wos-citing-at-point) t)
1976 'org-ref-cite-menu-funcs
1977 '("r" "elated" org-ref-wos-related-at-point) t)
1980 'org-ref-cite-menu-funcs
1981 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1984 'org-ref-cite-menu-funcs
1985 '("P" "ubmed" org-ref-pubmed-at-point) t))
1987 ;; add user functions
1988 (dolist (tup org-ref-user-cite-menu-funcs)
1990 'org-ref-cite-menu-funcs
1995 'org-ref-cite-menu-funcs
1996 '("q" "uit" (lambda ())) t)
1998 ;; now we make a menu
1999 ;; construct menu string as a message
2002 (let* ((results (org-ref-get-bibtex-key-and-file))
2004 (bibfile (cdr results)))
2007 (insert-file-contents bibfile)
2008 (bibtex-search-entry key)
2009 (org-ref-bib-citation))))
2013 (concat "[" (elt tup 0) "]"
2015 org-ref-cite-menu-funcs "")))
2017 (let* ((input (read-char-exclusive))
2019 (char-to-string input) org-ref-cite-menu-funcs)))
2020 ;; now run the function (2nd element in choice)
2029 : org-ref-cite-onclick-minibuffer-menu
2031 *** A function to format a cite link
2033 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.
2035 #+BEGIN_SRC emacs-lisp :tangle no
2036 ;(defun org-ref-cite-link-format (keyword desc format)
2038 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
2039 ; ((eq format 'latex)
2040 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
2041 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
2045 *** The actual cite link
2046 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
2048 #+BEGIN_SRC emacs-lisp :tangle no
2051 ; 'org-ref-cite-onclick-minibuffer-menu
2052 ; 'org-ref-cite-link-format)
2055 *** Automatic definition of the cite links
2056 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.
2058 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2059 (defmacro org-ref-make-completion-function (type)
2060 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
2066 (let ((bibtex-files (org-ref-find-bibliography)))
2067 (bibtex-global-key-alist))))))
2070 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.
2072 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2073 (defmacro org-ref-make-format-function (type)
2074 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
2079 (format "[[#%s][%s]]" key key))
2080 (org-ref-split-and-strip-string keyword) ","))
2087 (org-ref-split-and-strip-string keyword) ",") "]"))
2092 (format "<a href=\"#%s\">%s</a>" key key))
2093 (org-ref-split-and-strip-string keyword) ","))
2096 (if (string= (substring type -1) "s")
2097 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
2098 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
2099 (org-ref-split-and-strip-string keyword) ""))
2101 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
2102 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
2104 ;; for markdown we generate pandoc citations
2107 (desc ;; pre and or post text
2108 (let* ((text (split-string desc "::"))
2112 (format "[@%s," keyword)
2113 (when pre (format " %s" pre))
2114 (when post (format ", %s" post))
2119 (lambda (key) (concat "@" key))
2120 (org-ref-split-and-strip-string keyword)
2126 We create the links by mapping the function onto the list of defined link types.
2128 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2129 (defun org-ref-format-citation-description (desc)
2130 "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 ::."
2133 ((string-match "::" desc)
2134 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
2135 (t (format "[%s]" desc))))
2137 (defun org-ref-define-citation-link (type &optional key)
2138 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
2139 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
2140 and the completion function."
2141 (interactive "sCitation Type: \ncKey: ")
2143 ;; create the formatting function
2144 (eval `(org-ref-make-format-function ,type))
2149 org-ref-cite-onclick-function
2150 (quote ,(intern (format "org-ref-format-%s" type)))))
2152 ;; create the completion function
2153 (eval `(org-ref-make-completion-function ,type))
2155 ;; store new type so it works with adding citations, which checks
2156 ;; for existence in this list
2157 (add-to-list 'org-ref-cite-types type)
2159 ;; and finally if a key is specified, we modify the reftex menu
2161 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
2162 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
2163 `((,key . ,(concat type ":%l")))))))
2165 ;; create all the link types and their completion functions
2166 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
2169 *** org-ref-insert-cite-link
2170 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.
2172 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2173 (defun org-ref-insert-cite-link (alternative-cite)
2174 "Insert a default citation link using reftex. If you are on a link, it
2175 appends to the end of the link, otherwise, a new link is
2176 inserted. Use a prefix arg to get a menu of citation types."
2178 (org-ref-find-bibliography)
2179 (let* ((object (org-element-context))
2180 (link-string-beginning (org-element-property :begin object))
2181 (link-string-end (org-element-property :end object))
2182 (path (org-element-property :path object)))
2184 (if (not alternative-cite)
2187 ;; case where we are in a link
2188 ((and (equal (org-element-type object) 'link)
2189 (-contains? org-ref-cite-types (org-element-property :type object)))
2190 (goto-char link-string-end)
2191 ;; sometimes there are spaces at the end of the link
2192 ;; this code moves point pack until no spaces are there
2193 (while (looking-back " ") (backward-char))
2194 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
2196 ;; We are next to a link, and we want to append
2199 (and (equal (org-element-type (org-element-context)) 'link)
2200 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
2201 (while (looking-back " ") (backward-char))
2202 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
2204 ;; insert fresh link
2207 (concat org-ref-default-citation-link
2209 (mapconcat 'identity (reftex-citation t) ",")))))
2211 ;; you pressed a C-u so we run this code
2215 cite:zhou-2004-first-lda-u,paier-2006-errat,boes-2015-estim-bulk
2219 : org-ref-insert-cite-link
2221 *** Completion in cite links
2222 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.
2224 #+BEGIN_SRC emacs-lisp :tangle no
2225 (defun org-cite-complete-link (&optional arg)
2226 "Completion function for cite links"
2228 org-ref-default-citation-link
2231 (let ((bibtex-files (org-ref-find-bibliography)))
2232 (bibtex-global-key-alist)))))
2235 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
2237 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2238 (defun org-ref-insert-cite-with-completion (type)
2239 "Insert a cite link with completion"
2240 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
2241 (insert (funcall (intern (format "org-%s-complete-link" type)))))
2244 ** Storing links to a bibtex entry
2245 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.
2247 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2248 (defun org-ref-store-bibtex-entry-link ()
2249 "Save a citation link to the current bibtex entry. Saves in the default link type."
2251 (let ((link (concat org-ref-default-citation-link
2254 (bibtex-beginning-of-entry)
2255 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
2256 (message "saved %s" link)
2257 (push (list link) org-stored-links)
2258 (car org-stored-links)))
2262 org-ref minimally supports index entries. To make an index in a file, you should put in the LaTeX header these lines
2265 #+LATEX_HEADER: \usepackage{makeidx}
2266 #+LATEX_HEADER: \makeindex
2269 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.
2272 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.
2277 [[index:hello!Sam@\textsl{Sam}]]
2278 [[index:Lin@\textbf{Lin}]]
2279 [[index:Joe|textit]]
2280 [[index:Lin@\textbf{Lin}]]
2281 [[index:Peter|see {hello}]]
2282 [[index:Jen|seealso{Jenny}]]
2284 index:encodings!input!cp850
2286 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2292 (lambda (path desc format)
2295 (format "\\index{%s}" path)))))
2297 ;; this will generate a temporary index of entries in the file.
2301 (let ((*index-links* '())
2302 (*initial-letters* '()))
2305 (org-element-map (org-element-parse-buffer) 'link
2307 (let ((type (nth 0 link))
2308 (plist (nth 1 link)))
2310 (when (equal (plist-get plist ':type) "index")
2313 (cons (plist-get plist :path)
2315 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2317 (plist-get plist :begin) ;; position of link
2318 ;; grab a description
2320 (goto-char (plist-get plist :begin))
2321 (if (thing-at-point 'sentence)
2323 (replace-regexp-in-string
2324 "\n" "" (thing-at-point 'sentence))
2325 ;; or call it a link
2329 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2331 ;; now first letters
2332 (dolist (link *index-links*)
2333 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2335 ;; now create the index
2336 (switch-to-buffer (get-buffer-create "*index*"))
2339 (insert "#+TITLE: Index\n\n")
2340 (dolist (letter *initial-letters*)
2341 (insert (format "* %s\n" (upcase letter)))
2342 ;; now process the links
2345 (string= letter (substring (car (car *index-links*)) 0 1)))
2346 (let ((link (pop *index-links*)))
2347 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2348 (switch-to-buffer "*index*")))
2350 (lambda (path desc format)
2353 (format "\\printindex")))))
2357 | 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*)) |
2358 | lambda | (path desc format) | (cond ((eq format (quote latex)) (format \printindex))) |
2361 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.
2363 #+LATEX_HEADER: \usepackage{glossaries}
2364 #+LATEX_HEADER: \makeglossaries
2366 And at the end of the document put \makeglossaries.
2368 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2371 nil ;; no follow action
2372 (lambda (path desc format)
2375 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2381 nil ;; no follow action
2382 (lambda (path desc format)
2385 (format "\\gls{%s}" path)))))
2390 nil ;; no follow action
2391 (lambda (path desc format)
2394 (format "\\glspl{%s}" path)))))
2399 nil ;; no follow action
2400 (lambda (path desc format)
2403 (format "\\Gls{%s}" path)))))
2408 nil ;; no follow action
2409 (lambda (path desc format)
2412 (format "\\Glspl{%s}" path)))))
2416 ** create simple text citation from bibtex entry
2418 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2419 (defun org-ref-bib-citation ()
2420 "From a bibtex entry, create and return a simple citation string.
2421 This assumes you are in an article."
2423 (bibtex-beginning-of-entry)
2424 (let* ((cb (current-buffer))
2425 (bibtex-expand-strings t)
2426 (entry (loop for (key . value) in (bibtex-parse-entry t)
2427 collect (cons (downcase key) value)))
2428 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2429 (year (reftex-get-bib-field "year" entry))
2430 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2431 (key (reftex-get-bib-field "=key=" entry))
2432 (journal (reftex-get-bib-field "journal" entry))
2433 (volume (reftex-get-bib-field "volume" entry))
2434 (pages (reftex-get-bib-field "pages" entry))
2435 (doi (reftex-get-bib-field "doi" entry))
2436 (url (reftex-get-bib-field "url" entry))
2438 ;;authors, "title", Journal, vol(iss):pages (year).
2439 (format "%s, \"%s\", %s, %s:%s (%s)"
2440 author title journal volume pages year)))
2444 : org-ref-bib-citation
2447 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2448 (defun org-ref-bib-html-citation ()
2449 "from a bibtex entry, create and return a simple citation with html links."
2451 (bibtex-beginning-of-entry)
2452 (let* ((cb (current-buffer))
2453 (bibtex-expand-strings t)
2454 (entry (loop for (key . value) in (bibtex-parse-entry t)
2455 collect (cons (downcase key) value)))
2456 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2457 (year (reftex-get-bib-field "year" entry))
2458 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2459 (key (reftex-get-bib-field "=key=" entry))
2460 (journal (reftex-get-bib-field "journal" entry))
2461 (volume (reftex-get-bib-field "volume" entry))
2462 (pages (reftex-get-bib-field "pages" entry))
2463 (doi (reftex-get-bib-field "doi" entry))
2464 (url (reftex-get-bib-field "url" entry))
2466 ;;authors, "title", Journal, vol(iss):pages (year).
2467 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2468 author title journal volume pages year)
2469 (when url (format " <a href=\"%s\">link</a>" url))
2470 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2474 ** open pdf from bibtex
2475 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2476 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2477 (defun org-ref-open-bibtex-pdf ()
2478 "open pdf for a bibtex entry, if it exists. assumes point is in
2479 the entry of interest in the bibfile. but does not check that."
2482 (bibtex-beginning-of-entry)
2483 (let* ((bibtex-expand-strings t)
2484 (entry (bibtex-parse-entry t))
2485 (key (reftex-get-bib-field "=key=" entry))
2486 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2488 (if (file-exists-p pdf)
2489 (org-open-link-from-string (format "[[file:%s]]" pdf))
2493 ** open notes from bibtex
2494 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2496 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2497 (defun org-ref-open-bibtex-notes ()
2498 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
2500 I never did figure out how to use reftex to make this happen
2501 non-interactively. the reftex-format-citation function did not
2502 work perfectly; there were carriage returns in the strings, and
2503 it did not put the key where it needed to be. so, below I replace
2504 the carriage returns and extra spaces with a single space and
2505 construct the heading by hand."
2508 (bibtex-beginning-of-entry)
2509 (let* ((cb (current-buffer))
2510 (bibtex-expand-strings t)
2511 (entry (loop for (key . value) in (bibtex-parse-entry t)
2512 collect (cons (downcase key) value)))
2513 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2514 (year (reftex-get-bib-field "year" entry))
2515 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2516 (key (reftex-get-bib-field "=key=" entry))
2517 (journal (reftex-get-bib-field "journal" entry))
2518 (volume (reftex-get-bib-field "volume" entry))
2519 (pages (reftex-get-bib-field "pages" entry))
2520 (doi (reftex-get-bib-field "doi" entry))
2521 (url (reftex-get-bib-field "url" entry))
2524 ;; save key to clipboard to make saving pdf later easier by pasting.
2527 (kill-ring-save (point-min) (point-max)))
2529 ;; now look for entry in the notes file
2530 (if org-ref-bibliography-notes
2531 (find-file-other-window org-ref-bibliography-notes)
2532 (error "org-ref-bib-bibliography-notes is not set to anything"))
2534 (goto-char (point-min))
2535 ;; put new entry in notes if we don't find it.
2536 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2537 (funcall org-ref-open-notes-function)
2538 ;; no entry found, so add one
2539 (insert (format "\n** TODO %s - %s" year title))
2551 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2552 key author journal year volume pages doi url key org-ref-pdf-directory key))
2556 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2557 (defun org-ref-open-notes-from-reftex ()
2558 "Call reftex, and open notes for selected entry."
2560 (let ((bibtex-key )))
2562 ;; now look for entry in the notes file
2563 (if org-ref-bibliography-notes
2564 (find-file-other-window org-ref-bibliography-notes)
2565 (error "org-ref-bib-bibliography-notes is not set to anything"))
2567 (goto-char (point-min))
2569 (re-search-forward (format
2571 (first (reftex-citation t)) nil 'end))
2572 (funcall org-ref-open-notes-function))
2575 ** open url in browser from bibtex
2577 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2579 + 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.
2581 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2582 (defun org-ref-open-in-browser ()
2583 "Open the bibtex entry at point in a browser using the url field or doi field"
2586 (bibtex-beginning-of-entry)
2588 (let ((url (bibtex-autokey-get-field "url")))
2593 (let ((doi (bibtex-autokey-get-field "doi")))
2595 (if (string-match "^http" doi)
2597 (browse-url (format "http://dx.doi.org/%s" doi)))
2599 (message "No url or doi found"))))
2603 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.
2605 *** function to upload bibtex to citeulike
2607 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2608 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2609 "with point in a bibtex entry get bibtex string and submit to citeulike.
2611 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2613 (message "uploading to citeulike")
2615 (bibtex-narrow-to-entry)
2616 (let ((startpos (point-min))
2617 (endpos (point-max))
2618 (bibtex-string (buffer-string))
2619 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2620 (with-temp-buffer (insert bibtex-string)
2621 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2624 *** The upload script
2625 Here is the python script for uploading.
2627 *************** TODO document how to get the cookies
2630 # :tangle upload_bibtex_citeulike.py
2633 import pickle, requests, sys
2636 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
2637 cookies = pickle.load(f)
2639 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
2641 bibtex = sys.stdin.read()
2643 data = {'pasted':bibtex,
2645 'tag_parsing':'simple',
2646 'strip_brackets':'no',
2647 'update_id':'bib-key',
2648 'btn_bibtex':'Import BibTeX file ...'}
2650 headers = {'content-type': 'multipart/form-data',
2651 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
2653 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
2657 ** Build a pdf from a bibtex file
2658 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.
2660 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2661 (defun org-ref-build-full-bibliography ()
2662 "build pdf of all bibtex entries, and open it."
2664 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2665 (bib-base (file-name-sans-extension bibfile))
2666 (texfile (concat bib-base ".tex"))
2667 (pdffile (concat bib-base ".pdf")))
2670 (insert (format "\\documentclass[12pt]{article}
2671 \\usepackage[version=3]{mhchem}
2673 \\usepackage[numbers]{natbib}
2674 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2678 \\bibliographystyle{unsrtnat}
2680 \\end{document}" bib-base))
2682 (shell-command (concat "pdflatex " bib-base))
2683 (shell-command (concat "bibtex " bib-base))
2684 (shell-command (concat "pdflatex " bib-base))
2685 (shell-command (concat "pdflatex " bib-base))
2686 (kill-buffer texfile)
2687 (org-open-file pdffile)
2691 ** Extract bibtex entries cited in an org-file
2692 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.
2694 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2695 (defun org-ref-extract-bibtex-entries ()
2696 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2698 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
2700 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2701 (tempname (make-temp-file "extract-bib"))
2702 (contents (buffer-string))
2703 (cb (current-buffer))
2704 basename texfile bibfile results)
2706 ;; open tempfile and insert org-buffer contents
2707 (find-file tempname)
2709 (setq basename (file-name-sans-extension
2710 (file-name-nondirectory buffer-file-name))
2711 texfile (concat tempname ".tex")
2712 bibfile (concat tempname ".bib"))
2714 ;; see if we have a bibliography, and insert the default one if not.
2716 (goto-char (point-min))
2717 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2718 (insert (format "\nbibliography:%s"
2719 (mapconcat 'identity reftex-default-bibliography ",")))))
2722 ;; get a latex file and extract the references
2723 (org-latex-export-to-latex)
2726 (reftex-create-bibtex-file bibfile)
2728 ;; save results of the references
2729 (setq results (buffer-string))
2731 ;; kill buffers. these are named by basename, not full path
2732 (kill-buffer (concat basename ".bib"))
2733 (kill-buffer (concat basename ".tex"))
2734 (kill-buffer basename)
2736 (delete-file bibfile)
2737 (delete-file texfile)
2738 (delete-file tempname)
2740 ;; Now back to the original org buffer and insert the results
2741 (switch-to-buffer cb)
2742 (when (not (string= "" results))
2744 (goto-char (point-max))
2746 (org-insert-heading)
2747 (insert (format " Bibtex entries
2749 ,#+BEGIN_SRC text :tangle %s
2751 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2754 ** Find bad cite links
2756 :ID: 8515E800-EDA0-4B2A-85FD-55B6FF849203
2758 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.
2760 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2763 (defun index (substring list)
2764 "return the index of string in a list of strings"
2767 (dolist (arg list i)
2768 (if (string-match (concat "^" substring "$") arg)
2773 ;; return counter if found, otherwise return nil
2777 (defun org-ref-find-bad-citations ()
2778 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2780 Makes a new buffer with clickable links."
2782 ;; generate the list of bibtex-keys and cited keys
2783 (let* ((bibtex-files (org-ref-find-bibliography))
2784 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2785 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2786 (bad-citations '()))
2788 (org-element-map (org-element-parse-buffer) 'link
2790 (let ((plist (nth 1 link)))
2791 (when (-contains? org-ref-cite-types (plist-get plist :type))
2792 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2793 (when (not (index key bibtex-keys))
2794 (message-box "%s" link)
2799 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2802 (plist-get plist :begin)))))
2804 ;; set with-affilates to t to get citations in a caption
2809 (switch-to-buffer-other-window "*Missing citations*")
2812 (insert "* List of bad cite links\n")
2813 (insert (mapconcat 'identity bad-citations ""))
2814 ;(setq buffer-read-only t)
2815 (use-local-map (copy-keymap org-mode-map))
2816 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2818 (when (get-buffer "*Missing citations*")
2819 (kill-buffer "*Missing citations*"))
2820 (message "No bad cite links found"))))
2823 ** helm interface to org-ref
2824 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.
2826 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.
2828 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2829 (defun org-ref-bad-cite-candidates ()
2830 "Returns a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2831 (let* ((cp (point)) ; save to return to later
2832 (bibtex-files (org-ref-find-bibliography))
2833 (bibtex-file-path (mapconcat
2835 (file-name-directory (file-truename x)))
2837 (bibtex-keys (mapcar (lambda (x) (car x))
2838 (bibtex-global-key-alist)))
2839 (bad-citations '()))
2841 (org-element-map (org-element-parse-buffer) 'link
2843 (let ((plist (nth 1 link)))
2844 (when (-contains? org-ref-cite-types (plist-get plist :type))
2845 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2846 (when (not (index key bibtex-keys))
2847 (goto-char (plist-get plist :begin))
2848 (re-search-forward key)
2849 (push (cons key (point-marker)) bad-citations)))
2851 ;; add with-affiliates to get cites in caption
2857 (defun org-ref-bad-ref-candidates ()
2858 "Returns a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2859 ;; first get a list of legitimate labels
2861 (labels (org-ref-get-labels))
2863 ;; now loop over ref links
2864 (goto-char (point-min))
2865 (org-element-map (org-element-parse-buffer) 'link
2867 (let ((plist (nth 1 link)))
2868 (when (or (equal (plist-get plist ':type) "ref")
2869 (equal (plist-get plist ':type) "eqref")
2870 (equal (plist-get plist ':type) "pageref")
2871 (equal (plist-get plist ':type) "nameref"))
2872 (unless (-contains? labels (plist-get plist :path))
2873 (goto-char (plist-get plist :begin))
2876 (cons (plist-get plist :path)
2877 (point-marker))))))))
2882 (defun org-ref-bad-label-candidates ()
2883 "Return a list of labels where label is multiply defined."
2884 (let ((labels (org-ref-get-labels))
2885 (multiple-labels '()))
2886 (when (not (= (length labels)
2887 (length (-uniq labels))))
2888 (dolist (label labels)
2889 (when (> (-count (lambda (a)
2892 ;; this is a multiply defined label.
2894 (goto-char (point-min))
2895 (while (re-search-forward
2896 (format "[^#+]label:%s\\s-" label) nil t)
2897 (push (cons label (point-marker)) multiple-labels))
2899 (goto-char (point-min))
2900 (while (re-search-forward
2901 (format "\\label{%s}\\s-?" label) nil t)
2902 (push (cons label (point-marker)) multiple-labels))
2904 (goto-char (point-min))
2905 (while (re-search-forward
2906 (format "^#\\+label:\\s-*%s" label) nil t)
2907 (push (cons label (point-marker)) multiple-labels))
2909 (goto-char (point-min))
2910 (while (re-search-forward
2911 (format "^#\\+tblname:\\s-*%s" label) nil t)
2912 (push (cons label (point-marker)) multiple-labels))
2918 : org-ref-bad-label-candidates
2920 Now, we have a functions for candidates, we can make helm sources for each one, and then run a helm command to view them.
2922 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2924 "Opens a helm interface to actions for org-ref.
2925 Shows bad citations, ref links and labels"
2927 (let ((cb (current-buffer))
2928 (bad-citations (org-ref-bad-cite-candidates))
2929 (bad-refs (org-ref-bad-ref-candidates))
2930 (bad-labels (org-ref-bad-label-candidates)))
2932 (helm :sources `(((name . "Bad citations")
2933 (candidates . ,bad-citations)
2934 (action . (lambda (marker)
2935 (switch-to-buffer (marker-buffer marker))
2936 (goto-char marker))))
2938 ((name . "Bad Labels")
2939 (candidates . ,bad-labels)
2940 (action . (lambda (marker)
2941 (switch-to-buffer (marker-buffer marker))
2942 (goto-char marker))))
2944 ((name . "Bad ref links")
2945 (candidates . ,bad-refs)
2946 (action . (lambda (marker)
2947 (switch-to-buffer (marker-buffer marker))
2948 (goto-char marker))))
2950 ((name . "Utilities")
2951 (candidates . (("Check buffer again" . org-ref)
2952 ("Insert citation" . helm-bibtex)
2953 ("Insert label link" . org-ref-helm-insert-label-link)
2954 ("Insert ref link" . org-ref-helm-insert-ref-link)
2955 ("List of figures" . org-ref-list-of-figures)
2956 ("List of tables" . org-ref-list-of-tables)
2957 ("Table of contents" . nil)
2959 (action . (lambda (x)
2960 (switch-to-buffer ,cb)
2963 ((name . "Export functions")
2964 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2965 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2966 ("Export to pdf and open" . (lambda ()
2967 (org-open-file (org-latex-export-to-pdf))))
2968 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2969 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2972 (action . (lambda (x)
2973 (switch-to-buffer ,cb)
2979 ** Finding non-ascii characters
2980 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2982 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2983 (defun org-ref-find-non-ascii-characters ()
2984 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2986 (occur "[^[:ascii:]]"))
2989 ** Resort a bibtex entry
2990 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.
2992 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2993 (defun org-ref-sort-bibtex-entry ()
2994 "sort fields of entry in standard order and downcase them"
2996 (bibtex-beginning-of-entry)
2997 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2998 (entry (bibtex-parse-entry))
3001 (type (cdr (assoc "=type=" entry)))
3002 (key (cdr (assoc "=key=" entry))))
3004 ;; these are the fields we want to order that are in this entry
3005 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
3006 ;; we do not want to reenter these fields
3007 (setq entry-fields (remove "=key=" entry-fields))
3008 (setq entry-fields (remove "=type=" entry-fields))
3010 ;;these are the other fields in the entry
3011 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
3014 ;; right now we only resort articles
3015 ((string= (downcase type) "article")
3018 (concat "@article{" key ",\n"
3021 (when (member field entry-fields)
3022 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
3025 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
3027 (bibtex-find-entry key)
3029 (bibtex-clean-entry)
3033 ** Clean a bibtex entry
3034 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.
3035 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.
3036 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3037 (defun org-ref-clean-bibtex-entry(&optional keep-key)
3038 "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"
3040 (bibtex-beginning-of-entry)
3042 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
3043 (unless (string-match ",$" (thing-at-point 'line))
3047 ;; check for empty pages, and put eid or article id in its place
3048 (let ((entry (bibtex-parse-entry))
3049 (pages (bibtex-autokey-get-field "pages"))
3050 (year (bibtex-autokey-get-field "year"))
3051 (doi (bibtex-autokey-get-field "doi"))
3052 ;; The Journal of Chemical Physics uses eid
3053 (eid (bibtex-autokey-get-field "eid")))
3055 ;; replace http://dx.doi.org/ in doi. some journals put that in,
3056 ;; but we only want the doi.
3057 (when (string-match "^http://dx.doi.org/" doi)
3058 (bibtex-beginning-of-entry)
3059 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
3061 (bibtex-make-field "doi")
3063 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
3065 ;; asap articles often set year to 0, which messes up key
3066 ;; generation. fix that.
3067 (when (string= "0" year)
3068 (bibtex-beginning-of-entry)
3069 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
3071 (bibtex-make-field "year")
3073 (insert (read-string "Enter year: ")))
3075 ;; fix pages if they are empty if there is an eid to put there.
3076 (when (string= "-" pages)
3078 (bibtex-beginning-of-entry)
3079 ;; this seems like a clunky way to set the pages field.But I
3080 ;; cannot find a better way.
3081 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
3083 (bibtex-make-field "pages")
3087 ;; replace naked & with \&
3089 (bibtex-narrow-to-entry)
3090 (bibtex-beginning-of-entry)
3091 (message "checking &")
3092 (replace-regexp " & " " \\\\& ")
3095 ;; generate a key, and if it duplicates an existing key, edit it.
3097 (let ((key (bibtex-generate-autokey)))
3099 ;; first we delete the existing key
3100 (bibtex-beginning-of-entry)
3101 (re-search-forward bibtex-entry-maybe-empty-head)
3102 (if (match-beginning bibtex-key-in-head)
3103 (delete-region (match-beginning bibtex-key-in-head)
3104 (match-end bibtex-key-in-head)))
3105 ;; check if the key is in the buffer
3106 (when (save-excursion
3107 (bibtex-search-entry key))
3109 (bibtex-search-entry key)
3110 (bibtex-copy-entry-as-kill)
3111 (switch-to-buffer-other-window "*duplicate entry*")
3113 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
3116 (kill-new key))) ;; save key for pasting
3118 ;; run hooks. each of these operates on the entry with no arguments.
3119 ;; this did not work like i thought, it gives a symbolp error.
3120 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
3125 org-ref-clean-bibtex-entry-hook)
3127 ;; sort fields within entry
3128 (org-ref-sort-bibtex-entry)
3129 ;; check for non-ascii characters
3130 (occur "[^[:ascii:]]")
3135 : org-ref-clean-bibtex-entry
3137 ** Sort the entries in a citation link by year
3138 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
3140 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3141 (defun org-ref-get-citation-year (key)
3142 "get the year of an entry with key. Returns year as a string."
3144 (let* ((results (org-ref-get-bibtex-key-and-file key))
3145 (bibfile (cdr results)))
3147 (insert-file-contents bibfile)
3148 (bibtex-search-entry key nil 0)
3149 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
3152 (defun org-ref-sort-citation-link ()
3153 "replace link at point with sorted link by year"
3155 (let* ((object (org-element-context))
3156 (type (org-element-property :type object))
3157 (begin (org-element-property :begin object))
3158 (end (org-element-property :end object))
3159 (link-string (org-element-property :path object))
3161 (setq keys (org-ref-split-and-strip-string link-string))
3162 (setq years (mapcar 'org-ref-get-citation-year keys))
3163 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
3164 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
3165 ;; now get the keys separated by commas
3166 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
3167 ;; and replace the link with the sorted keys
3168 (cl--set-buffer-substring begin end (concat type ":" keys))))
3171 ** Sort entries in citation links with shift-arrow keys
3172 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
3173 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3174 (defun org-ref-swap-keys (i j keys)
3175 "swap the keys in a list with index i and j"
3176 (let ((tempi (nth i keys)))
3177 (setf (nth i keys) (nth j keys))
3178 (setf (nth j keys) tempi))
3181 (defun org-ref-swap-citation-link (direction)
3182 "move citation at point in direction +1 is to the right, -1 to the left"
3184 (let* ((object (org-element-context))
3185 (type (org-element-property :type object))
3186 (begin (org-element-property :begin object))
3187 (end (org-element-property :end object))
3188 (link-string (org-element-property :path object))
3190 ;; We only want this to work on citation links
3191 (when (-contains? org-ref-cite-types type)
3192 (setq key (org-ref-get-bibtex-key-under-cursor))
3193 (setq keys (org-ref-split-and-strip-string link-string))
3194 (setq i (index key keys)) ;; defined in org-ref
3195 (if (> direction 0) ;; shift right
3196 (org-ref-swap-keys i (+ i 1) keys)
3197 (org-ref-swap-keys i (- i 1) keys))
3198 (setq keys (mapconcat 'identity keys ","))
3199 ;; and replace the link with the sorted keys
3200 (cl--set-buffer-substring begin end (concat type ":" keys " "))
3201 ;; now go forward to key so we can move with the key
3202 (re-search-forward key)
3203 (goto-char (match-beginning 0)))))
3205 ;; add hooks to make it work
3206 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
3207 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
3210 ** Lightweight messages about links
3211 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.
3213 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3214 (defun org-ref-get-label-context (label)
3215 "Return a string of context around a label."
3218 (goto-char (point-min))
3219 (when (re-search-forward
3220 (format "label:%s\\b" label) nil t)
3221 (throw 'result (buffer-substring
3230 (goto-char (point-min))
3231 (when (re-search-forward
3232 (format "\\label{%s}" label) nil t)
3233 (throw 'result (buffer-substring
3242 (goto-char (point-min))
3243 (when (re-search-forward
3244 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
3245 (throw 'result (buffer-substring
3254 (goto-char (point-min))
3255 (when (re-search-forward
3256 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
3257 (throw 'result (buffer-substring
3265 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
3268 (defun org-ref-link-message ()
3269 "Print a minibuffer message about the link that point is on."
3271 (when (eq major-mode 'org-mode)
3272 (let* ((object (org-element-context))
3273 (type (org-element-property :type object)))
3277 ((-contains? org-ref-cite-types type)
3278 (message (org-ref-get-citation-string-at-point)))
3280 ;; message some context about the label we are referring to
3281 ((string= type "ref")
3282 (message "%scount: %s"
3283 (org-ref-get-label-context
3284 (org-element-property :path object))
3285 (org-ref-count-labels
3286 (org-element-property :path object))))
3288 ((string= type "eqref")
3289 (message "%scount: %s"
3290 (org-ref-get-label-context
3291 (org-element-property :path object))
3292 (org-ref-count-labels
3293 (org-element-property :path object))))
3295 ;; message the count
3296 ((string= type "label")
3297 (let ((count (org-ref-count-labels
3298 (org-element-property :path object))))
3299 ;; get plurality on occurrence correct
3301 (number-to-string count)
3303 (when (or (= count 0)
3307 ((string= type "custom-id")
3309 (org-open-link-from-string
3310 (format "[[#%s]]" (org-element-property :path object)))
3311 (message "%s" (org-get-heading))))
3313 ;; check if the bibliography files exist.
3314 ((string= type "bibliography")
3316 ;; object is the link you clicked on
3317 (object (org-element-context))
3318 (link-string (org-element-property :path object))
3319 (link-string-beginning)
3322 (goto-char (org-element-property :begin object))
3323 (search-forward link-string nil nil 1)
3324 (setq link-string-beginning (match-beginning 0))
3325 (setq link-string-end (match-end 0)))
3327 ;; make sure we are in link and not before the :
3328 (when (> link-string-beginning (point))
3329 (goto-char link-string-beginning))
3331 ;; now if we have comma separated bibliographies
3332 ;; we find the one clicked on. we want to
3333 ;; search forward to next comma from point
3335 (if (search-forward "," link-string-end 1 1)
3336 (setq key-end (- (match-end 0) 1)) ; we found a match
3337 (setq key-end (point)))) ; no comma found so take the point
3339 ;; and backward to previous comma from point
3341 (if (search-backward "," link-string-beginning 1 1)
3342 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
3343 (setq key-beginning (point)))) ; no match found
3344 ;; save the key we clicked on.
3346 (org-ref-strip-string
3347 (buffer-substring key-beginning key-end)))
3348 (if (file-exists-p bibfile)
3349 (message "%s exists." bibfile)
3350 (message "!!! %s NOT FOUND !!!" bibfile))))
3355 I like convenience. Here are some aliases for faster typing.
3357 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3358 (defalias 'oro 'org-ref-open-citation-at-point)
3359 (defalias 'orc 'org-ref-citation-at-point)
3360 (defalias 'orp 'org-ref-open-pdf-at-point)
3361 (defalias 'oru 'org-ref-open-url-at-point)
3362 (defalias 'orn 'org-ref-open-notes-at-point)
3363 (defalias 'ornr 'org-ref-open-notes-from-reftex)
3365 (defalias 'orib 'org-ref-insert-bibliography-link)
3366 (defalias 'oric 'org-ref-insert-cite-link)
3367 (defalias 'orir 'org-ref-insert-ref-link)
3368 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
3370 (defalias 'orcb 'org-ref-clean-bibtex-entry)
3373 [[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.
3375 1. Make the default action to insert selected keys.
3376 2. Make open entry second action
3377 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3378 (setq helm-source-bibtex
3379 '((name . "BibTeX entries")
3380 (init . helm-bibtex-init)
3381 (candidates . helm-bibtex-candidates)
3382 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3383 (action . (("Insert citation" . helm-bibtex-insert-citation)
3384 ("Show entry" . helm-bibtex-show-entry)
3385 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3386 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3387 ("Insert reference" . helm-bibtex-insert-reference)
3388 ("Insert BibTeX key" . helm-bibtex-insert-key)
3389 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3390 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3391 ("Edit notes" . helm-bibtex-edit-notes)
3395 Now, let us define a function that inserts the cite links:
3396 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3397 (defun helm-bibtex-format-org-ref (keys)
3398 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3399 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.
3401 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3403 C-u C-u will change the key at point to the selected keys.
3405 (let* ((object (org-element-context))
3406 (last-char (save-excursion
3407 (goto-char (org-element-property :end object))
3409 (if (looking-at " ")
3413 ;; case where we are in a link
3414 ((and (equal (org-element-type object) 'link)
3417 (org-element-property :type object)))
3419 ;; no prefix. append keys
3420 ((equal helm-current-prefix-arg nil)
3421 (goto-char (org-element-property :end object))
3422 (while (looking-back " ") (backward-char))
3423 (insert (concat "," (mapconcat 'identity keys ","))))
3424 ;; double prefix, replace key at point
3425 ((equal helm-current-prefix-arg '(16))
3426 (setf (buffer-substring
3427 (org-element-property :begin object)
3428 (org-element-property :end object))
3430 (replace-regexp-in-string
3431 (car (org-ref-get-bibtex-key-and-file)) ; key
3432 (mapconcat 'identity keys ",") ; new keys
3433 (org-element-property :raw-link object))
3434 ;; replace space at end to avoid collapsing into next word.
3436 ;; and we want to go to the end of the new link
3438 (org-element-property :end (org-element-context))))
3440 (message "Not found"))))
3442 ;; We are next to a link, and we want to append
3443 ;; next to a link means one character back is on a link.
3446 (and (equal (org-element-type (org-element-context)) 'link)
3449 (org-element-property :type (org-element-context)))))
3450 (while (looking-back " ") (backward-char))
3451 (insert (concat "," (mapconcat 'identity keys ","))))
3453 ;; insert fresh link
3455 ;;(message-box "fresh link")
3457 (concat (if (equal helm-current-prefix-arg '(4))
3458 (helm :sources `((name . "link types")
3459 (candidates . ,org-ref-cite-types)
3460 (action . (lambda (x) x))))
3461 org-ref-default-citation-link)
3463 (s-join "," keys))))))
3464 ;; return empty string for helm
3467 (setq helm-bibtex-format-citation-functions
3468 '((org-mode . helm-bibtex-format-org-ref)))
3470 (defun org-ref-helm-insert-cite-link (arg)
3471 "org-ref function to use helm-bibtex to insert a citation link.
3472 With one prefix arg, insert a ref link.
3473 With two prefix args, insert a label link."
3477 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3480 (org-ref-helm-insert-ref-link))
3482 (org-ref-helm-insert-label-link))))
3484 (require 'helm-bibtex)
3486 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3487 (setq helm-bibtex-fallback-options
3488 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3490 (setq helm-bibtex-fallback-options
3493 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3494 helm-bibtex-fallback-options))
3496 (setq helm-bibtex-fallback-options
3497 (-insert-at 1 '("WOS" . "http://gateway.webofknowledge.com/gateway/Gateway.cgi?topic=%s&GWVersion=2&SrcApp=WEB&SrcAuth=HSB&DestApp=UA&DestLinkType=GeneralSearchSummary") helm-bibtex-fallback-options))
3500 ** A helm click menu
3501 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.
3502 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3503 (defun org-ref-get-citation-string-at-point ()
3504 "Get a string of a formatted citation"
3506 (let* ((results (org-ref-get-bibtex-key-and-file))
3508 (bibfile (cdr results)))
3512 (insert-file-contents bibfile)
3513 (bibtex-search-entry key)
3514 (org-ref-bib-citation)))
3515 "!!! No entry found !!!" )))
3517 (defun org-ref-cite-candidates ()
3518 "Generate the list of possible candidates for click actions on a cite link.
3519 Checks for pdf and doi, and add appropriate functions."
3521 (let* ((results (org-ref-get-bibtex-key-and-file))
3523 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3524 (bibfile (cdr results))
3525 (url (save-excursion
3527 (insert-file-contents bibfile)
3528 (bibtex-search-entry key)
3529 (bibtex-autokey-get-field "url"))))
3530 (doi (save-excursion
3532 (insert-file-contents bibfile)
3533 (bibtex-search-entry key)
3534 ;; I like this better than bibtex-url which does not always find
3536 (bibtex-autokey-get-field "doi"))))
3537 (candidates `(("Quit" . org-ref-citation-at-point)
3538 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3539 ;; for some reason, when there is no doi or url, they are returned as "". I
3540 ;; prefer nil so we correct this here.
3541 (when (string= doi "") (setq doi nil))
3542 (when (string= url "") (setq url nil))
3544 ;; Conditional pdf functions
3545 (if (file-exists-p pdf-file)
3548 '("Open pdf" . org-ref-open-pdf-at-point)
3552 '("Try to get pdf" . (lambda ()
3553 (save-window-excursion
3554 (org-ref-open-citation-at-point)
3555 (bibtex-beginning-of-entry)
3556 (doi-utils-get-bibtex-entry-pdf))))
3562 '("Open notes" . org-ref-open-notes-at-point)
3565 ;; conditional url and doi functions
3569 '("Open in browser" . org-ref-open-url-at-point)
3574 (add-to-list 'candidates x t))
3575 `(("WOS" . org-ref-wos-at-point)
3576 ("Related articles in WOS" . org-ref-wos-related-at-point)
3577 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3578 ("Google Scholar" . org-ref-google-scholar-at-point)
3579 ("Pubmed" . org-ref-pubmed-at-point)
3580 ("Crossref" . org-ref-crossref-at-point)
3585 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3590 '("Copy key to clipboard" . (lambda ()
3592 (car (org-ref-get-bibtex-key-and-file)))))
3597 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3602 '("Email bibtex entry and pdf" . (lambda ()
3604 (org-ref-open-citation-at-point)
3605 (email-bibtex-entry))))
3607 ;; finally return a numbered list of the candidates
3609 for cell in candidates
3610 collect (cons (format "%2s. %s" i (car cell))
3614 (defvar org-ref-helm-user-candidates '()
3615 "List of user-defined candidates to act when clicking on a cite link.
3616 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.
3619 ;; example of adding your own function
3621 'org-ref-helm-user-candidates
3622 '("Example" . (lambda () (message-box "You did it!")))
3625 (defun org-ref-cite-click-helm (key)
3627 1. get name and candidates before entering helm because we need the org-buffer.
3628 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer."
3630 (let ((name (org-ref-get-citation-string-at-point))
3631 (candidates (org-ref-cite-candidates))
3632 (cb (current-buffer)))
3634 (helm :sources `(((name . ,name)
3635 (candidates . ,candidates)
3636 (action . (lambda (f)
3637 (switch-to-buffer cb)
3639 ((name . "User functions")
3640 (candidates . ,org-ref-helm-user-candidates)
3641 (action . (lambda (f)
3642 (switch-to-buffer cb)
3648 : org-ref-cite-click-helm
3651 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3656 This code will tangle the elisp code out to org-ref.el and load it.
3658 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
3660 Alternatively you may use:
3662 [[elisp:(org-babel-load-file "org-ref.org")]]