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 1. Get minibuffer messages for the cite/ref/label link under point
17 With helm integration (default) you can:
19 1. C-c ] to insert a citation link
21 - Enter to insert or append citation(s)
22 - C-u Enter to insert an alternative cite link
23 - C-u C-u Enter to replace the citation at point
24 2. C-u C-c ] to insert a ref link with helm completion
25 3. C-u C-u C-c ] to insert a label with completion
26 4. M-x org-ref to get a helm completion buffer with link checks, utilities and export options
29 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
30 ;;; org-ref.el --- setup bibliography, cite, ref and label org-mode links.
32 ;; Copyright(C) 2014 John Kitchin
34 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
35 ;; This file is not currently part of GNU Emacs.
37 ;; This program is free software; you can redistribute it and/or
38 ;; modify it under the terms of the GNU General Public License as
39 ;; published by the Free Software Foundation; either version 2, or (at
40 ;; your option) any later version.
42 ;; This program is distributed in the hope that it will be useful, but
43 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
44 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
45 ;; General Public License for more details.
47 ;; You should have received a copy of the GNU General Public License
48 ;; along with this program ; see the file COPYING. If not, write to
49 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
50 ;; Boston, MA 02111-1307, USA.
54 ;; Lisp code to setup bibliography cite, ref and label org-mode links. also
55 ;; sets up reftex and helm for org-mode citations. The links are clickable and
56 ;; do things that are useful. You should really read org-ref.org for details.
58 ;; Package-Requires: ((dash) (helm) (helm-bibtex))
62 The only external require is reftex-cite
64 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
65 (require 'reftex-cite)
68 (require 'helm-bibtex)
72 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.
74 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
76 "customization group for org-ref")
78 (defcustom org-ref-bibliography-notes
80 "filename to where you will put all your notes about an entry in
81 the default bibliography."
85 (defcustom org-ref-default-bibliography
87 "list of bibtex files to search for. You should use full-paths for each file."
88 :type '(repeat :tag "List of bibtex files" file)
91 (defcustom org-ref-pdf-directory
93 "directory where pdfs are stored by key. put a trailing / in"
97 (defcustom org-ref-default-citation-link
99 "The default type of citation link to use"
103 (defcustom org-ref-insert-cite-key
105 "Keyboard shortcut to insert a citation."
109 (defcustom org-ref-bibliography-entry-format
110 '(("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>.")
112 ("book" . "%a, %t, %u (%y).")
114 ("proceedings" . "%e, %t in %S, %u (%y).")
116 ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
118 "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."
122 (defcustom org-ref-open-notes-function
128 ;;(org-tree-to-indirect-buffer)
129 (outline-previous-visible-heading 1)
130 (recenter-top-bottom 0))
131 "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"
136 (defcustom org-ref-open-pdf-function
137 'org-ref-open-pdf-at-point
138 "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'."
143 (defcustom org-ref-insert-cite-function
144 'org-ref-helm-insert-cite-link
145 "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."
150 (defcustom org-ref-cite-onclick-function
151 'org-ref-cite-click-helm
152 "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."
156 (defcustom org-ref-show-citation-on-enter t
157 "If non-nil add a hook function to show the citation summary in
158 the minibuffer just by putting the cursor in a link"
163 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.
165 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
166 (defcustom org-ref-cite-types
167 '("cite" "nocite" ;; the default latex cite commands
168 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
169 "citet" "citet*" "citep" "citep*"
170 "citealt" "citealt*" "citealp" "citealp*"
172 "citeauthor" "citeauthor*"
173 "citeyear" "citeyear*"
174 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
176 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
178 "parencite" "Parencite"
179 "footcite" "footcitetext"
180 "textcite" "Textcite"
181 "smartcite" "Smartcite"
182 "cite*" "parencite*" "supercite"
183 "autocite" "Autocite" "autocite*" "Autocite*"
185 "citetitle" "citetitle*"
186 "citedate" "citedate*"
188 "fullcite" "footfullcite"
189 ;; "volcite" "Volcite" cannot support the syntax
190 "notecite" "Notecite"
191 "pnotecite" "Pnotecite"
193 ;; multicites. Very limited support for these.
194 "cites" "Cites" "parencites" "Parencites"
195 "footcites" "footcitetexts"
196 "smartcites" "Smartcites" "textcites" "Textcites"
197 "supercites" "autocites" "Autocites"
198 ;; for the bibentry package
201 "List of citation types known in org-ref"
202 :type '(repeat :tag "List of citation types" string)
206 We need a hook variable to store user-defined bibtex entry cleaning functions
207 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
208 (defcustom org-ref-clean-bibtex-entry-hook nil
209 "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
215 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
216 (defvar org-ref-bibliography-files
218 "variable to hold bibliography files to be searched")
221 ** org-mode / reftex setup
223 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.
225 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
227 (defun org-mode-reftex-setup ()
228 (and (buffer-file-name)
229 (file-exists-p (buffer-file-name))
230 (global-auto-revert-mode t)
231 ;; I do not remember why I put this next line in. It doesn't
232 ;; work for org-files. Nothing very bad happens, but it gives
233 ;; an annoying error. Commenting it out for now.
236 (make-local-variable 'reftex-cite-format)
237 (setq reftex-cite-format 'org))
239 ;; define key for inserting citations
240 (define-key org-mode-map
241 (kbd org-ref-insert-cite-key)
242 org-ref-insert-cite-function)
244 (when org-ref-show-citation-on-enter
245 (setq org-ref-message-timer
246 (run-with-idle-timer 0.5 t 'org-ref-link-message)))
248 (defun org-ref-show-link-messages ()
249 "Turn on link messages. You will see a message in the
250 minibuffer when on a cite, ref or label link."
252 (setq org-ref-message-timer
253 (run-with-idle-timer 0.5 t 'org-ref-link-message))
255 (defun org-ref-cancel-link-messages ()
256 "Stop showing messages in minibuffer when on a link."
258 (cancel-timer org-ref-message-timer))
260 ;; this approach caused the selected region to not be highlighted any more.
261 ; (add-hook 'post-command-hook 'org-ref-link-message))
262 ; (remove-hook 'post-command-hook 'org-ref-link-message))
264 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
266 (eval-after-load 'reftex-vars
268 (add-to-list 'reftex-cite-format-builtin
269 '(org "Org-mode citation"
270 ((?\C-m . "cite:%l") ; default
271 (?d . ",%l") ; for appending
277 (?h . "citeauthor:%l")
278 (?H . "citeauthor*:%l")
285 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.
287 #+BEGIN_SRC emacs-lisp :tangle no
289 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
290 (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l")
291 (?z . "newcite:%l"))))
294 You can define a new citation link like this:
295 #+BEGIN_SRC emacs-lisp :tangle no
296 (org-ref-define-citation-link "citez" ?z)
300 Most of this library is the creation of functional links to help with references and citations.
302 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.
304 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
305 (defun org-ref-strip-string (string)
306 "strip leading and trailing whitespace from the string"
307 (replace-regexp-in-string
308 (concat search-whitespace-regexp "$" ) ""
309 (replace-regexp-in-string
310 (concat "^" search-whitespace-regexp ) "" string)))
313 It is helpful to make the previous function operate on a list of strings here.
315 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
316 (defun org-ref-split-and-strip-string (string)
317 "split key-string and strip keys. Assumes the key-string is comma delimited"
318 (mapcar 'org-ref-strip-string (split-string string ",")))
321 ** bibliography and bibliographystyle
322 *** An html bibliography
324 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.
326 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
327 (defun org-ref-reftex-get-bib-field (field entry &optional format)
328 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
330 (setq result (reftex-get-bib-field field entry format))
331 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
332 (setq result (substring result 1 -1)))
333 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
334 (setq result (substring result 1 -1)))
337 (defun org-ref-reftex-format-citation (entry format)
338 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
339 to the format argument. The format is a string with these percent escapes.
341 In the format, the following percent escapes will be expanded.
343 %l The BibTeX label of the citation.
344 %a List of author names, see also `reftex-cite-punctuation'.
345 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
346 %A First author name only.
347 %e Works like %a, but on list of editor names. (%2e and %E work a well)
349 It is also possible to access all other BibTeX database fields:
350 %b booktitle %c chapter %d edition %h howpublished
351 %i institution %j journal %k key %m month
352 %n number %o organization %p pages %P first page
353 %r address %s school %u publisher %t title
355 %B booktitle, abbreviated %T title, abbreviated
360 Usually, only %l is needed. The other stuff is mainly for the echo area
361 display, and for (setq reftex-comment-citations t).
363 %< as a special operator kills punctuation and space around it after the
364 string has been formatted.
366 A pair of square brackets indicates an optional argument, and RefTeX
367 will prompt for the values of these arguments.
369 Beware that all this only works with BibTeX database files. When
370 citations are made from the \bibitems in an explicit thebibliography
371 environment, only %l is available."
372 ;; Format a citation from the info in the BibTeX ENTRY
374 (unless (stringp format) (setq format "\\cite{%l}"))
376 (if (and reftex-comment-citations
377 (string-match "%l" reftex-cite-comment-format))
378 (error "reftex-cite-comment-format contains invalid %%l"))
381 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
383 (let ((n (string-to-number (match-string 4 format)))
384 (l (string-to-char (match-string 5 format)))
390 (org-ref-reftex-get-bib-field "&key" entry)
391 (if reftex-comment-citations
392 reftex-cite-comment-format
394 ((= l ?a) (reftex-format-names
395 (reftex-get-bib-names "author" entry)
397 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
398 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
399 ((= l ?B) (reftex-abbreviate-title
400 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
401 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
402 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
403 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
404 ((= l ?e) (reftex-format-names
405 (reftex-get-bib-names "editor" entry)
407 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
408 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
409 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
410 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
411 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
412 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
413 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
414 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
415 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
416 ((= l ?P) (car (split-string
417 (org-ref-reftex-get-bib-field "pages" entry)
419 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
420 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
421 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
422 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
423 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
424 ;; strip enclosing brackets from title if they are there
425 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
426 ((= l ?T) (reftex-abbreviate-title
427 (org-ref-reftex-get-bib-field "title" entry)))
428 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
429 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
432 (setq b (match-beginning 2) e (match-end 2))
433 (setq b (match-beginning 3) e (match-end 3)))
434 (setq format (concat (substring format 0 b) rpl (substring format e)))))
435 (while (string-match "%%" format)
436 (setq format (replace-match "%" t t format)))
437 (while (string-match "[ ,.;:]*%<" format)
438 (setq format (replace-match "" t t format)))
439 ;; also replace carriage returns, tabs, and multiple whitespaces
440 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
443 (defun org-ref-get-bibtex-entry-citation (key)
444 "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
446 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
447 (file) (entry) (bibtex-entry) (entry-type) (format))
449 (setq file (catch 'result
450 (loop for file in org-ref-bibliography-files do
451 (if (org-ref-key-in-file-p key (file-truename file))
453 (message "%s not found in %s" key (file-truename file))))))
456 (insert-file-contents file)
457 (bibtex-search-entry key nil 0)
458 (setq bibtex-entry (bibtex-parse-entry))
459 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
460 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
462 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
464 (bibtex-narrow-to-entry)
465 (setq entry (buffer-string)))))
470 : org-ref-reftex-format-citation
472 Here is how to use the function. You call it with point in an entry in a bibtex file.
474 #+BEGIN_SRC emacs-lisp :tangle no
475 (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>."))
476 (org-ref-get-bibtex-entry-citation "armiento-2014-high"))
479 : 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>.
481 I am not sure why full author names are not used.
483 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
485 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
486 (defun org-ref-get-bibtex-keys ()
487 "return a list of unique keys in the buffer."
489 (org-element-map (org-element-parse-buffer) 'link
491 (let ((plist (nth 1 link)))
492 (when (-contains? org-ref-cite-types (plist-get plist ':type))
495 (org-ref-split-and-strip-string (plist-get plist ':path)))
496 (when (not (-contains? keys key))
497 (setq keys (append keys (list key)))))))))
498 ;; Sort keys alphabetically
499 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
503 This function gets the html for one entry.
505 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
506 (defun org-ref-get-bibtex-entry-html (key)
507 "returns an html string for the bibliography entry corresponding to key"
509 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
512 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
514 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
515 (defun org-ref-get-html-bibliography ()
516 "Create an html bibliography when there are keys"
517 (let ((keys (org-ref-get-bibtex-keys)))
519 (concat "<h1>Bibliography</h1>
521 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
525 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.
527 *** An org bibliography
528 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.
530 First, we get the string for a single entry.
531 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
532 (defun org-ref-get-bibtex-entry-org (key)
533 "returns an org string for the bibliography entry corresponding to key"
534 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
535 (file) (entry) (bibtex-entry) (entry-type) (format))
537 (setq file (catch 'result
538 (loop for file in org-ref-bibliography-files do
539 (if (org-ref-key-in-file-p key (file-truename file))
541 (message "%s not found in %s" key (file-truename file))))))
544 (insert-file-contents file)
545 (bibtex-search-entry key nil 0)
546 (setq entry (bibtex-parse-entry))
551 " (org-ref-reftex-get-bib-field "author" entry)
552 (org-ref-reftex-get-bib-field "title" entry)
553 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
554 (mapconcat (lambda (element) (format " :%s: %s"
555 (upcase (car element))
561 Now, we loop over the keys, and combine all the entries into a bibliography.
562 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
563 (defun org-ref-get-org-bibliography ()
564 "Create an org bibliography when there are keys"
565 (let ((keys (org-ref-get-bibtex-keys)))
567 (concat "* Bibliography
569 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
573 *** An ascii bibliography
575 This function gets the html for one entry.
577 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
578 (defun org-ref-get-bibtex-entry-ascii (key)
579 "returns an ascii string for the bibliography entry corresponding to key"
581 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
584 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
586 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
587 (defun org-ref-get-ascii-bibliography ()
588 "Create an html bibliography when there are keys"
589 (let ((keys (org-ref-get-bibtex-keys)))
595 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
601 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.
603 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
604 (org-add-link-type "bibliography"
605 ;; this code is run on clicking. The bibliography
606 ;; may contain multiple files. this code finds the
607 ;; one you clicked on and opens it.
608 (lambda (link-string)
609 ;; get link-string boundaries
610 ;; we have to go to the beginning of the line, and then search forward
613 ;; object is the link you clicked on
614 (object (org-element-context))
615 (link-string-beginning)
619 (goto-char (org-element-property :begin object))
620 (search-forward link-string nil nil 1)
621 (setq link-string-beginning (match-beginning 0))
622 (setq link-string-end (match-end 0)))
624 ;; We set the reftex-default-bibliography
625 ;; here. it should be a local variable only in
626 ;; the current buffer. We need this for using
627 ;; reftex to do citations.
628 (set (make-local-variable 'reftex-default-bibliography)
629 (split-string (org-element-property :path object) ","))
631 ;; now if we have comma separated bibliographies
632 ;; we find the one clicked on. we want to
633 ;; search forward to next comma from point
635 (if (search-forward "," link-string-end 1 1)
636 (setq key-end (- (match-end 0) 1)) ; we found a match
637 (setq key-end (point)))) ; no comma found so take the point
638 ;; and backward to previous comma from point
640 (if (search-backward "," link-string-beginning 1 1)
641 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
642 (setq key-beginning (point)))) ; no match found
643 ;; save the key we clicked on.
644 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
645 (find-file bibfile))) ; open file on click
648 (lambda (keyword desc format)
650 ((eq format 'org) (org-ref-get-org-bibliography))
651 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
652 ((eq format 'html) (org-ref-get-html-bibliography))
654 ;; write out the latex bibliography command
655 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
656 (mapcar 'expand-file-name
657 (split-string keyword ","))
662 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.
665 \input{project-description.bbl}
668 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.
670 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
671 (org-add-link-type "nobibliography"
672 ;; this code is run on clicking. The bibliography
673 ;; may contain multiple files. this code finds the
674 ;; one you clicked on and opens it.
675 (lambda (link-string)
676 ;; get link-string boundaries
677 ;; we have to go to the beginning of the line, and then search forward
680 ;; object is the link you clicked on
681 (object (org-element-context))
683 (link-string-beginning)
687 (goto-char (org-element-property :begin object))
688 (search-forward link-string nil nil 1)
689 (setq link-string-beginning (match-beginning 0))
690 (setq link-string-end (match-end 0)))
692 ;; We set the reftex-default-bibliography
693 ;; here. it should be a local variable only in
694 ;; the current buffer. We need this for using
695 ;; reftex to do citations.
696 (set (make-local-variable 'reftex-default-bibliography)
697 (split-string (org-element-property :path object) ","))
699 ;; now if we have comma separated bibliographies
700 ;; we find the one clicked on. we want to
701 ;; search forward to next comma from point
703 (if (search-forward "," link-string-end 1 1)
704 (setq key-end (- (match-end 0) 1)) ; we found a match
705 (setq key-end (point)))) ; no comma found so take the point
706 ;; and backward to previous comma from point
708 (if (search-backward "," link-string-beginning 1 1)
709 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
710 (setq key-beginning (point)))) ; no match found
711 ;; save the key we clicked on.
712 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
713 (find-file bibfile))) ; open file on click
716 (lambda (keyword desc format)
718 ((eq format 'org) (org-ref-get-org-bibliography))
719 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
720 ((eq format 'html) (org-ref-get-html-bibliography))
722 ;; write out the latex bibliography command
724 ; (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
725 ; (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
726 ; (mapcar 'expand-file-name
727 ; (split-string keyword ","))
730 (format "\\nobibliography{%s}"
731 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
732 (mapcar 'expand-file-name
733 (split-string keyword ","))
739 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
740 (org-add-link-type "printbibliography"
741 (lambda (arg) (message "Nothing implemented for clicking here."))
742 (lambda (keyword desc format)
744 ((eq format 'org) (org-ref-get-org-bibliography))
745 ((eq format 'html) (org-ref-get-html-bibliography))
747 ;; write out the biblatex bibliography command
748 "\\printbibliography"))
752 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, ...
754 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
755 (org-add-link-type "bibliographystyle"
756 (lambda (arg) (message "Nothing implemented for clicking here."))
757 (lambda (keyword desc format)
760 ;; write out the latex bibliography command
761 (format "\\bibliographystyle{%s}" keyword)))))
764 *** Completion for bibliography link
767 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
768 (defun org-bibliography-complete-link (&optional arg)
769 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
771 (defun org-ref-insert-bibliography-link ()
772 "insert a bibliography with completion"
774 (insert (org-bibliography-complete-link)))
778 This is apparently used for biblatex.
779 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
780 (org-add-link-type "addbibresource"
781 ;; this code is run on clicking. The addbibresource
782 ;; may contain multiple files. this code finds the
783 ;; one you clicked on and opens it.
784 (lambda (link-string)
785 ;; get link-string boundaries
786 ;; we have to go to the beginning of the line, and then search forward
789 ;; object is the link you clicked on
790 (object (org-element-context))
792 (link-string-beginning)
796 (goto-char (org-element-property :begin object))
797 (search-forward link-string nil nil 1)
798 (setq link-string-beginning (match-beginning 0))
799 (setq link-string-end (match-end 0)))
801 ;; We set the reftex-default-addbibresource
802 ;; here. it should be a local variable only in
803 ;; the current buffer. We need this for using
804 ;; reftex to do citations.
805 (set (make-local-variable 'reftex-default-addbibresource)
806 (split-string (org-element-property :path object) ","))
808 ;; now if we have comma separated bibliographies
809 ;; we find the one clicked on. we want to
810 ;; search forward to next comma from point
812 (if (search-forward "," link-string-end 1 1)
813 (setq key-end (- (match-end 0) 1)) ; we found a match
814 (setq key-end (point)))) ; no comma found so take the point
815 ;; and backward to previous comma from point
817 (if (search-backward "," link-string-beginning 1 1)
818 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
819 (setq key-beginning (point)))) ; no match found
820 ;; save the key we clicked on.
821 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
822 (find-file bibfile))) ; open file on click
825 (lambda (keyword desc format)
827 ((eq format 'html) (format "")); no output for html
829 ;; write out the latex addbibresource command
830 (format "\\addbibresource{%s}" keyword)))))
835 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.
837 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
838 (defun org-ref-list-of-figures (&optional arg)
839 "Generate buffer with list of figures in them"
841 (save-excursion (widen)
842 (let* ((c-b (buffer-name))
845 (org-element-map (org-element-parse-buffer) 'link
847 "create a link for to the figure"
849 (and (string= (org-element-property :type link) "file")
851 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
852 (org-element-property :path link)))
855 (let* ((start (org-element-property :begin link))
856 (parent (car (cdr (org-element-property :parent link))))
857 (caption (caaar (plist-get parent :caption)))
858 (name (plist-get parent :name)))
861 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
862 c-b start counter (or name "") caption)
864 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
865 c-b start counter (or name "")))))))))
866 (switch-to-buffer "*List of Figures*")
867 (setq buffer-read-only nil)
870 (insert (mapconcat 'identity list-of-figures ""))
871 (setq buffer-read-only t)
872 (use-local-map (copy-keymap org-mode-map))
873 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
877 'org-ref-list-of-figures ; on click
878 (lambda (keyword desc format)
881 (format "\\listoffigures")))))
886 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
887 (defun org-ref-list-of-tables (&optional arg)
888 "Generate a buffer with a list of tables"
892 (let* ((c-b (buffer-name))
895 (org-element-map (org-element-parse-buffer 'element) 'table
897 "create a link for to the table"
899 (let ((start (org-element-property :begin table))
900 (name (org-element-property :name table))
901 (caption (caaar (org-element-property :caption table))))
904 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
905 c-b start counter (or name "") caption)
907 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
908 c-b start counter (or name ""))))))))
909 (switch-to-buffer "*List of Tables*")
910 (setq buffer-read-only nil)
913 (insert (mapconcat 'identity list-of-tables ""))
914 (setq buffer-read-only t)
915 (use-local-map (copy-keymap org-mode-map))
916 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
920 'org-ref-list-of-tables
921 (lambda (keyword desc format)
924 (format "\\listoftables")))))
928 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.
930 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
931 (defun org-ref-count-labels (label)
932 "Counts number of matches for label in the document"
933 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
934 ;; for tblname, it is not enough to get word boundary
935 ;; tab-little and tab-little-2 match then.
936 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
937 (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max))
938 ;; this is the org-format #+label:
939 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
940 (let ((custom-id-count 0))
943 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
944 (setq custom-id-count (+ 1 custom-id-count)))))
950 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
951 (let ((count (org-ref-count-labels label)))
952 (message (format "%s occurence%s"
958 (org-ref-count-labels label))))
959 (lambda (keyword desc format)
961 ((eq format 'html) (format "(<label>%s</label>)" path))
963 (format "\\label{%s}" keyword)))))
966 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.
968 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
969 (defun org-label-store-link ()
970 "store a link to a label. The output will be a ref to that label"
971 ;; First we have to make sure we are on a label link.
972 (let* ((object (org-element-context)))
973 (when (and (equal (org-element-type object) 'link)
974 (equal (org-element-property :type object) "label"))
975 (org-store-link-props
977 :link (concat "ref:" (org-element-property :path object))))
979 ;; Store link on table
980 (when (equal (org-element-type object) 'table)
981 (org-store-link-props
983 :link (concat "ref:" (org-element-property :name object))))
985 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
986 ;; store link on heading with custom_id
987 ; (when (and (equal (org-element-type object) 'headline)
988 ; (org-entry-get (point) "CUSTOM_ID"))
989 ; (org-store-link-props
991 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
993 ;; and to #+label: lines
994 (when (and (equal (org-element-type object) 'paragraph)
995 (org-element-property :name object))
996 (org-store-link-props
998 :link (concat "ref:" (org-element-property :name object))))
1001 (add-hook 'org-store-link-functions 'org-label-store-link)
1005 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.
1007 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
1009 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1013 "on clicking goto the label. Navigate back with C-c &"
1014 (org-mark-ring-push)
1015 ;; next search from beginning of the buffer
1017 ;; it is possible you would not find the label if narrowing is in effect
1024 (goto-char (point-min))
1025 (re-search-forward (format "label:%s\\b" label) nil t))
1029 (goto-char (point-min))
1030 (re-search-forward (format "\\label{%s}" label) nil t))
1032 ;; #+label: name org-definition
1034 (goto-char (point-min))
1035 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1039 (goto-char (point-min))
1040 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1042 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1043 ;; you need [[#label]] links.
1046 ; (goto-char (point-min))
1047 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1049 ;; we did not find anything, so go back to where we came
1050 (org-mark-ring-goto)
1051 (error "%s not found" label))
1053 (message "go back with (org-mark-ring-goto) `C-c &`"))
1055 (lambda (keyword desc format)
1057 ((eq format 'html) (format "(<ref>%s</ref>)" path))
1059 (format "\\ref{%s}" keyword)))))
1062 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.
1064 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1065 (defun org-ref-get-org-labels ()
1066 "find #+LABEL: labels"
1068 (goto-char (point-min))
1069 (let ((matches '()))
1070 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1071 (add-to-list 'matches (match-string-no-properties 1) t))
1075 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1076 (defun org-ref-get-custom-ids ()
1077 "return a list of custom_id properties in the buffer"
1078 (let ((results '()) custom_id)
1081 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1082 (when (not (null custom_id))
1083 (setq results (append results (list custom_id)))))))
1087 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
1088 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1089 (defun org-ref-get-latex-labels ()
1091 (goto-char (point-min))
1092 (let ((matches '()))
1093 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1094 (add-to-list 'matches (match-string-no-properties 1) t))
1098 Finally, we get the table names.
1100 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1101 (defun org-ref-get-tblnames ()
1102 (org-element-map (org-element-parse-buffer 'element) 'table
1104 (org-element-property :name table))))
1107 Now, we can put all the labels together which will give us a list of candidates.
1109 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1110 (defun org-ref-get-labels ()
1111 "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
1115 (goto-char (point-min))
1116 (let ((matches '()))
1117 (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1118 (add-to-list 'matches (match-string-no-properties 1) t))
1119 (append matches (org-ref-get-org-labels) (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
1122 Let us make a helm function to insert a label link. This will help you enter unique labels.
1123 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1124 (defun org-ref-helm-insert-label-link ()
1125 "Insert a label link. helm just shows you what labels already exist.
1126 If you are on a label link, replace it."
1128 (let* ((labels (org-ref-get-labels))
1129 (cb (current-buffer)))
1130 (helm :sources `(((name . "Existing labels")
1131 (candidates . ,labels)
1132 ;; default action is to open to the label
1133 (action . (lambda (label)
1134 ;; unfortunately I do not have markers here
1135 (org-open-link-from-string (format "ref:%s" label))))
1136 ;; if you select a label, replace current one
1137 (action . (lambda (label)
1138 (switch-to-buffer ,cb)
1140 ;; no prefix or on a link
1141 ((equal helm-current-prefix-arg nil)
1142 (let* ((object (org-element-context))
1143 (last-char (save-excursion
1144 (goto-char (org-element-property :end object))
1146 (if (looking-at " ")
1149 (when (-contains? '("label")
1150 (org-element-property :type object))
1151 ;; we are on a link, so replace it.
1154 (org-element-property :begin object)
1155 (org-element-property :end object))
1157 (replace-regexp-in-string
1158 (org-element-property :path object)
1160 (org-element-property :raw-link object))
1162 ;; no prefix options defined
1164 ;; no matching selection creates a new label
1165 ((name . "Create new label")
1167 ;; default action creates a new label, or replaces old one
1168 (action . (lambda (label)
1169 (switch-to-buffer ,cb)
1170 (let* ((object (org-element-context))
1171 (last-char (save-excursion
1172 (goto-char (org-element-property :end object))
1174 (if (looking-at " ")
1177 (if (-contains? '("label")
1178 (org-element-property :type object))
1179 ;; we are on a link, so replace it.
1182 (org-element-property :begin object)
1183 (org-element-property :end object))
1185 (replace-regexp-in-string
1186 (org-element-property :path object)
1188 (org-element-property :raw-link object))
1195 helm-pattern))))))))))))
1198 Now we create the completion function. This works from the org-machinery, e.g. if you type C-c C-l to insert a link, and use completion by pressing tab.
1200 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1201 (defun org-ref-complete-link (&optional arg)
1202 "Completion function for ref links"
1204 (setq label (completing-read "label: " (org-ref-get-labels)))
1205 (format "ref:%s" label)))
1208 Alternatively, you may want to just call a function that inserts a link with completion:
1210 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1211 (defun org-ref-insert-ref-link ()
1213 (insert (org-ref-complete-link)))
1216 Another alternative ref insertion is to use helm.
1218 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1219 (defun org-ref-helm-insert-ref-link ()
1220 "Helm menu to insert ref links to labels in the document.
1221 If you are on link, replace with newly selected label.
1222 Use C-u to insert a different kind of ref link.
1225 (let* ((labels (org-ref-get-labels))
1226 (contexts (mapcar 'org-ref-get-label-context labels))
1227 (cb (current-buffer)))
1229 (helm :input (thing-at-point 'word)
1230 :sources `(((name . "Available labels to ref")
1231 (candidates . ,(loop for label in labels
1232 for context in contexts
1233 ;; we do some kludgy adding spaces
1234 ;; and bars to make it "easier" to
1236 collect (cons (concat
1241 (split-string context "\n")
1244 ;; default action to replace or insert ref link.
1245 (action . (lambda (label)
1246 (switch-to-buffer ,cb)
1249 ;; no prefix or on a link
1250 ((equal helm-current-prefix-arg nil)
1251 (let* ((object (org-element-context))
1252 (last-char (save-excursion
1253 (goto-char (org-element-property :end object))
1255 (if (looking-at " ")
1258 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1259 (org-element-property :type object))
1260 ;; we are on a link, so replace it.
1263 (org-element-property :begin object)
1264 (org-element-property :end object))
1266 (replace-regexp-in-string
1267 (org-element-property :path object)
1269 (org-element-property :raw-link object))
1271 ;; insert a new link
1276 ;; one prefix, alternate ref link
1277 ((equal helm-current-prefix-arg '(4))
1280 (helm :sources '((name . "Ref link types")
1281 (candidates . ("ref" "eqref" "pageref" "nameref"))
1282 (action . (lambda (x) x))))
1288 : org-ref-helm-insert-ref-link
1292 This refers to the page of a label in LaTeX.
1294 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1298 "on clicking goto the label. Navigate back with C-c &"
1299 (org-mark-ring-push)
1300 ;; next search from beginning of the buffer
1306 (goto-char (point-min))
1307 (re-search-forward (format "label:%s\\b" label) nil t))
1311 (goto-char (point-min))
1312 (re-search-forward (format "\\label{%s}" label) nil t))
1314 ;; #+label: name org-definition
1316 (goto-char (point-min))
1317 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1321 (goto-char (point-min))
1322 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1324 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1325 ;; you need [[#label]] links.
1328 ; (goto-char (point-min))
1329 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1331 ;; we did not find anything, so go back to where we came
1332 (org-mark-ring-goto)
1333 (error "%s not found" label))
1334 (message "go back with (org-mark-ring-goto) `C-c &`"))
1336 (lambda (keyword desc format)
1338 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1340 (format "\\pageref{%s}" keyword)))))
1343 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1344 (defun org-pageref-complete-link (&optional arg)
1345 "Completion function for ref links"
1347 (setq label (completing-read "label: " (org-ref-get-labels)))
1348 (format "ref:%s" label)))
1351 Alternatively, you may want to just call a function that inserts a link with completion:
1353 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1354 (defun org-pageref-insert-ref-link ()
1356 (insert (org-pageref-complete-link)))
1361 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.
1363 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1367 "on clicking goto the label. Navigate back with C-c &"
1368 (org-mark-ring-push)
1369 ;; next search from beginning of the buffer
1375 (goto-char (point-min))
1376 (re-search-forward (format "\\label{%s}" label) nil t))
1378 ;; we did not find anything, so go back to where we came
1379 (org-mark-ring-goto)
1380 (error "%s not found" label))
1381 (message "go back with (org-mark-ring-goto) `C-c &`"))
1383 (lambda (keyword desc format)
1385 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1387 (format "\\nameref{%s}" keyword)))))
1391 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1393 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1397 "on clicking goto the label. Navigate back with C-c &"
1398 (org-mark-ring-push)
1399 ;; next search from beginning of the buffer
1401 (goto-char (point-min))
1404 ;; search forward for the first match
1406 (re-search-forward (format "label:%s" label) nil t)
1408 (re-search-forward (format "\\label{%s}" label) nil t)
1409 ;; #+label: name org-definition
1410 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1411 (org-mark-ring-goto)
1412 (error "%s not found" label))
1413 (message "go back with (org-mark-ring-goto) `C-c &`"))
1415 (lambda (keyword desc format)
1417 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1419 (format "\\eqref{%s}" keyword)))))
1423 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.
1425 *** Implementing the click actions of cite
1427 **** Getting the key we clicked on
1428 The first thing we need is to get the bibtex key we clicked on.
1430 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1431 (defun org-ref-get-bibtex-key-under-cursor ()
1432 "returns key under the bibtex cursor. We search forward from
1433 point to get a comma, or the end of the link, and then backwards
1434 to get a comma, or the beginning of the link. that delimits the
1435 keyword we clicked on. We also strip the text properties."
1437 (let* ((object (org-element-context))
1438 (link-string (org-element-property :path object)))
1439 ;; you may click on the part before the citations. here we make
1440 ;; sure to move to the beginning so you get the first citation.
1442 (goto-char (org-element-property :begin object))
1443 (search-forward link-string (org-element-property :end object))
1444 (goto-char (match-beginning 0))
1445 ;; check if we clicked before the path and move as needed.
1446 (unless (< cp (point))
1449 (if (not (org-element-property :contents-begin object))
1450 ;; this means no description in the link
1452 ;; we need the link path start and end
1454 (goto-char (org-element-property :begin object))
1455 (search-forward link-string nil nil 1)
1456 (setq link-string-beginning (match-beginning 0))
1457 (setq link-string-end (match-end 0)))
1459 ;; The key is the text between commas, or the link boundaries
1461 (if (search-forward "," link-string-end t 1)
1462 (setq key-end (- (match-end 0) 1)) ; we found a match
1463 (setq key-end link-string-end))) ; no comma found so take the end
1464 ;; and backward to previous comma from point which defines the start character
1466 (if (search-backward "," link-string-beginning 1 1)
1467 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1468 (setq key-beginning link-string-beginning))) ; no match found
1469 ;; save the key we clicked on.
1470 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1471 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1473 ;; link with description. assume only one key
1477 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.
1479 **** Getting the bibliographies
1480 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1481 (defun org-ref-find-bibliography ()
1482 "find the bibliography in the buffer.
1483 This function sets and returns cite-bibliography-files, which is a list of files
1484 either from bibliography:f1.bib,f2.bib
1485 \bibliography{f1,f2}
1486 internal bibliographies
1488 falling back to what the user has set in org-ref-default-bibliography
1493 (goto-char (point-min))
1494 ;; look for a bibliography link
1495 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1496 (setq org-ref-bibliography-files
1497 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1498 (throw 'result org-ref-bibliography-files))
1501 ;; we did not find a bibliography link. now look for \bibliography
1502 (goto-char (point-min))
1503 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1504 ;; split, and add .bib to each file
1505 (setq org-ref-bibliography-files
1506 (mapcar (lambda (x) (concat x ".bib"))
1507 (mapcar 'org-ref-strip-string
1508 (split-string (match-string 1) ","))))
1509 (throw 'result org-ref-bibliography-files))
1511 ;; no bibliography found. maybe we need a biblatex addbibresource
1512 (goto-char (point-min))
1513 ;; look for a bibliography link
1514 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1515 (setq org-ref-bibliography-files
1516 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1517 (throw 'result org-ref-bibliography-files))
1519 ;; we did not find anything. use defaults
1520 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1522 ;; set reftex-default-bibliography so we can search
1523 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1524 org-ref-bibliography-files)
1527 **** Finding the bibliography file a key is in
1528 Now, we can see if an entry is in a file.
1530 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1531 (defun org-ref-key-in-file-p (key filename)
1532 "determine if the key is in the file"
1533 (interactive "skey: \nsFile: ")
1534 (save-current-buffer
1535 (let ((bibtex-files (list filename)))
1536 (bibtex-search-entry key t))))
1539 Finally, we want to know which file the key is in.
1541 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1542 (defun org-ref-get-bibtex-key-and-file (&optional key)
1543 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1545 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1548 (setq key (org-ref-get-bibtex-key-under-cursor)))
1549 (setq file (catch 'result
1550 (loop for file in org-ref-bibliography-files do
1551 (if (org-ref-key-in-file-p key (file-truename file))
1552 (throw 'result file)))))
1556 **** convenience functions to act on citation at point
1558 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1560 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.
1562 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1563 (defun org-ref-open-pdf-at-point ()
1564 "open the pdf for bibtex key under point if it exists"
1566 (let* ((results (org-ref-get-bibtex-key-and-file))
1568 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1569 (if (file-exists-p pdf-file)
1570 (org-open-file pdf-file)
1571 (message "no pdf found for %s" key))))
1574 (defun org-ref-open-url-at-point ()
1575 "open the url for bibtex key under point."
1577 (let* ((results (org-ref-get-bibtex-key-and-file))
1579 (bibfile (cdr results)))
1582 (insert-file-contents bibfile)
1583 (bibtex-search-entry key)
1584 ;; I like this better than bibtex-url which does not always find
1587 (let ((url (bibtex-autokey-get-field "url")))
1592 (let ((doi (bibtex-autokey-get-field "doi")))
1594 (if (string-match "^http" doi)
1596 (browse-url (format "http://dx.doi.org/%s" doi)))
1597 (throw 'done nil))))))))
1600 (defun org-ref-open-notes-at-point ()
1601 "open the notes for bibtex key under point."
1603 (let* ((results (org-ref-get-bibtex-key-and-file))
1605 (bibfile (cdr results)))
1608 (insert-file-contents bibfile)
1609 (bibtex-search-entry key)
1610 (org-ref-open-bibtex-notes)))))
1613 (defun org-ref-citation-at-point ()
1614 "give message of current citation at point"
1616 (let* ((cb (current-buffer))
1617 (results (org-ref-get-bibtex-key-and-file))
1619 (bibfile (cdr results)))
1620 (message "%s" (progn
1622 (insert-file-contents bibfile)
1623 (bibtex-search-entry key)
1624 (org-ref-bib-citation))))))
1627 (defun org-ref-open-citation-at-point ()
1628 "open bibtex file to key at point"
1630 (let* ((cb (current-buffer))
1631 (results (org-ref-get-bibtex-key-and-file))
1633 (bibfile (cdr results)))
1635 (bibtex-search-entry key)))
1638 **** the actual minibuffer menu
1639 Now, we create the menu. This is a rewrite of the cite action. This makes the function extendable by users.
1641 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1642 (defvar org-ref-cite-menu-funcs '()
1643 "Functions to run on cite click menu. Each entry is a list of (key menu-name function).
1644 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.")
1647 (defvar org-ref-user-cite-menu-funcs
1648 '(("C" "rossref" org-ref-crossref-at-point)
1649 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1650 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1651 "user-defined functions to run on bibtex key at point.")
1654 (defun org-ref-copy-entry-as-summary ()
1655 "Copy the bibtex entry for the citation at point as a summary."
1657 (save-window-excursion
1658 (org-ref-open-citation-at-point)
1659 (kill-new (org-ref-bib-citation))))
1662 (defun org-ref-copy-entry-at-point-to-file ()
1663 "Copy the bibtex entry for the citation at point to NEW-FILE.
1664 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."
1666 (let ((new-file (ido-completing-read
1668 (append org-ref-default-bibliography
1669 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1670 (key (org-ref-get-bibtex-key-under-cursor)))
1671 (save-window-excursion
1672 (org-ref-open-citation-at-point)
1673 (bibtex-copy-entry-as-kill))
1675 (let ((bibtex-files (list (file-truename new-file))))
1676 (if (assoc key (bibtex-global-key-alist))
1677 (message "That key already exists in %s" new-file)
1679 (save-window-excursion
1680 (find-file new-file)
1681 (goto-char (point-max))
1682 ;; make sure we are at the beginning of a line.
1683 (unless (looking-at "^") (insert "\n\n"))
1688 (defun org-ref-get-doi-at-point ()
1689 "Get doi for key at point."
1691 (let* ((results (org-ref-get-bibtex-key-and-file))
1693 (bibfile (cdr results))
1697 (insert-file-contents bibfile)
1698 (bibtex-search-entry key)
1699 (setq doi (bibtex-autokey-get-field "doi"))
1700 ;; in case doi is a url, remove the url part.
1701 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1704 ;; functions that operate on key at point for click menu
1705 (defun org-ref-wos-at-point ()
1706 "open the doi in wos for bibtex key under point."
1708 (doi-utils-wos (org-ref-get-doi-at-point)))
1711 (defun org-ref-wos-citing-at-point ()
1712 "open the doi in wos citing articles for bibtex key under point."
1714 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1717 (defun org-ref-wos-related-at-point ()
1718 "open the doi in wos related articles for bibtex key under point."
1720 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1723 (defun org-ref-google-scholar-at-point ()
1724 "open the doi in google scholar for bibtex key under point."
1726 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1729 (defun org-ref-pubmed-at-point ()
1730 "open the doi in pubmed for bibtex key under point."
1732 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1735 (defun org-ref-crossref-at-point ()
1736 "open the doi in crossref for bibtex key under point."
1738 (doi-utils-crossref (org-ref-get-doi-at-point)))
1741 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1742 "action when a cite link is clicked on.
1743 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."
1745 (let* ((results (org-ref-get-bibtex-key-and-file))
1747 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1748 (bibfile (cdr results))
1749 (url (save-excursion
1751 (insert-file-contents bibfile)
1752 (bibtex-search-entry key)
1753 (bibtex-autokey-get-field "url"))))
1754 (doi (save-excursion
1756 (insert-file-contents bibfile)
1757 (bibtex-search-entry key)
1758 ;; I like this better than bibtex-url which does not always find
1760 (bibtex-autokey-get-field "doi")))))
1762 (when (string= "" doi) (setq doi nil))
1763 (when (string= "" url) (setq url nil))
1764 (setq org-ref-cite-menu-funcs '())
1770 'org-ref-cite-menu-funcs
1771 '("o" "pen" org-ref-open-citation-at-point)))
1774 (when (file-exists-p pdf-file)
1776 'org-ref-cite-menu-funcs
1777 `("p" "df" ,org-ref-open-pdf-function) t))
1781 'org-ref-cite-menu-funcs
1782 '("n" "otes" org-ref-open-notes-at-point) t)
1787 'org-ref-cite-menu-funcs
1788 '("u" "rl" org-ref-open-url-at-point) t))
1793 'org-ref-cite-menu-funcs
1794 '("w" "os" org-ref-wos-at-point) t)
1797 'org-ref-cite-menu-funcs
1798 '("c" "iting" org-ref-wos-citing-at-point) t)
1801 'org-ref-cite-menu-funcs
1802 '("r" "elated" org-ref-wos-related-at-point) t)
1805 'org-ref-cite-menu-funcs
1806 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1809 'org-ref-cite-menu-funcs
1810 '("P" "ubmed" org-ref-pubmed-at-point) t))
1812 ;; add user functions
1813 (dolist (tup org-ref-user-cite-menu-funcs)
1815 'org-ref-cite-menu-funcs
1820 'org-ref-cite-menu-funcs
1821 '("q" "uit" (lambda ())) t)
1823 ;; now we make a menu
1824 ;; construct menu string as a message
1827 (let* ((results (org-ref-get-bibtex-key-and-file))
1829 (bibfile (cdr results)))
1832 (insert-file-contents bibfile)
1833 (bibtex-search-entry key)
1834 (org-ref-bib-citation))))
1838 (concat "[" (elt tup 0) "]"
1840 org-ref-cite-menu-funcs "")))
1842 (let* ((input (read-char-exclusive))
1844 (char-to-string input) org-ref-cite-menu-funcs)))
1845 ;; now run the function (2nd element in choice)
1854 : org-ref-cite-onclick-minibuffer-menu
1856 *** A function to format a cite link
1858 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.
1860 #+BEGIN_SRC emacs-lisp :tangle no
1861 ;(defun org-ref-cite-link-format (keyword desc format)
1863 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1864 ; ((eq format 'latex)
1865 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1866 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1870 *** The actual cite link
1871 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1873 #+BEGIN_SRC emacs-lisp :tangle no
1876 ; 'org-ref-cite-onclick-minibuffer-menu
1877 ; 'org-ref-cite-link-format)
1880 *** Automatic definition of the cite links
1881 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.
1883 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1884 (defmacro org-ref-make-completion-function (type)
1885 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1891 (let ((bibtex-files (org-ref-find-bibliography)))
1892 (bibtex-global-key-alist))))))
1895 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.
1897 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1898 (defmacro org-ref-make-format-function (type)
1899 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1904 (format "[[#%s][%s]]" key key))
1905 (org-ref-split-and-strip-string keyword) ","))
1912 (org-ref-split-and-strip-string keyword) ",") "]"))
1917 (format "<a href=\"#%s\">%s</a>" key key))
1918 (org-ref-split-and-strip-string keyword) ","))
1921 (if (string= (substring type -1) "s")
1922 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1923 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1924 (org-ref-split-and-strip-string keyword) ""))
1926 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1927 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1933 We create the links by mapping the function onto the list of defined link types.
1935 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1936 (defun org-ref-format-citation-description (desc)
1937 "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 ::."
1940 ((string-match "::" desc)
1941 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1942 (t (format "[%s]" desc))))
1944 (defun org-ref-define-citation-link (type &optional key)
1945 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1946 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1947 and the completion function."
1948 (interactive "sCitation Type: \ncKey: ")
1950 ;; create the formatting function
1951 (eval `(org-ref-make-format-function ,type))
1956 org-ref-cite-onclick-function
1957 (quote ,(intern (format "org-ref-format-%s" type)))))
1959 ;; create the completion function
1960 (eval `(org-ref-make-completion-function ,type))
1962 ;; store new type so it works with adding citations, which checks
1963 ;; for existence in this list
1964 (add-to-list 'org-ref-cite-types type)
1966 ;; and finally if a key is specified, we modify the reftex menu
1968 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1969 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1970 `((,key . ,(concat type ":%l")))))))
1972 ;; create all the link types and their completion functions
1973 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1976 *** org-ref-insert-cite-link
1977 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.
1979 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1980 (defun org-ref-insert-cite-link (alternative-cite)
1981 "Insert a default citation link using reftex. If you are on a link, it
1982 appends to the end of the link, otherwise, a new link is
1983 inserted. Use a prefix arg to get a menu of citation types."
1985 (org-ref-find-bibliography)
1986 (let* ((object (org-element-context))
1987 (link-string-beginning (org-element-property :begin object))
1988 (link-string-end (org-element-property :end object))
1989 (path (org-element-property :path object)))
1991 (if (not alternative-cite)
1994 ;; case where we are in a link
1995 ((and (equal (org-element-type object) 'link)
1996 (-contains? org-ref-cite-types (org-element-property :type object)))
1997 (goto-char link-string-end)
1998 ;; sometimes there are spaces at the end of the link
1999 ;; this code moves point pack until no spaces are there
2000 (while (looking-back " ") (backward-char))
2001 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
2003 ;; We are next to a link, and we want to append
2006 (and (equal (org-element-type (org-element-context)) 'link)
2007 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
2008 (while (looking-back " ") (backward-char))
2009 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
2011 ;; insert fresh link
2014 (concat org-ref-default-citation-link
2016 (mapconcat 'identity (reftex-citation t) ",")))))
2018 ;; you pressed a C-u so we run this code
2022 cite:zhou-2004-first-lda-u,paier-2006-errat,boes-2015-estim-bulk
2026 : org-ref-insert-cite-link
2028 *** Completion in cite links
2029 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.
2031 #+BEGIN_SRC emacs-lisp :tangle no
2032 (defun org-cite-complete-link (&optional arg)
2033 "Completion function for cite links"
2035 org-ref-default-citation-link
2038 (let ((bibtex-files (org-ref-find-bibliography)))
2039 (bibtex-global-key-alist)))))
2042 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
2044 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2045 (defun org-ref-insert-cite-with-completion (type)
2046 "Insert a cite link with completion"
2047 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
2048 (insert (funcall (intern (format "org-%s-complete-link" type)))))
2051 ** Storing links to a bibtex entry
2052 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.
2054 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2055 (defun org-ref-store-bibtex-entry-link ()
2056 "Save a citation link to the current bibtex entry. Saves in the default link type."
2058 (let ((link (concat org-ref-default-citation-link
2061 (bibtex-beginning-of-entry)
2062 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
2063 (message "saved %s" link)
2064 (push (list link) org-stored-links)
2065 (car org-stored-links)))
2069 org-ref minimally supports index entries. To make an index in a file, you should put in the LaTeX header these lines
2072 #+LATEX_HEADER: \usepackage{makeidx}
2073 #+LATEX_HEADER: \makeindex
2076 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.
2079 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.
2084 [[index:hello!Sam@\textsl{Sam}]]
2085 [[index:Lin@\textbf{Lin}]]
2086 [[index:Joe|textit]]
2087 [[index:Lin@\textbf{Lin}]]
2088 [[index:Peter|see {hello}]]
2089 [[index:Jen|seealso{Jenny}]]
2091 index:encodings!input!cp850
2093 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2099 (lambda (path desc format)
2102 (format "\\index{%s}" path)))))
2104 ;; this will generate a temporary index of entries in the file.
2108 (let ((*index-links* '())
2109 (*initial-letters* '()))
2112 (org-element-map (org-element-parse-buffer) 'link
2114 (let ((type (nth 0 link))
2115 (plist (nth 1 link)))
2117 (when (equal (plist-get plist ':type) "index")
2120 (cons (plist-get plist :path)
2122 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2124 (plist-get plist :begin) ;; position of link
2125 ;; grab a description
2127 (goto-char (plist-get plist :begin))
2128 (if (thing-at-point 'sentence)
2130 (replace-regexp-in-string
2131 "\n" "" (thing-at-point 'sentence))
2132 ;; or call it a link
2136 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2138 ;; now first letters
2139 (dolist (link *index-links*)
2140 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2142 ;; now create the index
2143 (switch-to-buffer (get-buffer-create "*index*"))
2146 (insert "#+TITLE: Index\n\n")
2147 (dolist (letter *initial-letters*)
2148 (insert (format "* %s\n" (upcase letter)))
2149 ;; now process the links
2152 (string= letter (substring (car (car *index-links*)) 0 1)))
2153 (let ((link (pop *index-links*)))
2154 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2155 (switch-to-buffer "*index*")))
2157 (lambda (path desc format)
2160 (format "\\printindex")))))
2164 | 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*)) |
2165 | lambda | (path desc format) | (cond ((eq format (quote latex)) (format \printindex))) |
2168 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.
2170 #+LATEX_HEADER: \usepackage{glossaries}
2171 #+LATEX_HEADER: \makeglossaries
2173 And at the end of the document put \makeglossaries.
2175 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2178 nil ;; no follow action
2179 (lambda (path desc format)
2182 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2188 nil ;; no follow action
2189 (lambda (path desc format)
2192 (format "\\gls{%s}" path)))))
2197 nil ;; no follow action
2198 (lambda (path desc format)
2201 (format "\\glspl{%s}" path)))))
2206 nil ;; no follow action
2207 (lambda (path desc format)
2210 (format "\\Gls{%s}" path)))))
2215 nil ;; no follow action
2216 (lambda (path desc format)
2219 (format "\\Glspl{%s}" path)))))
2223 ** create simple text citation from bibtex entry
2225 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2226 (defun org-ref-bib-citation ()
2227 "From a bibtex entry, create and return a simple citation string.
2228 This assumes you are in an article."
2230 (bibtex-beginning-of-entry)
2231 (let* ((cb (current-buffer))
2232 (bibtex-expand-strings t)
2233 (entry (loop for (key . value) in (bibtex-parse-entry t)
2234 collect (cons (downcase key) value)))
2235 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2236 (year (reftex-get-bib-field "year" entry))
2237 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2238 (key (reftex-get-bib-field "=key=" entry))
2239 (journal (reftex-get-bib-field "journal" entry))
2240 (volume (reftex-get-bib-field "volume" entry))
2241 (pages (reftex-get-bib-field "pages" entry))
2242 (doi (reftex-get-bib-field "doi" entry))
2243 (url (reftex-get-bib-field "url" entry))
2245 ;;authors, "title", Journal, vol(iss):pages (year).
2246 (format "%s, \"%s\", %s, %s:%s (%s)"
2247 author title journal volume pages year)))
2251 : org-ref-bib-citation
2254 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2255 (defun org-ref-bib-html-citation ()
2256 "from a bibtex entry, create and return a simple citation with html links."
2258 (bibtex-beginning-of-entry)
2259 (let* ((cb (current-buffer))
2260 (bibtex-expand-strings t)
2261 (entry (loop for (key . value) in (bibtex-parse-entry t)
2262 collect (cons (downcase key) value)))
2263 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2264 (year (reftex-get-bib-field "year" entry))
2265 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2266 (key (reftex-get-bib-field "=key=" entry))
2267 (journal (reftex-get-bib-field "journal" entry))
2268 (volume (reftex-get-bib-field "volume" entry))
2269 (pages (reftex-get-bib-field "pages" entry))
2270 (doi (reftex-get-bib-field "doi" entry))
2271 (url (reftex-get-bib-field "url" entry))
2273 ;;authors, "title", Journal, vol(iss):pages (year).
2274 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2275 author title journal volume pages year)
2276 (when url (format " <a href=\"%s\">link</a>" url))
2277 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2281 ** open pdf from bibtex
2282 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2283 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2284 (defun org-ref-open-bibtex-pdf ()
2285 "open pdf for a bibtex entry, if it exists. assumes point is in
2286 the entry of interest in the bibfile. but does not check that."
2289 (bibtex-beginning-of-entry)
2290 (let* ((bibtex-expand-strings t)
2291 (entry (bibtex-parse-entry t))
2292 (key (reftex-get-bib-field "=key=" entry))
2293 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2295 (if (file-exists-p pdf)
2296 (org-open-link-from-string (format "[[file:%s]]" pdf))
2300 ** open notes from bibtex
2301 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2303 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2304 (defun org-ref-open-bibtex-notes ()
2305 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
2307 I never did figure out how to use reftex to make this happen
2308 non-interactively. the reftex-format-citation function did not
2309 work perfectly; there were carriage returns in the strings, and
2310 it did not put the key where it needed to be. so, below I replace
2311 the carriage returns and extra spaces with a single space and
2312 construct the heading by hand."
2315 (bibtex-beginning-of-entry)
2316 (let* ((cb (current-buffer))
2317 (bibtex-expand-strings t)
2318 (entry (loop for (key . value) in (bibtex-parse-entry t)
2319 collect (cons (downcase key) value)))
2320 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2321 (year (reftex-get-bib-field "year" entry))
2322 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2323 (key (reftex-get-bib-field "=key=" entry))
2324 (journal (reftex-get-bib-field "journal" entry))
2325 (volume (reftex-get-bib-field "volume" entry))
2326 (pages (reftex-get-bib-field "pages" entry))
2327 (doi (reftex-get-bib-field "doi" entry))
2328 (url (reftex-get-bib-field "url" entry))
2331 ;; save key to clipboard to make saving pdf later easier by pasting.
2334 (kill-ring-save (point-min) (point-max)))
2336 ;; now look for entry in the notes file
2337 (if org-ref-bibliography-notes
2338 (find-file-other-window org-ref-bibliography-notes)
2339 (error "org-ref-bib-bibliography-notes is not set to anything"))
2341 (goto-char (point-min))
2342 ;; put new entry in notes if we don't find it.
2343 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2344 (funcall org-ref-open-notes-function)
2345 ;; no entry found, so add one
2346 (insert (format "\n** TODO %s - %s" year title))
2358 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2359 key author journal year volume pages doi url key org-ref-pdf-directory key))
2363 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2364 (defun org-ref-open-notes-from-reftex ()
2365 "Call reftex, and open notes for selected entry."
2367 (let ((bibtex-key )))
2369 ;; now look for entry in the notes file
2370 (if org-ref-bibliography-notes
2371 (find-file-other-window org-ref-bibliography-notes)
2372 (error "org-ref-bib-bibliography-notes is not set to anything"))
2374 (goto-char (point-min))
2376 (re-search-forward (format
2378 (first (reftex-citation t)) nil 'end))
2379 (funcall org-ref-open-notes-function))
2382 ** open url in browser from bibtex
2384 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2386 + 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.
2388 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2389 (defun org-ref-open-in-browser ()
2390 "Open the bibtex entry at point in a browser using the url field or doi field"
2393 (bibtex-beginning-of-entry)
2395 (let ((url (bibtex-autokey-get-field "url")))
2400 (let ((doi (bibtex-autokey-get-field "doi")))
2402 (if (string-match "^http" doi)
2404 (browse-url (format "http://dx.doi.org/%s" doi)))
2406 (message "No url or doi found"))))
2410 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.
2412 *** function to upload bibtex to citeulike
2414 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2415 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2416 "with point in a bibtex entry get bibtex string and submit to citeulike.
2418 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2420 (message "uploading to citeulike")
2422 (bibtex-narrow-to-entry)
2423 (let ((startpos (point-min))
2424 (endpos (point-max))
2425 (bibtex-string (buffer-string))
2426 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2427 (with-temp-buffer (insert bibtex-string)
2428 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2431 *** The upload script
2432 Here is the python script for uploading.
2434 *************** TODO document how to get the cookies
2438 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
2440 import pickle, requests, sys
2443 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
2444 cookies = pickle.load(f)
2446 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
2448 bibtex = sys.stdin.read()
2450 data = {'pasted':bibtex,
2452 'tag_parsing':'simple',
2453 'strip_brackets':'no',
2454 'update_id':'bib-key',
2455 'btn_bibtex':'Import BibTeX file ...'}
2457 headers = {'content-type': 'multipart/form-data',
2458 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
2460 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
2464 ** Build a pdf from a bibtex file
2465 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.
2467 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2468 (defun org-ref-build-full-bibliography ()
2469 "build pdf of all bibtex entries, and open it."
2471 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2472 (bib-base (file-name-sans-extension bibfile))
2473 (texfile (concat bib-base ".tex"))
2474 (pdffile (concat bib-base ".pdf")))
2477 (insert (format "\\documentclass[12pt]{article}
2478 \\usepackage[version=3]{mhchem}
2480 \\usepackage[numbers]{natbib}
2481 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2485 \\bibliographystyle{unsrtnat}
2487 \\end{document}" bib-base))
2489 (shell-command (concat "pdflatex " bib-base))
2490 (shell-command (concat "bibtex " bib-base))
2491 (shell-command (concat "pdflatex " bib-base))
2492 (shell-command (concat "pdflatex " bib-base))
2493 (kill-buffer texfile)
2494 (org-open-file pdffile)
2498 ** Extract bibtex entries cited in an org-file
2499 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.
2501 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2502 (defun org-ref-extract-bibtex-entries ()
2503 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2505 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
2507 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2508 (tempname (make-temp-file "extract-bib"))
2509 (contents (buffer-string))
2510 (cb (current-buffer))
2511 basename texfile bibfile results)
2513 ;; open tempfile and insert org-buffer contents
2514 (find-file tempname)
2516 (setq basename (file-name-sans-extension
2517 (file-name-nondirectory buffer-file-name))
2518 texfile (concat tempname ".tex")
2519 bibfile (concat tempname ".bib"))
2521 ;; see if we have a bibliography, and insert the default one if not.
2523 (goto-char (point-min))
2524 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2525 (insert (format "\nbibliography:%s"
2526 (mapconcat 'identity reftex-default-bibliography ",")))))
2529 ;; get a latex file and extract the references
2530 (org-latex-export-to-latex)
2533 (reftex-create-bibtex-file bibfile)
2535 ;; save results of the references
2536 (setq results (buffer-string))
2538 ;; kill buffers. these are named by basename, not full path
2539 (kill-buffer (concat basename ".bib"))
2540 (kill-buffer (concat basename ".tex"))
2541 (kill-buffer basename)
2543 (delete-file bibfile)
2544 (delete-file texfile)
2545 (delete-file tempname)
2547 ;; Now back to the original org buffer and insert the results
2548 (switch-to-buffer cb)
2549 (when (not (string= "" results))
2551 (goto-char (point-max))
2553 (org-insert-heading)
2554 (insert (format " Bibtex entries
2556 ,#+BEGIN_SRC text :tangle %s
2558 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2561 ** Find bad cite links
2563 :ID: 8515E800-EDA0-4B2A-85FD-55B6FF849203
2565 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.
2567 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2570 (defun index (substring list)
2571 "return the index of string in a list of strings"
2574 (dolist (arg list i)
2575 (if (string-match (concat "^" substring "$") arg)
2580 ;; return counter if found, otherwise return nil
2584 (defun org-ref-find-bad-citations ()
2585 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2587 Makes a new buffer with clickable links."
2589 ;; generate the list of bibtex-keys and cited keys
2590 (let* ((bibtex-files (org-ref-find-bibliography))
2591 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2592 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2593 (bad-citations '()))
2595 (org-element-map (org-element-parse-buffer) 'link
2597 (let ((plist (nth 1 link)))
2598 (when (equal (plist-get plist ':type) "cite")
2599 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2600 (when (not (index key bibtex-keys))
2601 (setq bad-citations (append bad-citations
2602 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2603 key (buffer-name)(plist-get plist ':begin)))))
2608 (switch-to-buffer-other-window "*Missing citations*")
2611 (insert "* List of bad cite links\n")
2612 (insert (mapconcat 'identity bad-citations ""))
2613 ;(setq buffer-read-only t)
2614 (use-local-map (copy-keymap org-mode-map))
2615 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2617 (when (get-buffer "*Missing citations*")
2618 (kill-buffer "*Missing citations*"))
2619 (message "No bad cite links found"))))
2622 ** helm interface to org-ref
2623 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.
2625 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.
2627 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2628 (defun org-ref-bad-cite-candidates ()
2629 "Returns a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2630 (let* ((cp (point)) ; save to return to later
2631 (bibtex-files (org-ref-find-bibliography))
2632 (bibtex-file-path (mapconcat
2634 (file-name-directory (file-truename x)))
2636 (bibtex-keys (mapcar (lambda (x) (car x))
2637 (bibtex-global-key-alist)))
2638 (bad-citations '()))
2640 (org-element-map (org-element-parse-buffer) 'link
2642 (let ((plist (nth 1 link)))
2643 (when (-contains? org-ref-cite-types (plist-get plist ':type))
2644 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2645 (when (not (index key bibtex-keys))
2646 (goto-char (plist-get plist ':begin))
2647 (re-search-forward key)
2648 (push (cons key (point-marker)) bad-citations)))
2653 ;; It seems I forgot I already defined this earlier!
2654 ;; (defun org-ref-get-labels ()
2655 ;; "Returns a list of known labels in the org document. These include label links, latex labels, label tags, and table names. The list contains all labels, not just unique ones.
2657 ;; (let ((cp (point))
2659 ;; (goto-char (point-min))
2660 ;; (while (re-search-forward "[^#+]label:\\(.*\\)\\s-" nil t)
2661 ;; (push (match-string 1) labels))
2663 ;; (goto-char (point-min))
2664 ;; (while (re-search-forward "\\label{\\(.*\\)}\\s-?" nil t)
2665 ;; (push (match-string 1) labels))
2667 ;; (goto-char (point-min))
2668 ;; (while (re-search-forward "^#\\+label:\\s-*\\(.*\\)" nil t)
2669 ;; (push (match-string 1) labels))
2671 ;; (goto-char (point-min))
2672 ;; (while (re-search-forward "^#\\+tblname:\\s-*\\(.*\\)" nil t)
2673 ;; (push (match-string 1) labels))
2674 ;; ;; check for CUSTOM_ID
2677 ;; (when (org-entry-get (point) "CUSTOM_ID")
2678 ;; (push (org-entry-get (point) "CUSTOM_ID") labels))))
2679 ;; ;; return to original place
2684 (defun org-ref-bad-ref-candidates ()
2685 "Returns a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2686 ;; first get a list of legitimate labels
2688 (labels (org-ref-get-labels))
2690 ;; now loop over ref links
2691 (goto-char (point-min))
2692 (org-element-map (org-element-parse-buffer) 'link
2694 (let ((plist (nth 1 link)))
2695 (when (or (equal (plist-get plist ':type) "ref")
2696 (equal (plist-get plist ':type) "eqref")
2697 (equal (plist-get plist ':type) "pageref")
2698 (equal (plist-get plist ':type) "nameref"))
2699 (unless (-contains? labels (plist-get plist :path))
2700 (goto-char (plist-get plist :begin))
2703 (cons (plist-get plist :path)
2704 (point-marker))))))))
2709 (defun org-ref-bad-label-candidates ()
2710 "Return a list of labels where label is multiply defined."
2711 (let ((labels (org-ref-get-labels))
2712 (multiple-labels '()))
2713 (when (not (= (length labels)
2714 (length (-uniq labels))))
2715 (dolist (label labels)
2716 (when (> (-count (lambda (a)
2719 ;; this is a multiply defined label.
2721 (goto-char (point-min))
2722 (while (re-search-forward
2723 (format "[^#+]label:%s\\s-" label) nil t)
2724 (push (cons label (point-marker)) multiple-labels))
2726 (goto-char (point-min))
2727 (while (re-search-forward
2728 (format "\\label{%s}\\s-?" label) nil t)
2729 (push (cons label (point-marker)) multiple-labels))
2731 (goto-char (point-min))
2732 (while (re-search-forward
2733 (format "^#\\+label:\\s-*%s" label) nil t)
2734 (push (cons label (point-marker)) multiple-labels))
2736 (goto-char (point-min))
2737 (while (re-search-forward
2738 (format "^#\\+tblname:\\s-*%s" label) nil t)
2739 (push (cons label (point-marker)) multiple-labels))
2745 : org-ref-bad-label-candidates
2747 Now, we have a functions for candidates, we can make helm sources for each one, and then run a helm command to view them.
2749 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2751 "Opens a helm interface to actions for org-ref.
2752 Shows bad citations, ref links and labels"
2754 (let ((cb (current-buffer))
2755 (bad-citations (org-ref-bad-cite-candidates))
2756 (bad-refs (org-ref-bad-ref-candidates))
2757 (bad-labels (org-ref-bad-label-candidates)))
2759 (helm :sources `(((name . "Bad citations")
2760 (candidates . ,bad-citations)
2761 (action . (lambda (marker)
2762 (switch-to-buffer (marker-buffer marker))
2763 (goto-char marker))))
2765 ((name . "Bad Labels")
2766 (candidates . ,bad-labels)
2767 (action . (lambda (marker)
2768 (switch-to-buffer (marker-buffer marker))
2769 (goto-char marker))))
2771 ((name . "Bad ref links")
2772 (candidates . ,bad-refs)
2773 (action . (lambda (marker)
2774 (switch-to-buffer (marker-buffer marker))
2775 (goto-char marker))))
2777 ((name . "Utilities")
2778 (candidates . (("Check buffer again" . org-ref)
2779 ("Insert citation" . helm-bibtex)
2780 ("Insert label link" . org-ref-helm-insert-label-link)
2781 ("Insert ref link" . org-ref-helm-insert-ref-link)
2782 ("List of figures" . org-ref-list-of-figures)
2783 ("List of tables" . org-ref-list-of-tables)
2784 ("Table of contents" . nil)
2786 (action . (lambda (x)
2787 (switch-to-buffer ,cb)
2790 ((name . "Export functions")
2791 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2792 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2793 ("Export to pdf and open" . (lambda ()
2794 (org-open-file (org-latex-export-to-pdf))))
2795 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2796 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2799 (action . (lambda (x)
2800 (switch-to-buffer ,cb)
2806 ** Finding non-ascii characters
2807 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2809 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2810 (defun org-ref-find-non-ascii-characters ()
2811 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2813 (occur "[^[:ascii:]]"))
2816 ** Resort a bibtex entry
2817 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.
2819 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2820 (defun org-ref-sort-bibtex-entry ()
2821 "sort fields of entry in standard order and downcase them"
2823 (bibtex-beginning-of-entry)
2824 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2825 (entry (bibtex-parse-entry))
2828 (type (cdr (assoc "=type=" entry)))
2829 (key (cdr (assoc "=key=" entry))))
2831 ;; these are the fields we want to order that are in this entry
2832 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2833 ;; we do not want to reenter these fields
2834 (setq entry-fields (remove "=key=" entry-fields))
2835 (setq entry-fields (remove "=type=" entry-fields))
2837 ;;these are the other fields in the entry
2838 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2841 ;; right now we only resort articles
2842 ((string= (downcase type) "article")
2845 (concat "@article{" key ",\n"
2848 (when (member field entry-fields)
2849 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2852 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2854 (bibtex-find-entry key)
2856 (bibtex-clean-entry)
2860 ** Clean a bibtex entry
2861 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.
2862 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.
2863 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2864 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2865 "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"
2867 (bibtex-beginning-of-entry)
2869 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2870 (unless (string-match ",$" (thing-at-point 'line))
2874 ;; check for empty pages, and put eid or article id in its place
2875 (let ((entry (bibtex-parse-entry))
2876 (pages (bibtex-autokey-get-field "pages"))
2877 (year (bibtex-autokey-get-field "year"))
2878 (doi (bibtex-autokey-get-field "doi"))
2879 ;; The Journal of Chemical Physics uses eid
2880 (eid (bibtex-autokey-get-field "eid")))
2882 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2883 ;; but we only want the doi.
2884 (when (string-match "^http://dx.doi.org/" doi)
2885 (bibtex-beginning-of-entry)
2886 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2888 (bibtex-make-field "doi")
2890 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2892 ;; asap articles often set year to 0, which messes up key
2893 ;; generation. fix that.
2894 (when (string= "0" year)
2895 (bibtex-beginning-of-entry)
2896 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2898 (bibtex-make-field "year")
2900 (insert (read-string "Enter year: ")))
2902 ;; fix pages if they are empty if there is an eid to put there.
2903 (when (string= "-" pages)
2905 (bibtex-beginning-of-entry)
2906 ;; this seems like a clunky way to set the pages field.But I
2907 ;; cannot find a better way.
2908 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2910 (bibtex-make-field "pages")
2914 ;; replace naked & with \&
2916 (bibtex-narrow-to-entry)
2917 (bibtex-beginning-of-entry)
2918 (message "checking &")
2919 (replace-regexp " & " " \\\\& ")
2922 ;; generate a key, and if it duplicates an existing key, edit it.
2924 (let ((key (bibtex-generate-autokey)))
2926 ;; first we delete the existing key
2927 (bibtex-beginning-of-entry)
2928 (re-search-forward bibtex-entry-maybe-empty-head)
2929 (if (match-beginning bibtex-key-in-head)
2930 (delete-region (match-beginning bibtex-key-in-head)
2931 (match-end bibtex-key-in-head)))
2932 ;; check if the key is in the buffer
2933 (when (save-excursion
2934 (bibtex-search-entry key))
2936 (bibtex-search-entry key)
2937 (bibtex-copy-entry-as-kill)
2938 (switch-to-buffer-other-window "*duplicate entry*")
2940 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2943 (kill-new key))) ;; save key for pasting
2945 ;; run hooks. each of these operates on the entry with no arguments.
2946 ;; this did not work like i thought, it gives a symbolp error.
2947 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2952 org-ref-clean-bibtex-entry-hook)
2954 ;; sort fields within entry
2955 (org-ref-sort-bibtex-entry)
2956 ;; check for non-ascii characters
2957 (occur "[^[:ascii:]]")
2962 : org-ref-clean-bibtex-entry
2964 ** Sort the entries in a citation link by year
2965 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2967 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2968 (defun org-ref-get-citation-year (key)
2969 "get the year of an entry with key. Returns year as a string."
2971 (let* ((results (org-ref-get-bibtex-key-and-file key))
2972 (bibfile (cdr results)))
2974 (insert-file-contents bibfile)
2975 (bibtex-search-entry key nil 0)
2976 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2979 (defun org-ref-sort-citation-link ()
2980 "replace link at point with sorted link by year"
2982 (let* ((object (org-element-context))
2983 (type (org-element-property :type object))
2984 (begin (org-element-property :begin object))
2985 (end (org-element-property :end object))
2986 (link-string (org-element-property :path object))
2988 (setq keys (org-ref-split-and-strip-string link-string))
2989 (setq years (mapcar 'org-ref-get-citation-year keys))
2990 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2991 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2992 ;; now get the keys separated by commas
2993 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2994 ;; and replace the link with the sorted keys
2995 (cl--set-buffer-substring begin end (concat type ":" keys))))
2998 ** Sort entries in citation links with shift-arrow keys
2999 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
3000 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3001 (defun org-ref-swap-keys (i j keys)
3002 "swap the keys in a list with index i and j"
3003 (let ((tempi (nth i keys)))
3004 (setf (nth i keys) (nth j keys))
3005 (setf (nth j keys) tempi))
3008 (defun org-ref-swap-citation-link (direction)
3009 "move citation at point in direction +1 is to the right, -1 to the left"
3011 (let* ((object (org-element-context))
3012 (type (org-element-property :type object))
3013 (begin (org-element-property :begin object))
3014 (end (org-element-property :end object))
3015 (link-string (org-element-property :path object))
3017 ;; We only want this to work on citation links
3018 (when (-contains? org-ref-cite-types type)
3019 (setq key (org-ref-get-bibtex-key-under-cursor))
3020 (setq keys (org-ref-split-and-strip-string link-string))
3021 (setq i (index key keys)) ;; defined in org-ref
3022 (if (> direction 0) ;; shift right
3023 (org-ref-swap-keys i (+ i 1) keys)
3024 (org-ref-swap-keys i (- i 1) keys))
3025 (setq keys (mapconcat 'identity keys ","))
3026 ;; and replace the link with the sorted keys
3027 (cl--set-buffer-substring begin end (concat type ":" keys " "))
3028 ;; now go forward to key so we can move with the key
3029 (re-search-forward key)
3030 (goto-char (match-beginning 0)))))
3032 ;; add hooks to make it work
3033 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
3034 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
3037 ** Lightweight messages about links
3038 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.
3040 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3041 (defun org-ref-get-label-context (label)
3042 "Return a string of context around a label."
3045 (goto-char (point-min))
3046 (when (re-search-forward
3047 (format "label:%s\\b" label) nil t)
3048 (throw 'result (buffer-substring
3057 (goto-char (point-min))
3058 (when (re-search-forward
3059 (format "\\label{%s}" label) nil t)
3060 (throw 'result (buffer-substring
3069 (goto-char (point-min))
3070 (when (re-search-forward
3071 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
3072 (throw 'result (buffer-substring
3081 (goto-char (point-min))
3082 (when (re-search-forward
3083 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
3084 (throw 'result (buffer-substring
3093 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
3096 (defun org-ref-link-message ()
3097 "Print a minibuffer message about the link that point is on."
3099 (when (eq major-mode 'org-mode)
3100 (let* ((object (org-element-context))
3101 (type (org-element-property :type object)))
3105 ((-contains? org-ref-cite-types type)
3106 (message (org-ref-get-citation-string-at-point)))
3108 ;; message some context about the label we are referring to
3109 ((string= type "ref")
3110 (message (org-ref-get-label-context
3111 (org-element-property :path object))))
3113 ((string= type "eqref")
3114 (message (org-ref-get-label-context
3115 (org-element-property :path object))))
3117 ;; message the count
3118 ((string= type "label")
3119 (let ((count (org-ref-count-labels
3120 (org-element-property :path object))))
3121 ;; get plurality on occurrence correct
3122 (when (> count 1) (beep))
3124 (number-to-string count)
3126 (when (or (= count 0)
3130 ((string= type "custom-id")
3132 (org-open-link-from-string
3133 (format "[[#%s]]" (org-element-property :path object)))
3134 (message "%s" (org-get-heading))))
3136 ;; check if the bibliography files exist.
3137 ((string= type "bibliography")
3139 ;; object is the link you clicked on
3140 (object (org-element-context))
3141 (link-string (org-element-property :path object))
3142 (link-string-beginning)
3145 (goto-char (org-element-property :begin object))
3146 (search-forward link-string nil nil 1)
3147 (setq link-string-beginning (match-beginning 0))
3148 (setq link-string-end (match-end 0)))
3150 ;; make sure we are in link and not before the :
3151 (when (> link-string-beginning (point))
3152 (goto-char link-string-beginning))
3154 ;; now if we have comma separated bibliographies
3155 ;; we find the one clicked on. we want to
3156 ;; search forward to next comma from point
3158 (if (search-forward "," link-string-end 1 1)
3159 (setq key-end (- (match-end 0) 1)) ; we found a match
3160 (setq key-end (point)))) ; no comma found so take the point
3162 ;; and backward to previous comma from point
3164 (if (search-backward "," link-string-beginning 1 1)
3165 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
3166 (setq key-beginning (point)))) ; no match found
3167 ;; save the key we clicked on.
3169 (org-ref-strip-string
3170 (buffer-substring key-beginning key-end)))
3171 (if (file-exists-p bibfile)
3172 (message "%s exists." bibfile)
3174 (message "!!! %s NOT FOUND !!!" bibfile))))
3179 I like convenience. Here are some aliases for faster typing.
3181 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3182 (defalias 'oro 'org-ref-open-citation-at-point)
3183 (defalias 'orc 'org-ref-citation-at-point)
3184 (defalias 'orp 'org-ref-open-pdf-at-point)
3185 (defalias 'oru 'org-ref-open-url-at-point)
3186 (defalias 'orn 'org-ref-open-notes-at-point)
3187 (defalias 'ornr 'org-ref-open-notes-from-reftex)
3189 (defalias 'orib 'org-ref-insert-bibliography-link)
3190 (defalias 'oric 'org-ref-insert-cite-link)
3191 (defalias 'orir 'org-ref-insert-ref-link)
3192 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
3194 (defalias 'orcb 'org-ref-clean-bibtex-entry)
3197 [[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.
3199 1. Make the default action to insert selected keys.
3200 2. Make open entry second action
3201 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3202 (setq helm-source-bibtex
3203 '((name . "BibTeX entries")
3204 (init . helm-bibtex-init)
3205 (candidates . helm-bibtex-candidates)
3206 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3207 (action . (("Insert citation" . helm-bibtex-insert-citation)
3208 ("Show entry" . helm-bibtex-show-entry)
3209 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3210 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3211 ("Insert reference" . helm-bibtex-insert-reference)
3212 ("Insert BibTeX key" . helm-bibtex-insert-key)
3213 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3214 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3215 ("Edit notes" . helm-bibtex-edit-notes)
3219 Now, let us define a function that inserts the cite links:
3220 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3221 (defun helm-bibtex-format-org-ref (keys)
3222 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3223 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.
3225 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3227 C-u C-u will change the key at point to the selected keys.
3229 (let* ((object (org-element-context))
3230 (last-char (save-excursion
3231 (goto-char (org-element-property :end object))
3233 (if (looking-at " ")
3237 ;; case where we are in a link
3238 ((and (equal (org-element-type object) 'link)
3241 (org-element-property :type object)))
3243 ;; no prefix. append keys
3244 ((equal helm-current-prefix-arg nil)
3245 (goto-char (org-element-property :end object))
3246 (while (looking-back " ") (backward-char))
3247 (insert (concat "," (mapconcat 'identity keys ","))))
3248 ;; double prefix, replace key at point
3249 ((equal helm-current-prefix-arg '(16))
3250 (setf (buffer-substring
3251 (org-element-property :begin object)
3252 (org-element-property :end object))
3254 (replace-regexp-in-string
3255 (car (org-ref-get-bibtex-key-and-file)) ; key
3256 (mapconcat 'identity keys ",") ; new keys
3257 (org-element-property :raw-link object)
3259 ;; replace space at end to avoid collapsing into next word.
3262 (message "Not found"))))
3264 ;; We are next to a link, and we want to append
3265 ;; next to a link means one character back is on a link.
3268 (and (equal (org-element-type (org-element-context)) 'link)
3271 (org-element-property :type (org-element-context)))))
3272 (while (looking-back " ") (backward-char))
3273 (insert (concat "," (mapconcat 'identity keys ","))))
3275 ;; insert fresh link
3277 ;;(message-box "fresh link")
3279 (concat (if (equal helm-current-prefix-arg '(4))
3280 (helm :sources `((name . "link types")
3281 (candidates . ,org-ref-cite-types)
3282 (action . (lambda (x) x))))
3283 org-ref-default-citation-link)
3285 (s-join "," keys))))))
3286 ;; return empty string for helm
3289 (setq helm-bibtex-format-citation-functions
3290 '((org-mode . helm-bibtex-format-org-ref)))
3292 (defun org-ref-helm-insert-cite-link (arg)
3293 "org-ref function to use helm-bibtex to insert a citation link.
3294 With one prefix arg, insert a ref link.
3295 With two prefix args, insert a label link."
3299 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3302 (org-ref-helm-insert-ref-link))
3304 (org-ref-helm-insert-label-link))))
3306 (require 'helm-bibtex)
3308 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3309 (setq helm-bibtex-fallback-options
3310 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3312 (setq helm-bibtex-fallback-options
3315 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3316 helm-bibtex-fallback-options))
3318 (setq helm-bibtex-fallback-options
3319 (-insert-at 1 '("Open Web of Science" . (lambda () (browse-url "http://apps.webofknowledge.com")))
3320 helm-bibtex-fallback-options))
3323 ** A helm click menu
3324 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.
3325 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3326 (defun org-ref-get-citation-string-at-point ()
3327 "Get a string of a formatted citation"
3329 (let* ((results (org-ref-get-bibtex-key-and-file))
3331 (bibfile (cdr results)))
3335 (insert-file-contents bibfile)
3336 (bibtex-search-entry key)
3337 (org-ref-bib-citation)))
3339 "!!! No entry found !!!" )))
3341 (defun org-ref-cite-candidates ()
3342 "Generate the list of possible candidates for click actions on a cite link.
3343 Checks for pdf and doi, and add appropriate functions."
3345 (let* ((results (org-ref-get-bibtex-key-and-file))
3347 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3348 (bibfile (cdr results))
3349 (url (save-excursion
3351 (insert-file-contents bibfile)
3352 (bibtex-search-entry key)
3353 (bibtex-autokey-get-field "url"))))
3354 (doi (save-excursion
3356 (insert-file-contents bibfile)
3357 (bibtex-search-entry key)
3358 ;; I like this better than bibtex-url which does not always find
3360 (bibtex-autokey-get-field "doi"))))
3361 (candidates `(("Quit" . org-ref-citation-at-point)
3362 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3363 ;; for some reason, when there is no doi or url, they are returned as "". I
3364 ;; prefer nil so we correct this here.
3365 (when (string= doi "") (setq doi nil))
3366 (when (string= url "") (setq url nil))
3368 ;; Conditional pdf functions
3369 (if (file-exists-p pdf-file)
3372 '("Open pdf" . org-ref-open-pdf-at-point)
3376 '("Try to get pdf" . (lambda ()
3377 (save-window-excursion
3378 (org-ref-open-citation-at-point)
3379 (bibtex-beginning-of-entry)
3380 (doi-utils-get-bibtex-entry-pdf))))
3386 '("Open notes" . org-ref-open-notes-at-point)
3389 ;; conditional url and doi functions
3393 '("Open in browser" . org-ref-open-url-at-point)
3398 (add-to-list 'candidates x t))
3399 `(("WOS" . org-ref-wos-at-point)
3400 ("Related articles in WOS" . org-ref-wos-related-at-point)
3401 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3402 ("Google Scholar" . org-ref-google-scholar-at-point)
3403 ("Pubmed" . org-ref-pubmed-at-point)
3404 ("Crossref" . org-ref-crossref-at-point)
3409 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3414 '("Copy key to clipboard" . (lambda ()
3416 (car (org-ref-get-bibtex-key-and-file)))))
3421 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3426 '("Email bibtex entry and pdf" . (lambda ()
3428 (org-ref-open-citation-at-point)
3429 (email-bibtex-entry))))
3431 ;; finally return a numbered list of the candidates
3433 for cell in candidates
3434 collect (cons (format "%2s. %s" i (car cell))
3438 (defvar org-ref-helm-user-candidates '()
3439 "List of user-defined candidates to act when clicking on a cite link.
3440 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.
3443 ;; example of adding your own function
3445 'org-ref-helm-user-candidates
3446 '("Example" . (lambda () (message-box "You did it!")))
3449 (defun org-ref-cite-click-helm (key)
3451 1. get name and candidates before entering helm because we need the org-buffer.
3452 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer."
3454 (let ((name (org-ref-get-citation-string-at-point))
3455 (candidates (org-ref-cite-candidates))
3456 (cb (current-buffer)))
3458 (helm :sources `(((name . ,name)
3459 (candidates . ,candidates)
3460 (action . (lambda (f)
3461 (switch-to-buffer cb)
3463 ((name . "User functions")
3464 (candidates . ,org-ref-helm-user-candidates)
3465 (action . (lambda (f)
3466 (switch-to-buffer cb)
3472 : org-ref-cite-click-helm
3475 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3480 This code will tangle the elisp code out to org-ref.el and load it.
3482 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
3484 Alternatively you may use:
3486 [[elisp:(org-babel-load-file "org-ref.org")]]