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}" 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 "Return a list of #+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 "Return list of table names in the buffer."
1103 (org-element-map (org-element-parse-buffer 'element) 'table
1105 (org-element-property :name table))))
1108 Now, we can put all the labels together which will give us a list of candidates.
1110 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1111 (defun org-ref-get-labels ()
1112 "Returns a list of labels in the buffer that you can make a ref link to.
1113 This is used to auto-complete ref links and in helm menus."
1117 (goto-char (point-min))
1118 (let ((matches '()))
1119 ;; these are the label:stuff kinds
1120 (while (re-search-forward "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1121 (add-to-list 'matches (match-string-no-properties 1) t))
1123 (org-ref-get-org-labels)
1124 (org-ref-get-latex-labels)
1125 (org-ref-get-tblnames)
1126 (org-ref-get-custom-ids))))))
1129 Let us make a helm function to insert a label link. This will help you enter unique labels by showing matching labels until they are all gone and you are left with a unique one. If you are on a link, it means you want to replace it.
1130 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1131 (defun org-ref-helm-insert-label-link ()
1132 "Insert a label link. helm just shows you what labels already exist.
1133 If you are on a label link, replace it."
1135 (let* ((labels (org-ref-get-labels))
1136 (cb (current-buffer)))
1137 (helm :sources `(((name . "Existing labels")
1138 (candidates . ,labels)
1139 ;; default action is to open to the label
1140 (action . (lambda (label)
1141 ;; unfortunately I do not have markers here
1142 (org-open-link-from-string (format "ref:%s" label))))
1143 ;; if you select a label, replace current one
1144 (action . (lambda (label)
1145 (switch-to-buffer ,cb)
1147 ;; no prefix or on a link
1148 ((equal helm-current-prefix-arg nil)
1149 (let* ((object (org-element-context))
1150 (last-char (save-excursion
1151 (goto-char (org-element-property :end object))
1153 (if (looking-at " ")
1156 (when (-contains? '("label")
1157 (org-element-property :type object))
1158 ;; we are on a link, so replace it.
1161 (org-element-property :begin object)
1162 (org-element-property :end object))
1164 (replace-regexp-in-string
1165 (org-element-property :path object)
1167 (org-element-property :raw-link object))
1169 ;; no prefix options defined
1171 ;; no matching selection creates a new label
1172 ((name . "Create new label")
1174 ;; default action creates a new label, or replaces old one
1175 (action . (lambda (label)
1176 (switch-to-buffer ,cb)
1177 (let* ((object (org-element-context))
1178 (last-char (save-excursion
1179 (goto-char (org-element-property :end object))
1181 (if (looking-at " ")
1184 (if (-contains? '("label")
1185 (org-element-property :type object))
1186 ;; we are on a link, so replace it.
1189 (org-element-property :begin object)
1190 (org-element-property :end object))
1192 (replace-regexp-in-string
1193 (org-element-property :path object)
1195 (org-element-property :raw-link object))
1202 helm-pattern))))))))))))
1205 Now we create a completion function. This works from the org-machinery, e.g. if you type C-c C-l to insert a link, and use completion by pressing tab.
1207 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1208 (defun org-ref-complete-link (&optional arg)
1209 "Completion function for ref links"
1211 (setq label (completing-read "label: " (org-ref-get-labels)))
1212 (format "ref:%s" label)))
1215 Alternatively, you may want to just call a function that inserts a link with completion:
1217 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1218 (defun org-ref-insert-ref-link ()
1220 (insert (org-ref-complete-link)))
1223 Another alternative ref insertion is to use helm.
1225 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1226 (defun org-ref-helm-insert-ref-link ()
1227 "Helm menu to insert ref links to labels in the document.
1228 If you are on link, replace with newly selected label.
1229 Use C-u to insert a different kind of ref link.
1230 Use C-u C-u to insert a [[#custom-id]] link
1233 (let* ((labels (org-ref-get-labels))
1234 (bs (buffer-string))
1235 (contexts (with-temp-buffer
1237 (mapcar 'org-ref-get-label-context labels)))
1238 (cb (current-buffer)))
1240 (helm :input (thing-at-point 'word)
1241 :sources `(((name . "Available labels to ref")
1242 (candidates . ,(loop for label in labels
1243 for context in contexts
1244 ;; we do some kludgy adding spaces
1245 ;; and bars to make it "easier" to
1247 collect (cons (concat
1252 (split-string context "\n")
1255 ;; default action to replace or insert ref link.
1256 (action . (lambda (label)
1257 (switch-to-buffer ,cb)
1260 ;; no prefix or on a link
1261 ((equal helm-current-prefix-arg nil)
1262 (let* ((object (org-element-context))
1263 (last-char (save-excursion
1264 (goto-char (org-element-property :end object))
1266 (if (looking-at " ")
1269 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1270 (org-element-property :type object))
1271 ;; we are on a link, so replace it.
1274 (org-element-property :begin object)
1275 (org-element-property :end object))
1277 (replace-regexp-in-string
1278 (org-element-property :path object)
1280 (org-element-property :raw-link object))
1282 ;; insert a new link
1287 ;; one prefix, alternate ref link
1288 ((equal helm-current-prefix-arg '(4))
1291 (helm :sources '((name . "Ref link types")
1292 (candidates . ("ref" "eqref" "pageref" "nameref"))
1293 (action . (lambda (x) x))))
1295 ;; two prefixes, insert section custom-id link
1296 ((equal helm-current-prefix-arg '(16))
1298 (format "[[#%s]]" label)))
1303 : org-ref-helm-insert-ref-link
1307 This refers to the page of a label in LaTeX.
1309 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1313 "on clicking goto the label. Navigate back with C-c &"
1314 (org-mark-ring-push)
1315 ;; next search from beginning of the buffer
1321 (goto-char (point-min))
1322 (re-search-forward (format "label:%s\\b" label) nil t))
1326 (goto-char (point-min))
1327 (re-search-forward (format "\\label{%s}" label) nil t))
1329 ;; #+label: name org-definition
1331 (goto-char (point-min))
1332 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1336 (goto-char (point-min))
1337 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1339 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1340 ;; you need [[#label]] links.
1343 ; (goto-char (point-min))
1344 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1346 ;; we did not find anything, so go back to where we came
1347 (org-mark-ring-goto)
1348 (error "%s not found" label))
1349 (message "go back with (org-mark-ring-goto) `C-c &`"))
1351 (lambda (keyword desc format)
1353 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1355 (format "\\pageref{%s}" keyword)))))
1358 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1359 (defun org-pageref-complete-link (&optional arg)
1360 "Completion function for ref links"
1362 (setq label (completing-read "label: " (org-ref-get-labels)))
1363 (format "ref:%s" label)))
1366 Alternatively, you may want to just call a function that inserts a link with completion:
1368 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1369 (defun org-pageref-insert-ref-link ()
1371 (insert (org-pageref-complete-link)))
1376 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.
1378 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1382 "on clicking goto the label. Navigate back with C-c &"
1383 (org-mark-ring-push)
1384 ;; next search from beginning of the buffer
1390 (goto-char (point-min))
1391 (re-search-forward (format "\\label{%s}" label) nil t))
1393 ;; we did not find anything, so go back to where we came
1394 (org-mark-ring-goto)
1395 (error "%s not found" label))
1396 (message "go back with (org-mark-ring-goto) `C-c &`"))
1398 (lambda (keyword desc format)
1400 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1402 (format "\\nameref{%s}" keyword)))))
1406 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1408 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1412 "on clicking goto the label. Navigate back with C-c &"
1413 (org-mark-ring-push)
1414 ;; next search from beginning of the buffer
1416 (goto-char (point-min))
1419 ;; search forward for the first match
1421 (re-search-forward (format "label:%s" label) nil t)
1423 (re-search-forward (format "\\label{%s}" label) nil t)
1424 ;; #+label: name org-definition
1425 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1426 (org-mark-ring-goto)
1427 (error "%s not found" label))
1428 (message "go back with (org-mark-ring-goto) `C-c &`"))
1430 (lambda (keyword desc format)
1432 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1434 (format "\\eqref{%s}" keyword)))))
1438 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.
1440 *** Implementing the click actions of cite
1442 **** Getting the key we clicked on
1443 The first thing we need is to get the bibtex key we clicked on.
1445 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1446 (defun org-ref-get-bibtex-key-under-cursor ()
1447 "returns key under the bibtex cursor. We search forward from
1448 point to get a comma, or the end of the link, and then backwards
1449 to get a comma, or the beginning of the link. that delimits the
1450 keyword we clicked on. We also strip the text properties."
1452 (let* ((object (org-element-context))
1453 (link-string (org-element-property :path object)))
1454 ;; you may click on the part before the citations. here we make
1455 ;; sure to move to the beginning so you get the first citation.
1457 (goto-char (org-element-property :begin object))
1458 (search-forward link-string (org-element-property :end object))
1459 (goto-char (match-beginning 0))
1460 ;; check if we clicked before the path and move as needed.
1461 (unless (< cp (point))
1464 (if (not (org-element-property :contents-begin object))
1465 ;; this means no description in the link
1467 ;; we need the link path start and end
1469 (goto-char (org-element-property :begin object))
1470 (search-forward link-string nil nil 1)
1471 (setq link-string-beginning (match-beginning 0))
1472 (setq link-string-end (match-end 0)))
1474 ;; The key is the text between commas, or the link boundaries
1476 (if (search-forward "," link-string-end t 1)
1477 (setq key-end (- (match-end 0) 1)) ; we found a match
1478 (setq key-end link-string-end))) ; no comma found so take the end
1479 ;; and backward to previous comma from point which defines the start character
1481 (if (search-backward "," link-string-beginning 1 1)
1482 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1483 (setq key-beginning link-string-beginning))) ; no match found
1484 ;; save the key we clicked on.
1485 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1486 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1488 ;; link with description. assume only one key
1492 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.
1494 **** Getting the bibliographies
1495 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1496 (defun org-ref-find-bibliography ()
1497 "find the bibliography in the buffer.
1498 This function sets and returns cite-bibliography-files, which is a list of files
1499 either from bibliography:f1.bib,f2.bib
1500 \bibliography{f1,f2}
1501 internal bibliographies
1503 falling back to what the user has set in org-ref-default-bibliography
1508 (goto-char (point-min))
1509 ;; look for a bibliography link
1510 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1511 (setq org-ref-bibliography-files
1512 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1513 (throw 'result org-ref-bibliography-files))
1516 ;; we did not find a bibliography link. now look for \bibliography
1517 (goto-char (point-min))
1518 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1519 ;; split, and add .bib to each file
1520 (setq org-ref-bibliography-files
1521 (mapcar (lambda (x) (concat x ".bib"))
1522 (mapcar 'org-ref-strip-string
1523 (split-string (match-string 1) ","))))
1524 (throw 'result org-ref-bibliography-files))
1526 ;; no bibliography found. maybe we need a biblatex addbibresource
1527 (goto-char (point-min))
1528 ;; look for a bibliography link
1529 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1530 (setq org-ref-bibliography-files
1531 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1532 (throw 'result org-ref-bibliography-files))
1534 ;; we did not find anything. use defaults
1535 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1537 ;; set reftex-default-bibliography so we can search
1538 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1539 org-ref-bibliography-files)
1542 **** Finding the bibliography file a key is in
1543 Now, we can see if an entry is in a file.
1545 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1546 (defun org-ref-key-in-file-p (key filename)
1547 "determine if the key is in the file"
1548 (interactive "skey: \nsFile: ")
1549 (save-current-buffer
1550 (let ((bibtex-files (list filename)))
1551 (bibtex-search-entry key t))))
1554 Finally, we want to know which file the key is in.
1556 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1557 (defun org-ref-get-bibtex-key-and-file (&optional key)
1558 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1560 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1563 (setq key (org-ref-get-bibtex-key-under-cursor)))
1564 (setq file (catch 'result
1565 (loop for file in org-ref-bibliography-files do
1566 (if (org-ref-key-in-file-p key (file-truename file))
1567 (throw 'result file)))))
1571 **** convenience functions to act on citation at point
1573 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1575 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.
1577 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1578 (defun org-ref-open-pdf-at-point ()
1579 "open the pdf for bibtex key under point if it exists"
1581 (let* ((results (org-ref-get-bibtex-key-and-file))
1583 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1584 (if (file-exists-p pdf-file)
1585 (org-open-file pdf-file)
1586 (message "no pdf found for %s" key))))
1589 (defun org-ref-open-url-at-point ()
1590 "open the url for bibtex key under point."
1592 (let* ((results (org-ref-get-bibtex-key-and-file))
1594 (bibfile (cdr results)))
1597 (insert-file-contents bibfile)
1598 (bibtex-search-entry key)
1599 ;; I like this better than bibtex-url which does not always find
1602 (let ((url (bibtex-autokey-get-field "url")))
1607 (let ((doi (bibtex-autokey-get-field "doi")))
1609 (if (string-match "^http" doi)
1611 (browse-url (format "http://dx.doi.org/%s" doi)))
1612 (throw 'done nil))))))))
1615 (defun org-ref-open-notes-at-point ()
1616 "open the notes for bibtex key under point."
1618 (let* ((results (org-ref-get-bibtex-key-and-file))
1620 (bibfile (cdr results)))
1623 (insert-file-contents bibfile)
1624 (bibtex-search-entry key)
1625 (org-ref-open-bibtex-notes)))))
1628 (defun org-ref-citation-at-point ()
1629 "give message of current citation at point"
1631 (let* ((cb (current-buffer))
1632 (results (org-ref-get-bibtex-key-and-file))
1634 (bibfile (cdr results)))
1635 (message "%s" (progn
1637 (insert-file-contents bibfile)
1638 (bibtex-search-entry key)
1639 (org-ref-bib-citation))))))
1642 (defun org-ref-open-citation-at-point ()
1643 "open bibtex file to key at point"
1645 (let* ((cb (current-buffer))
1646 (results (org-ref-get-bibtex-key-and-file))
1648 (bibfile (cdr results)))
1650 (bibtex-search-entry key)))
1653 **** the actual minibuffer menu
1654 Now, we create the menu. This is a rewrite of the cite action. This makes the function extendable by users.
1656 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1657 (defvar org-ref-cite-menu-funcs '()
1658 "Functions to run on cite click menu. Each entry is a list of (key menu-name function).
1659 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.")
1662 (defvar org-ref-user-cite-menu-funcs
1663 '(("C" "rossref" org-ref-crossref-at-point)
1664 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1665 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1666 "user-defined functions to run on bibtex key at point.")
1669 (defun org-ref-copy-entry-as-summary ()
1670 "Copy the bibtex entry for the citation at point as a summary."
1672 (save-window-excursion
1673 (org-ref-open-citation-at-point)
1674 (kill-new (org-ref-bib-citation))))
1677 (defun org-ref-copy-entry-at-point-to-file ()
1678 "Copy the bibtex entry for the citation at point to NEW-FILE.
1679 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."
1681 (let ((new-file (ido-completing-read
1683 (append org-ref-default-bibliography
1684 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1685 (key (org-ref-get-bibtex-key-under-cursor)))
1686 (save-window-excursion
1687 (org-ref-open-citation-at-point)
1688 (bibtex-copy-entry-as-kill))
1690 (let ((bibtex-files (list (file-truename new-file))))
1691 (if (assoc key (bibtex-global-key-alist))
1692 (message "That key already exists in %s" new-file)
1694 (save-window-excursion
1695 (find-file new-file)
1696 (goto-char (point-max))
1697 ;; make sure we are at the beginning of a line.
1698 (unless (looking-at "^") (insert "\n\n"))
1703 (defun org-ref-get-doi-at-point ()
1704 "Get doi for key at point."
1706 (let* ((results (org-ref-get-bibtex-key-and-file))
1708 (bibfile (cdr results))
1712 (insert-file-contents bibfile)
1713 (bibtex-search-entry key)
1714 (setq doi (bibtex-autokey-get-field "doi"))
1715 ;; in case doi is a url, remove the url part.
1716 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1719 ;; functions that operate on key at point for click menu
1720 (defun org-ref-wos-at-point ()
1721 "open the doi in wos for bibtex key under point."
1723 (doi-utils-wos (org-ref-get-doi-at-point)))
1726 (defun org-ref-wos-citing-at-point ()
1727 "open the doi in wos citing articles for bibtex key under point."
1729 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1732 (defun org-ref-wos-related-at-point ()
1733 "open the doi in wos related articles for bibtex key under point."
1735 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1738 (defun org-ref-google-scholar-at-point ()
1739 "open the doi in google scholar for bibtex key under point."
1741 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1744 (defun org-ref-pubmed-at-point ()
1745 "open the doi in pubmed for bibtex key under point."
1747 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1750 (defun org-ref-crossref-at-point ()
1751 "open the doi in crossref for bibtex key under point."
1753 (doi-utils-crossref (org-ref-get-doi-at-point)))
1756 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1757 "action when a cite link is clicked on.
1758 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."
1760 (let* ((results (org-ref-get-bibtex-key-and-file))
1762 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1763 (bibfile (cdr results))
1764 (url (save-excursion
1766 (insert-file-contents bibfile)
1767 (bibtex-search-entry key)
1768 (bibtex-autokey-get-field "url"))))
1769 (doi (save-excursion
1771 (insert-file-contents bibfile)
1772 (bibtex-search-entry key)
1773 ;; I like this better than bibtex-url which does not always find
1775 (bibtex-autokey-get-field "doi")))))
1777 (when (string= "" doi) (setq doi nil))
1778 (when (string= "" url) (setq url nil))
1779 (setq org-ref-cite-menu-funcs '())
1785 'org-ref-cite-menu-funcs
1786 '("o" "pen" org-ref-open-citation-at-point)))
1789 (when (file-exists-p pdf-file)
1791 'org-ref-cite-menu-funcs
1792 `("p" "df" ,org-ref-open-pdf-function) t))
1796 'org-ref-cite-menu-funcs
1797 '("n" "otes" org-ref-open-notes-at-point) t)
1802 'org-ref-cite-menu-funcs
1803 '("u" "rl" org-ref-open-url-at-point) t))
1808 'org-ref-cite-menu-funcs
1809 '("w" "os" org-ref-wos-at-point) t)
1812 'org-ref-cite-menu-funcs
1813 '("c" "iting" org-ref-wos-citing-at-point) t)
1816 'org-ref-cite-menu-funcs
1817 '("r" "elated" org-ref-wos-related-at-point) t)
1820 'org-ref-cite-menu-funcs
1821 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1824 'org-ref-cite-menu-funcs
1825 '("P" "ubmed" org-ref-pubmed-at-point) t))
1827 ;; add user functions
1828 (dolist (tup org-ref-user-cite-menu-funcs)
1830 'org-ref-cite-menu-funcs
1835 'org-ref-cite-menu-funcs
1836 '("q" "uit" (lambda ())) t)
1838 ;; now we make a menu
1839 ;; construct menu string as a message
1842 (let* ((results (org-ref-get-bibtex-key-and-file))
1844 (bibfile (cdr results)))
1847 (insert-file-contents bibfile)
1848 (bibtex-search-entry key)
1849 (org-ref-bib-citation))))
1853 (concat "[" (elt tup 0) "]"
1855 org-ref-cite-menu-funcs "")))
1857 (let* ((input (read-char-exclusive))
1859 (char-to-string input) org-ref-cite-menu-funcs)))
1860 ;; now run the function (2nd element in choice)
1869 : org-ref-cite-onclick-minibuffer-menu
1871 *** A function to format a cite link
1873 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.
1875 #+BEGIN_SRC emacs-lisp :tangle no
1876 ;(defun org-ref-cite-link-format (keyword desc format)
1878 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1879 ; ((eq format 'latex)
1880 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1881 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1885 *** The actual cite link
1886 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1888 #+BEGIN_SRC emacs-lisp :tangle no
1891 ; 'org-ref-cite-onclick-minibuffer-menu
1892 ; 'org-ref-cite-link-format)
1895 *** Automatic definition of the cite links
1896 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.
1898 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1899 (defmacro org-ref-make-completion-function (type)
1900 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1906 (let ((bibtex-files (org-ref-find-bibliography)))
1907 (bibtex-global-key-alist))))))
1910 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.
1912 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1913 (defmacro org-ref-make-format-function (type)
1914 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1919 (format "[[#%s][%s]]" key key))
1920 (org-ref-split-and-strip-string keyword) ","))
1927 (org-ref-split-and-strip-string keyword) ",") "]"))
1932 (format "<a href=\"#%s\">%s</a>" key key))
1933 (org-ref-split-and-strip-string keyword) ","))
1936 (if (string= (substring type -1) "s")
1937 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1938 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1939 (org-ref-split-and-strip-string keyword) ""))
1941 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1942 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1948 We create the links by mapping the function onto the list of defined link types.
1950 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1951 (defun org-ref-format-citation-description (desc)
1952 "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 ::."
1955 ((string-match "::" desc)
1956 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1957 (t (format "[%s]" desc))))
1959 (defun org-ref-define-citation-link (type &optional key)
1960 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1961 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1962 and the completion function."
1963 (interactive "sCitation Type: \ncKey: ")
1965 ;; create the formatting function
1966 (eval `(org-ref-make-format-function ,type))
1971 org-ref-cite-onclick-function
1972 (quote ,(intern (format "org-ref-format-%s" type)))))
1974 ;; create the completion function
1975 (eval `(org-ref-make-completion-function ,type))
1977 ;; store new type so it works with adding citations, which checks
1978 ;; for existence in this list
1979 (add-to-list 'org-ref-cite-types type)
1981 ;; and finally if a key is specified, we modify the reftex menu
1983 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1984 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1985 `((,key . ,(concat type ":%l")))))))
1987 ;; create all the link types and their completion functions
1988 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1991 *** org-ref-insert-cite-link
1992 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.
1994 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1995 (defun org-ref-insert-cite-link (alternative-cite)
1996 "Insert a default citation link using reftex. If you are on a link, it
1997 appends to the end of the link, otherwise, a new link is
1998 inserted. Use a prefix arg to get a menu of citation types."
2000 (org-ref-find-bibliography)
2001 (let* ((object (org-element-context))
2002 (link-string-beginning (org-element-property :begin object))
2003 (link-string-end (org-element-property :end object))
2004 (path (org-element-property :path object)))
2006 (if (not alternative-cite)
2009 ;; case where we are in a link
2010 ((and (equal (org-element-type object) 'link)
2011 (-contains? org-ref-cite-types (org-element-property :type object)))
2012 (goto-char link-string-end)
2013 ;; sometimes there are spaces at the end of the link
2014 ;; this code moves point pack until no spaces are there
2015 (while (looking-back " ") (backward-char))
2016 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
2018 ;; We are next to a link, and we want to append
2021 (and (equal (org-element-type (org-element-context)) 'link)
2022 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
2023 (while (looking-back " ") (backward-char))
2024 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
2026 ;; insert fresh link
2029 (concat org-ref-default-citation-link
2031 (mapconcat 'identity (reftex-citation t) ",")))))
2033 ;; you pressed a C-u so we run this code
2037 cite:zhou-2004-first-lda-u,paier-2006-errat,boes-2015-estim-bulk
2041 : org-ref-insert-cite-link
2043 *** Completion in cite links
2044 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.
2046 #+BEGIN_SRC emacs-lisp :tangle no
2047 (defun org-cite-complete-link (&optional arg)
2048 "Completion function for cite links"
2050 org-ref-default-citation-link
2053 (let ((bibtex-files (org-ref-find-bibliography)))
2054 (bibtex-global-key-alist)))))
2057 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
2059 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2060 (defun org-ref-insert-cite-with-completion (type)
2061 "Insert a cite link with completion"
2062 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
2063 (insert (funcall (intern (format "org-%s-complete-link" type)))))
2066 ** Storing links to a bibtex entry
2067 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.
2069 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2070 (defun org-ref-store-bibtex-entry-link ()
2071 "Save a citation link to the current bibtex entry. Saves in the default link type."
2073 (let ((link (concat org-ref-default-citation-link
2076 (bibtex-beginning-of-entry)
2077 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
2078 (message "saved %s" link)
2079 (push (list link) org-stored-links)
2080 (car org-stored-links)))
2084 org-ref minimally supports index entries. To make an index in a file, you should put in the LaTeX header these lines
2087 #+LATEX_HEADER: \usepackage{makeidx}
2088 #+LATEX_HEADER: \makeindex
2091 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.
2094 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.
2099 [[index:hello!Sam@\textsl{Sam}]]
2100 [[index:Lin@\textbf{Lin}]]
2101 [[index:Joe|textit]]
2102 [[index:Lin@\textbf{Lin}]]
2103 [[index:Peter|see {hello}]]
2104 [[index:Jen|seealso{Jenny}]]
2106 index:encodings!input!cp850
2108 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2114 (lambda (path desc format)
2117 (format "\\index{%s}" path)))))
2119 ;; this will generate a temporary index of entries in the file.
2123 (let ((*index-links* '())
2124 (*initial-letters* '()))
2127 (org-element-map (org-element-parse-buffer) 'link
2129 (let ((type (nth 0 link))
2130 (plist (nth 1 link)))
2132 (when (equal (plist-get plist ':type) "index")
2135 (cons (plist-get plist :path)
2137 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2139 (plist-get plist :begin) ;; position of link
2140 ;; grab a description
2142 (goto-char (plist-get plist :begin))
2143 (if (thing-at-point 'sentence)
2145 (replace-regexp-in-string
2146 "\n" "" (thing-at-point 'sentence))
2147 ;; or call it a link
2151 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2153 ;; now first letters
2154 (dolist (link *index-links*)
2155 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2157 ;; now create the index
2158 (switch-to-buffer (get-buffer-create "*index*"))
2161 (insert "#+TITLE: Index\n\n")
2162 (dolist (letter *initial-letters*)
2163 (insert (format "* %s\n" (upcase letter)))
2164 ;; now process the links
2167 (string= letter (substring (car (car *index-links*)) 0 1)))
2168 (let ((link (pop *index-links*)))
2169 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2170 (switch-to-buffer "*index*")))
2172 (lambda (path desc format)
2175 (format "\\printindex")))))
2179 | 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*)) |
2180 | lambda | (path desc format) | (cond ((eq format (quote latex)) (format \printindex))) |
2183 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.
2185 #+LATEX_HEADER: \usepackage{glossaries}
2186 #+LATEX_HEADER: \makeglossaries
2188 And at the end of the document put \makeglossaries.
2190 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2193 nil ;; no follow action
2194 (lambda (path desc format)
2197 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2203 nil ;; no follow action
2204 (lambda (path desc format)
2207 (format "\\gls{%s}" path)))))
2212 nil ;; no follow action
2213 (lambda (path desc format)
2216 (format "\\glspl{%s}" path)))))
2221 nil ;; no follow action
2222 (lambda (path desc format)
2225 (format "\\Gls{%s}" path)))))
2230 nil ;; no follow action
2231 (lambda (path desc format)
2234 (format "\\Glspl{%s}" path)))))
2238 ** create simple text citation from bibtex entry
2240 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2241 (defun org-ref-bib-citation ()
2242 "From a bibtex entry, create and return a simple citation string.
2243 This assumes you are in an article."
2245 (bibtex-beginning-of-entry)
2246 (let* ((cb (current-buffer))
2247 (bibtex-expand-strings t)
2248 (entry (loop for (key . value) in (bibtex-parse-entry t)
2249 collect (cons (downcase key) value)))
2250 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2251 (year (reftex-get-bib-field "year" entry))
2252 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2253 (key (reftex-get-bib-field "=key=" entry))
2254 (journal (reftex-get-bib-field "journal" entry))
2255 (volume (reftex-get-bib-field "volume" entry))
2256 (pages (reftex-get-bib-field "pages" entry))
2257 (doi (reftex-get-bib-field "doi" entry))
2258 (url (reftex-get-bib-field "url" entry))
2260 ;;authors, "title", Journal, vol(iss):pages (year).
2261 (format "%s, \"%s\", %s, %s:%s (%s)"
2262 author title journal volume pages year)))
2266 : org-ref-bib-citation
2269 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2270 (defun org-ref-bib-html-citation ()
2271 "from a bibtex entry, create and return a simple citation with html links."
2273 (bibtex-beginning-of-entry)
2274 (let* ((cb (current-buffer))
2275 (bibtex-expand-strings t)
2276 (entry (loop for (key . value) in (bibtex-parse-entry t)
2277 collect (cons (downcase key) value)))
2278 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2279 (year (reftex-get-bib-field "year" entry))
2280 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2281 (key (reftex-get-bib-field "=key=" entry))
2282 (journal (reftex-get-bib-field "journal" entry))
2283 (volume (reftex-get-bib-field "volume" entry))
2284 (pages (reftex-get-bib-field "pages" entry))
2285 (doi (reftex-get-bib-field "doi" entry))
2286 (url (reftex-get-bib-field "url" entry))
2288 ;;authors, "title", Journal, vol(iss):pages (year).
2289 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2290 author title journal volume pages year)
2291 (when url (format " <a href=\"%s\">link</a>" url))
2292 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2296 ** open pdf from bibtex
2297 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2298 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2299 (defun org-ref-open-bibtex-pdf ()
2300 "open pdf for a bibtex entry, if it exists. assumes point is in
2301 the entry of interest in the bibfile. but does not check that."
2304 (bibtex-beginning-of-entry)
2305 (let* ((bibtex-expand-strings t)
2306 (entry (bibtex-parse-entry t))
2307 (key (reftex-get-bib-field "=key=" entry))
2308 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2310 (if (file-exists-p pdf)
2311 (org-open-link-from-string (format "[[file:%s]]" pdf))
2315 ** open notes from bibtex
2316 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2318 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2319 (defun org-ref-open-bibtex-notes ()
2320 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
2322 I never did figure out how to use reftex to make this happen
2323 non-interactively. the reftex-format-citation function did not
2324 work perfectly; there were carriage returns in the strings, and
2325 it did not put the key where it needed to be. so, below I replace
2326 the carriage returns and extra spaces with a single space and
2327 construct the heading by hand."
2330 (bibtex-beginning-of-entry)
2331 (let* ((cb (current-buffer))
2332 (bibtex-expand-strings t)
2333 (entry (loop for (key . value) in (bibtex-parse-entry t)
2334 collect (cons (downcase key) value)))
2335 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2336 (year (reftex-get-bib-field "year" entry))
2337 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2338 (key (reftex-get-bib-field "=key=" entry))
2339 (journal (reftex-get-bib-field "journal" entry))
2340 (volume (reftex-get-bib-field "volume" entry))
2341 (pages (reftex-get-bib-field "pages" entry))
2342 (doi (reftex-get-bib-field "doi" entry))
2343 (url (reftex-get-bib-field "url" entry))
2346 ;; save key to clipboard to make saving pdf later easier by pasting.
2349 (kill-ring-save (point-min) (point-max)))
2351 ;; now look for entry in the notes file
2352 (if org-ref-bibliography-notes
2353 (find-file-other-window org-ref-bibliography-notes)
2354 (error "org-ref-bib-bibliography-notes is not set to anything"))
2356 (goto-char (point-min))
2357 ;; put new entry in notes if we don't find it.
2358 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2359 (funcall org-ref-open-notes-function)
2360 ;; no entry found, so add one
2361 (insert (format "\n** TODO %s - %s" year title))
2373 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2374 key author journal year volume pages doi url key org-ref-pdf-directory key))
2378 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2379 (defun org-ref-open-notes-from-reftex ()
2380 "Call reftex, and open notes for selected entry."
2382 (let ((bibtex-key )))
2384 ;; now look for entry in the notes file
2385 (if org-ref-bibliography-notes
2386 (find-file-other-window org-ref-bibliography-notes)
2387 (error "org-ref-bib-bibliography-notes is not set to anything"))
2389 (goto-char (point-min))
2391 (re-search-forward (format
2393 (first (reftex-citation t)) nil 'end))
2394 (funcall org-ref-open-notes-function))
2397 ** open url in browser from bibtex
2399 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2401 + 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.
2403 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2404 (defun org-ref-open-in-browser ()
2405 "Open the bibtex entry at point in a browser using the url field or doi field"
2408 (bibtex-beginning-of-entry)
2410 (let ((url (bibtex-autokey-get-field "url")))
2415 (let ((doi (bibtex-autokey-get-field "doi")))
2417 (if (string-match "^http" doi)
2419 (browse-url (format "http://dx.doi.org/%s" doi)))
2421 (message "No url or doi found"))))
2425 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.
2427 *** function to upload bibtex to citeulike
2429 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2430 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2431 "with point in a bibtex entry get bibtex string and submit to citeulike.
2433 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2435 (message "uploading to citeulike")
2437 (bibtex-narrow-to-entry)
2438 (let ((startpos (point-min))
2439 (endpos (point-max))
2440 (bibtex-string (buffer-string))
2441 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2442 (with-temp-buffer (insert bibtex-string)
2443 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2446 *** The upload script
2447 Here is the python script for uploading.
2449 *************** TODO document how to get the cookies
2453 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
2455 import pickle, requests, sys
2458 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
2459 cookies = pickle.load(f)
2461 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
2463 bibtex = sys.stdin.read()
2465 data = {'pasted':bibtex,
2467 'tag_parsing':'simple',
2468 'strip_brackets':'no',
2469 'update_id':'bib-key',
2470 'btn_bibtex':'Import BibTeX file ...'}
2472 headers = {'content-type': 'multipart/form-data',
2473 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
2475 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
2479 ** Build a pdf from a bibtex file
2480 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.
2482 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2483 (defun org-ref-build-full-bibliography ()
2484 "build pdf of all bibtex entries, and open it."
2486 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2487 (bib-base (file-name-sans-extension bibfile))
2488 (texfile (concat bib-base ".tex"))
2489 (pdffile (concat bib-base ".pdf")))
2492 (insert (format "\\documentclass[12pt]{article}
2493 \\usepackage[version=3]{mhchem}
2495 \\usepackage[numbers]{natbib}
2496 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2500 \\bibliographystyle{unsrtnat}
2502 \\end{document}" bib-base))
2504 (shell-command (concat "pdflatex " bib-base))
2505 (shell-command (concat "bibtex " bib-base))
2506 (shell-command (concat "pdflatex " bib-base))
2507 (shell-command (concat "pdflatex " bib-base))
2508 (kill-buffer texfile)
2509 (org-open-file pdffile)
2513 ** Extract bibtex entries cited in an org-file
2514 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.
2516 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2517 (defun org-ref-extract-bibtex-entries ()
2518 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2520 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
2522 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2523 (tempname (make-temp-file "extract-bib"))
2524 (contents (buffer-string))
2525 (cb (current-buffer))
2526 basename texfile bibfile results)
2528 ;; open tempfile and insert org-buffer contents
2529 (find-file tempname)
2531 (setq basename (file-name-sans-extension
2532 (file-name-nondirectory buffer-file-name))
2533 texfile (concat tempname ".tex")
2534 bibfile (concat tempname ".bib"))
2536 ;; see if we have a bibliography, and insert the default one if not.
2538 (goto-char (point-min))
2539 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2540 (insert (format "\nbibliography:%s"
2541 (mapconcat 'identity reftex-default-bibliography ",")))))
2544 ;; get a latex file and extract the references
2545 (org-latex-export-to-latex)
2548 (reftex-create-bibtex-file bibfile)
2550 ;; save results of the references
2551 (setq results (buffer-string))
2553 ;; kill buffers. these are named by basename, not full path
2554 (kill-buffer (concat basename ".bib"))
2555 (kill-buffer (concat basename ".tex"))
2556 (kill-buffer basename)
2558 (delete-file bibfile)
2559 (delete-file texfile)
2560 (delete-file tempname)
2562 ;; Now back to the original org buffer and insert the results
2563 (switch-to-buffer cb)
2564 (when (not (string= "" results))
2566 (goto-char (point-max))
2568 (org-insert-heading)
2569 (insert (format " Bibtex entries
2571 ,#+BEGIN_SRC text :tangle %s
2573 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2576 ** Find bad cite links
2578 :ID: 8515E800-EDA0-4B2A-85FD-55B6FF849203
2580 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.
2582 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2585 (defun index (substring list)
2586 "return the index of string in a list of strings"
2589 (dolist (arg list i)
2590 (if (string-match (concat "^" substring "$") arg)
2595 ;; return counter if found, otherwise return nil
2599 (defun org-ref-find-bad-citations ()
2600 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2602 Makes a new buffer with clickable links."
2604 ;; generate the list of bibtex-keys and cited keys
2605 (let* ((bibtex-files (org-ref-find-bibliography))
2606 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2607 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2608 (bad-citations '()))
2610 (org-element-map (org-element-parse-buffer) 'link
2612 (let ((plist (nth 1 link)))
2613 (when (equal (plist-get plist ':type) "cite")
2614 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2615 (when (not (index key bibtex-keys))
2616 (setq bad-citations (append bad-citations
2617 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2618 key (buffer-name)(plist-get plist ':begin)))))
2623 (switch-to-buffer-other-window "*Missing citations*")
2626 (insert "* List of bad cite links\n")
2627 (insert (mapconcat 'identity bad-citations ""))
2628 ;(setq buffer-read-only t)
2629 (use-local-map (copy-keymap org-mode-map))
2630 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2632 (when (get-buffer "*Missing citations*")
2633 (kill-buffer "*Missing citations*"))
2634 (message "No bad cite links found"))))
2637 ** helm interface to org-ref
2638 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.
2640 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.
2642 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2643 (defun org-ref-bad-cite-candidates ()
2644 "Returns a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2645 (let* ((cp (point)) ; save to return to later
2646 (bibtex-files (org-ref-find-bibliography))
2647 (bibtex-file-path (mapconcat
2649 (file-name-directory (file-truename x)))
2651 (bibtex-keys (mapcar (lambda (x) (car x))
2652 (bibtex-global-key-alist)))
2653 (bad-citations '()))
2655 (org-element-map (org-element-parse-buffer) 'link
2657 (let ((plist (nth 1 link)))
2658 (when (-contains? org-ref-cite-types (plist-get plist ':type))
2659 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2660 (when (not (index key bibtex-keys))
2661 (goto-char (plist-get plist ':begin))
2662 (re-search-forward key)
2663 (push (cons key (point-marker)) bad-citations)))
2668 ;; It seems I forgot I already defined this earlier!
2669 ;; (defun org-ref-get-labels ()
2670 ;; "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.
2672 ;; (let ((cp (point))
2674 ;; (goto-char (point-min))
2675 ;; (while (re-search-forward "[^#+]label:\\(.*\\)\\s-" nil t)
2676 ;; (push (match-string 1) labels))
2678 ;; (goto-char (point-min))
2679 ;; (while (re-search-forward "\\label{\\(.*\\)}\\s-?" nil t)
2680 ;; (push (match-string 1) labels))
2682 ;; (goto-char (point-min))
2683 ;; (while (re-search-forward "^#\\+label:\\s-*\\(.*\\)" nil t)
2684 ;; (push (match-string 1) labels))
2686 ;; (goto-char (point-min))
2687 ;; (while (re-search-forward "^#\\+tblname:\\s-*\\(.*\\)" nil t)
2688 ;; (push (match-string 1) labels))
2689 ;; ;; check for CUSTOM_ID
2692 ;; (when (org-entry-get (point) "CUSTOM_ID")
2693 ;; (push (org-entry-get (point) "CUSTOM_ID") labels))))
2694 ;; ;; return to original place
2699 (defun org-ref-bad-ref-candidates ()
2700 "Returns a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2701 ;; first get a list of legitimate labels
2703 (labels (org-ref-get-labels))
2705 ;; now loop over ref links
2706 (goto-char (point-min))
2707 (org-element-map (org-element-parse-buffer) 'link
2709 (let ((plist (nth 1 link)))
2710 (when (or (equal (plist-get plist ':type) "ref")
2711 (equal (plist-get plist ':type) "eqref")
2712 (equal (plist-get plist ':type) "pageref")
2713 (equal (plist-get plist ':type) "nameref"))
2714 (unless (-contains? labels (plist-get plist :path))
2715 (goto-char (plist-get plist :begin))
2718 (cons (plist-get plist :path)
2719 (point-marker))))))))
2724 (defun org-ref-bad-label-candidates ()
2725 "Return a list of labels where label is multiply defined."
2726 (let ((labels (org-ref-get-labels))
2727 (multiple-labels '()))
2728 (when (not (= (length labels)
2729 (length (-uniq labels))))
2730 (dolist (label labels)
2731 (when (> (-count (lambda (a)
2734 ;; this is a multiply defined label.
2736 (goto-char (point-min))
2737 (while (re-search-forward
2738 (format "[^#+]label:%s\\s-" label) nil t)
2739 (push (cons label (point-marker)) multiple-labels))
2741 (goto-char (point-min))
2742 (while (re-search-forward
2743 (format "\\label{%s}\\s-?" label) nil t)
2744 (push (cons label (point-marker)) multiple-labels))
2746 (goto-char (point-min))
2747 (while (re-search-forward
2748 (format "^#\\+label:\\s-*%s" label) nil t)
2749 (push (cons label (point-marker)) multiple-labels))
2751 (goto-char (point-min))
2752 (while (re-search-forward
2753 (format "^#\\+tblname:\\s-*%s" label) nil t)
2754 (push (cons label (point-marker)) multiple-labels))
2760 : org-ref-bad-label-candidates
2762 Now, we have a functions for candidates, we can make helm sources for each one, and then run a helm command to view them.
2764 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2766 "Opens a helm interface to actions for org-ref.
2767 Shows bad citations, ref links and labels"
2769 (let ((cb (current-buffer))
2770 (bad-citations (org-ref-bad-cite-candidates))
2771 (bad-refs (org-ref-bad-ref-candidates))
2772 (bad-labels (org-ref-bad-label-candidates)))
2774 (helm :sources `(((name . "Bad citations")
2775 (candidates . ,bad-citations)
2776 (action . (lambda (marker)
2777 (switch-to-buffer (marker-buffer marker))
2778 (goto-char marker))))
2780 ((name . "Bad Labels")
2781 (candidates . ,bad-labels)
2782 (action . (lambda (marker)
2783 (switch-to-buffer (marker-buffer marker))
2784 (goto-char marker))))
2786 ((name . "Bad ref links")
2787 (candidates . ,bad-refs)
2788 (action . (lambda (marker)
2789 (switch-to-buffer (marker-buffer marker))
2790 (goto-char marker))))
2792 ((name . "Utilities")
2793 (candidates . (("Check buffer again" . org-ref)
2794 ("Insert citation" . helm-bibtex)
2795 ("Insert label link" . org-ref-helm-insert-label-link)
2796 ("Insert ref link" . org-ref-helm-insert-ref-link)
2797 ("List of figures" . org-ref-list-of-figures)
2798 ("List of tables" . org-ref-list-of-tables)
2799 ("Table of contents" . nil)
2801 (action . (lambda (x)
2802 (switch-to-buffer ,cb)
2805 ((name . "Export functions")
2806 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2807 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2808 ("Export to pdf and open" . (lambda ()
2809 (org-open-file (org-latex-export-to-pdf))))
2810 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2811 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2814 (action . (lambda (x)
2815 (switch-to-buffer ,cb)
2821 ** Finding non-ascii characters
2822 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2824 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2825 (defun org-ref-find-non-ascii-characters ()
2826 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2828 (occur "[^[:ascii:]]"))
2831 ** Resort a bibtex entry
2832 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.
2834 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2835 (defun org-ref-sort-bibtex-entry ()
2836 "sort fields of entry in standard order and downcase them"
2838 (bibtex-beginning-of-entry)
2839 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2840 (entry (bibtex-parse-entry))
2843 (type (cdr (assoc "=type=" entry)))
2844 (key (cdr (assoc "=key=" entry))))
2846 ;; these are the fields we want to order that are in this entry
2847 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2848 ;; we do not want to reenter these fields
2849 (setq entry-fields (remove "=key=" entry-fields))
2850 (setq entry-fields (remove "=type=" entry-fields))
2852 ;;these are the other fields in the entry
2853 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2856 ;; right now we only resort articles
2857 ((string= (downcase type) "article")
2860 (concat "@article{" key ",\n"
2863 (when (member field entry-fields)
2864 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2867 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2869 (bibtex-find-entry key)
2871 (bibtex-clean-entry)
2875 ** Clean a bibtex entry
2876 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.
2877 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.
2878 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2879 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2880 "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"
2882 (bibtex-beginning-of-entry)
2884 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2885 (unless (string-match ",$" (thing-at-point 'line))
2889 ;; check for empty pages, and put eid or article id in its place
2890 (let ((entry (bibtex-parse-entry))
2891 (pages (bibtex-autokey-get-field "pages"))
2892 (year (bibtex-autokey-get-field "year"))
2893 (doi (bibtex-autokey-get-field "doi"))
2894 ;; The Journal of Chemical Physics uses eid
2895 (eid (bibtex-autokey-get-field "eid")))
2897 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2898 ;; but we only want the doi.
2899 (when (string-match "^http://dx.doi.org/" doi)
2900 (bibtex-beginning-of-entry)
2901 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2903 (bibtex-make-field "doi")
2905 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2907 ;; asap articles often set year to 0, which messes up key
2908 ;; generation. fix that.
2909 (when (string= "0" year)
2910 (bibtex-beginning-of-entry)
2911 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2913 (bibtex-make-field "year")
2915 (insert (read-string "Enter year: ")))
2917 ;; fix pages if they are empty if there is an eid to put there.
2918 (when (string= "-" pages)
2920 (bibtex-beginning-of-entry)
2921 ;; this seems like a clunky way to set the pages field.But I
2922 ;; cannot find a better way.
2923 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2925 (bibtex-make-field "pages")
2929 ;; replace naked & with \&
2931 (bibtex-narrow-to-entry)
2932 (bibtex-beginning-of-entry)
2933 (message "checking &")
2934 (replace-regexp " & " " \\\\& ")
2937 ;; generate a key, and if it duplicates an existing key, edit it.
2939 (let ((key (bibtex-generate-autokey)))
2941 ;; first we delete the existing key
2942 (bibtex-beginning-of-entry)
2943 (re-search-forward bibtex-entry-maybe-empty-head)
2944 (if (match-beginning bibtex-key-in-head)
2945 (delete-region (match-beginning bibtex-key-in-head)
2946 (match-end bibtex-key-in-head)))
2947 ;; check if the key is in the buffer
2948 (when (save-excursion
2949 (bibtex-search-entry key))
2951 (bibtex-search-entry key)
2952 (bibtex-copy-entry-as-kill)
2953 (switch-to-buffer-other-window "*duplicate entry*")
2955 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2958 (kill-new key))) ;; save key for pasting
2960 ;; run hooks. each of these operates on the entry with no arguments.
2961 ;; this did not work like i thought, it gives a symbolp error.
2962 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2967 org-ref-clean-bibtex-entry-hook)
2969 ;; sort fields within entry
2970 (org-ref-sort-bibtex-entry)
2971 ;; check for non-ascii characters
2972 (occur "[^[:ascii:]]")
2977 : org-ref-clean-bibtex-entry
2979 ** Sort the entries in a citation link by year
2980 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2982 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2983 (defun org-ref-get-citation-year (key)
2984 "get the year of an entry with key. Returns year as a string."
2986 (let* ((results (org-ref-get-bibtex-key-and-file key))
2987 (bibfile (cdr results)))
2989 (insert-file-contents bibfile)
2990 (bibtex-search-entry key nil 0)
2991 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2994 (defun org-ref-sort-citation-link ()
2995 "replace link at point with sorted link by year"
2997 (let* ((object (org-element-context))
2998 (type (org-element-property :type object))
2999 (begin (org-element-property :begin object))
3000 (end (org-element-property :end object))
3001 (link-string (org-element-property :path object))
3003 (setq keys (org-ref-split-and-strip-string link-string))
3004 (setq years (mapcar 'org-ref-get-citation-year keys))
3005 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
3006 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
3007 ;; now get the keys separated by commas
3008 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
3009 ;; and replace the link with the sorted keys
3010 (cl--set-buffer-substring begin end (concat type ":" keys))))
3013 ** Sort entries in citation links with shift-arrow keys
3014 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
3015 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3016 (defun org-ref-swap-keys (i j keys)
3017 "swap the keys in a list with index i and j"
3018 (let ((tempi (nth i keys)))
3019 (setf (nth i keys) (nth j keys))
3020 (setf (nth j keys) tempi))
3023 (defun org-ref-swap-citation-link (direction)
3024 "move citation at point in direction +1 is to the right, -1 to the left"
3026 (let* ((object (org-element-context))
3027 (type (org-element-property :type object))
3028 (begin (org-element-property :begin object))
3029 (end (org-element-property :end object))
3030 (link-string (org-element-property :path object))
3032 ;; We only want this to work on citation links
3033 (when (-contains? org-ref-cite-types type)
3034 (setq key (org-ref-get-bibtex-key-under-cursor))
3035 (setq keys (org-ref-split-and-strip-string link-string))
3036 (setq i (index key keys)) ;; defined in org-ref
3037 (if (> direction 0) ;; shift right
3038 (org-ref-swap-keys i (+ i 1) keys)
3039 (org-ref-swap-keys i (- i 1) keys))
3040 (setq keys (mapconcat 'identity keys ","))
3041 ;; and replace the link with the sorted keys
3042 (cl--set-buffer-substring begin end (concat type ":" keys " "))
3043 ;; now go forward to key so we can move with the key
3044 (re-search-forward key)
3045 (goto-char (match-beginning 0)))))
3047 ;; add hooks to make it work
3048 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
3049 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
3052 ** Lightweight messages about links
3053 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.
3055 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3056 (defun org-ref-get-label-context (label)
3057 "Return a string of context around a label."
3060 (goto-char (point-min))
3061 (when (re-search-forward
3062 (format "label:%s\\b" label) nil t)
3063 (throw 'result (buffer-substring
3072 (goto-char (point-min))
3073 (when (re-search-forward
3074 (format "\\label{%s}" label) nil t)
3075 (throw 'result (buffer-substring
3084 (goto-char (point-min))
3085 (when (re-search-forward
3086 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
3087 (throw 'result (buffer-substring
3096 (goto-char (point-min))
3097 (when (re-search-forward
3098 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
3099 (throw 'result (buffer-substring
3107 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
3110 (defun org-ref-link-message ()
3111 "Print a minibuffer message about the link that point is on."
3113 (when (eq major-mode 'org-mode)
3114 (let* ((object (org-element-context))
3115 (type (org-element-property :type object)))
3119 ((-contains? org-ref-cite-types type)
3120 (message (org-ref-get-citation-string-at-point)))
3122 ;; message some context about the label we are referring to
3123 ((string= type "ref")
3124 (message "%scount: %s"
3125 (org-ref-get-label-context
3126 (org-element-property :path object))
3127 (org-ref-count-labels
3128 (org-element-property :path object))))
3130 ((string= type "eqref")
3131 (message "%scount: %s"
3132 (org-ref-get-label-context
3133 (org-element-property :path object))
3134 (org-ref-count-labels
3135 (org-element-property :path object))))
3137 ;; message the count
3138 ((string= type "label")
3139 (let ((count (org-ref-count-labels
3140 (org-element-property :path object))))
3141 ;; get plurality on occurrence correct
3143 (number-to-string count)
3145 (when (or (= count 0)
3149 ((string= type "custom-id")
3151 (org-open-link-from-string
3152 (format "[[#%s]]" (org-element-property :path object)))
3153 (message "%s" (org-get-heading))))
3155 ;; check if the bibliography files exist.
3156 ((string= type "bibliography")
3158 ;; object is the link you clicked on
3159 (object (org-element-context))
3160 (link-string (org-element-property :path object))
3161 (link-string-beginning)
3164 (goto-char (org-element-property :begin object))
3165 (search-forward link-string nil nil 1)
3166 (setq link-string-beginning (match-beginning 0))
3167 (setq link-string-end (match-end 0)))
3169 ;; make sure we are in link and not before the :
3170 (when (> link-string-beginning (point))
3171 (goto-char link-string-beginning))
3173 ;; now if we have comma separated bibliographies
3174 ;; we find the one clicked on. we want to
3175 ;; search forward to next comma from point
3177 (if (search-forward "," link-string-end 1 1)
3178 (setq key-end (- (match-end 0) 1)) ; we found a match
3179 (setq key-end (point)))) ; no comma found so take the point
3181 ;; and backward to previous comma from point
3183 (if (search-backward "," link-string-beginning 1 1)
3184 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
3185 (setq key-beginning (point)))) ; no match found
3186 ;; save the key we clicked on.
3188 (org-ref-strip-string
3189 (buffer-substring key-beginning key-end)))
3190 (if (file-exists-p bibfile)
3191 (message "%s exists." bibfile)
3192 (message "!!! %s NOT FOUND !!!" bibfile))))
3197 I like convenience. Here are some aliases for faster typing.
3199 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3200 (defalias 'oro 'org-ref-open-citation-at-point)
3201 (defalias 'orc 'org-ref-citation-at-point)
3202 (defalias 'orp 'org-ref-open-pdf-at-point)
3203 (defalias 'oru 'org-ref-open-url-at-point)
3204 (defalias 'orn 'org-ref-open-notes-at-point)
3205 (defalias 'ornr 'org-ref-open-notes-from-reftex)
3207 (defalias 'orib 'org-ref-insert-bibliography-link)
3208 (defalias 'oric 'org-ref-insert-cite-link)
3209 (defalias 'orir 'org-ref-insert-ref-link)
3210 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
3212 (defalias 'orcb 'org-ref-clean-bibtex-entry)
3215 [[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.
3217 1. Make the default action to insert selected keys.
3218 2. Make open entry second action
3219 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3220 (setq helm-source-bibtex
3221 '((name . "BibTeX entries")
3222 (init . helm-bibtex-init)
3223 (candidates . helm-bibtex-candidates)
3224 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3225 (action . (("Insert citation" . helm-bibtex-insert-citation)
3226 ("Show entry" . helm-bibtex-show-entry)
3227 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3228 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3229 ("Insert reference" . helm-bibtex-insert-reference)
3230 ("Insert BibTeX key" . helm-bibtex-insert-key)
3231 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3232 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3233 ("Edit notes" . helm-bibtex-edit-notes)
3237 Now, let us define a function that inserts the cite links:
3238 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3239 (defun helm-bibtex-format-org-ref (keys)
3240 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3241 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.
3243 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3245 C-u C-u will change the key at point to the selected keys.
3247 (let* ((object (org-element-context))
3248 (last-char (save-excursion
3249 (goto-char (org-element-property :end object))
3251 (if (looking-at " ")
3255 ;; case where we are in a link
3256 ((and (equal (org-element-type object) 'link)
3259 (org-element-property :type object)))
3261 ;; no prefix. append keys
3262 ((equal helm-current-prefix-arg nil)
3263 (goto-char (org-element-property :end object))
3264 (while (looking-back " ") (backward-char))
3265 (insert (concat "," (mapconcat 'identity keys ","))))
3266 ;; double prefix, replace key at point
3267 ((equal helm-current-prefix-arg '(16))
3268 (setf (buffer-substring
3269 (org-element-property :begin object)
3270 (org-element-property :end object))
3272 (replace-regexp-in-string
3273 (car (org-ref-get-bibtex-key-and-file)) ; key
3274 (mapconcat 'identity keys ",") ; new keys
3275 (org-element-property :raw-link object)
3277 ;; replace space at end to avoid collapsing into next word.
3280 (message "Not found"))))
3282 ;; We are next to a link, and we want to append
3283 ;; next to a link means one character back is on a link.
3286 (and (equal (org-element-type (org-element-context)) 'link)
3289 (org-element-property :type (org-element-context)))))
3290 (while (looking-back " ") (backward-char))
3291 (insert (concat "," (mapconcat 'identity keys ","))))
3293 ;; insert fresh link
3295 ;;(message-box "fresh link")
3297 (concat (if (equal helm-current-prefix-arg '(4))
3298 (helm :sources `((name . "link types")
3299 (candidates . ,org-ref-cite-types)
3300 (action . (lambda (x) x))))
3301 org-ref-default-citation-link)
3303 (s-join "," keys))))))
3304 ;; return empty string for helm
3307 (setq helm-bibtex-format-citation-functions
3308 '((org-mode . helm-bibtex-format-org-ref)))
3310 (defun org-ref-helm-insert-cite-link (arg)
3311 "org-ref function to use helm-bibtex to insert a citation link.
3312 With one prefix arg, insert a ref link.
3313 With two prefix args, insert a label link."
3317 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3320 (org-ref-helm-insert-ref-link))
3322 (org-ref-helm-insert-label-link))))
3324 (require 'helm-bibtex)
3326 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3327 (setq helm-bibtex-fallback-options
3328 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3330 (setq helm-bibtex-fallback-options
3333 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3334 helm-bibtex-fallback-options))
3336 (setq helm-bibtex-fallback-options
3337 (-insert-at 1 '("Open Web of Science" . (lambda () (browse-url "http://apps.webofknowledge.com")))
3338 helm-bibtex-fallback-options))
3341 ** A helm click menu
3342 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.
3343 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3344 (defun org-ref-get-citation-string-at-point ()
3345 "Get a string of a formatted citation"
3347 (let* ((results (org-ref-get-bibtex-key-and-file))
3349 (bibfile (cdr results)))
3353 (insert-file-contents bibfile)
3354 (bibtex-search-entry key)
3355 (org-ref-bib-citation)))
3356 "!!! No entry found !!!" )))
3358 (defun org-ref-cite-candidates ()
3359 "Generate the list of possible candidates for click actions on a cite link.
3360 Checks for pdf and doi, and add appropriate functions."
3362 (let* ((results (org-ref-get-bibtex-key-and-file))
3364 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3365 (bibfile (cdr results))
3366 (url (save-excursion
3368 (insert-file-contents bibfile)
3369 (bibtex-search-entry key)
3370 (bibtex-autokey-get-field "url"))))
3371 (doi (save-excursion
3373 (insert-file-contents bibfile)
3374 (bibtex-search-entry key)
3375 ;; I like this better than bibtex-url which does not always find
3377 (bibtex-autokey-get-field "doi"))))
3378 (candidates `(("Quit" . org-ref-citation-at-point)
3379 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3380 ;; for some reason, when there is no doi or url, they are returned as "". I
3381 ;; prefer nil so we correct this here.
3382 (when (string= doi "") (setq doi nil))
3383 (when (string= url "") (setq url nil))
3385 ;; Conditional pdf functions
3386 (if (file-exists-p pdf-file)
3389 '("Open pdf" . org-ref-open-pdf-at-point)
3393 '("Try to get pdf" . (lambda ()
3394 (save-window-excursion
3395 (org-ref-open-citation-at-point)
3396 (bibtex-beginning-of-entry)
3397 (doi-utils-get-bibtex-entry-pdf))))
3403 '("Open notes" . org-ref-open-notes-at-point)
3406 ;; conditional url and doi functions
3410 '("Open in browser" . org-ref-open-url-at-point)
3415 (add-to-list 'candidates x t))
3416 `(("WOS" . org-ref-wos-at-point)
3417 ("Related articles in WOS" . org-ref-wos-related-at-point)
3418 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3419 ("Google Scholar" . org-ref-google-scholar-at-point)
3420 ("Pubmed" . org-ref-pubmed-at-point)
3421 ("Crossref" . org-ref-crossref-at-point)
3426 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3431 '("Copy key to clipboard" . (lambda ()
3433 (car (org-ref-get-bibtex-key-and-file)))))
3438 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3443 '("Email bibtex entry and pdf" . (lambda ()
3445 (org-ref-open-citation-at-point)
3446 (email-bibtex-entry))))
3448 ;; finally return a numbered list of the candidates
3450 for cell in candidates
3451 collect (cons (format "%2s. %s" i (car cell))
3455 (defvar org-ref-helm-user-candidates '()
3456 "List of user-defined candidates to act when clicking on a cite link.
3457 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.
3460 ;; example of adding your own function
3462 'org-ref-helm-user-candidates
3463 '("Example" . (lambda () (message-box "You did it!")))
3466 (defun org-ref-cite-click-helm (key)
3468 1. get name and candidates before entering helm because we need the org-buffer.
3469 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer."
3471 (let ((name (org-ref-get-citation-string-at-point))
3472 (candidates (org-ref-cite-candidates))
3473 (cb (current-buffer)))
3475 (helm :sources `(((name . ,name)
3476 (candidates . ,candidates)
3477 (action . (lambda (f)
3478 (switch-to-buffer cb)
3480 ((name . "User functions")
3481 (candidates . ,org-ref-helm-user-candidates)
3482 (action . (lambda (f)
3483 (switch-to-buffer cb)
3489 : org-ref-cite-click-helm
3492 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3497 This code will tangle the elisp code out to org-ref.el and load it.
3499 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
3501 Alternatively you may use:
3503 [[elisp:(org-babel-load-file "org-ref.org")]]