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
16 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
17 ;;; org-ref.el --- setup bibliography, cite, ref and label org-mode links.
19 ;; Copyright(C) 2014 John Kitchin
21 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
22 ;; This file is not currently part of GNU Emacs.
24 ;; This program is free software; you can redistribute it and/or
25 ;; modify it under the terms of the GNU General Public License as
26 ;; published by the Free Software Foundation; either version 2, or (at
27 ;; your option) any later version.
29 ;; This program is distributed in the hope that it will be useful, but
30 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
31 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
32 ;; General Public License for more details.
34 ;; You should have received a copy of the GNU General Public License
35 ;; along with this program ; see the file COPYING. If not, write to
36 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
37 ;; Boston, MA 02111-1307, USA.
41 ;; Lisp code to setup bibliography cite, ref and label org-mode links. also
42 ;; sets up reftex and helm for org-mode citations. The links are clickable and
43 ;; do things that are useful. You should really read org-ref.org for details.
45 ;; Package-Requires: ((dash) (helm) (helm-bibtex))
49 The only external require is reftex-cite
51 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
52 (require 'reftex-cite)
55 (require 'helm-bibtex)
59 There are some variables needed later to tell this library where you store your pdf files, where your notes file is, and your default bibliography. This variable is similar to the reftex-default-bibliography. I do not remember why I made it separate.
61 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
63 "customization group for org-ref")
65 (defcustom org-ref-bibliography-notes
67 "filename to where you will put all your notes about an entry in
68 the default bibliography."
72 (defcustom org-ref-default-bibliography
74 "list of bibtex files to search for. You should use full-paths for each file."
75 :type '(repeat :tag "List of bibtex files" file)
78 (defcustom org-ref-pdf-directory
80 "directory where pdfs are stored by key. put a trailing / in"
84 (defcustom org-ref-default-citation-link
86 "The default type of citation link to use"
90 (defcustom org-ref-insert-cite-key
92 "Keyboard shortcut to insert a citation."
96 (defcustom org-ref-bibliography-entry-format
97 '(("article" . "%a, %t, <i>%j</i>, <b>%v(%n)</b>, %p (%y). <a href=\"%U\">link</a>. <a href=\"http://dx.doi.org/%D\">doi</a>.")
99 ("book" . "%a, %t, %u (%y).")
101 ("proceedings" . "%e, %t in %S, %u (%y).")
103 ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
105 "string to format an entry. Just the reference, no numbering at the beginning, etc... see the `org-ref-reftex-format-citation' docstring for the escape codes."
109 (defcustom org-ref-open-notes-function
115 ;;(org-tree-to-indirect-buffer)
116 (outline-previous-visible-heading 1)
117 (recenter-top-bottom 0))
118 "User-defined way to open a notes entry. This is excecuted after the entry is found, with the cursor at the beginning of the headline. The default setting fully expands the notes, and moves the headline to the top of the buffer"
123 (defcustom org-ref-open-pdf-function
124 'org-ref-open-pdf-at-point
125 "User-defined function to open a pdf from a link. The function must get the key at point, and derive a path to the pdf file, then open it. The default function is `org-ref-open-pdf-at-point'."
130 (defcustom org-ref-insert-cite-function
131 'org-ref-helm-insert-cite-link
132 "Function to call to insert citation links. The default is `org-ref-helm-insert-cite-link' which uses `helm-bibtex'. org-ref modifies helm-bibtex a little bit to give org-mode citations, and to reorder default actions. You may use `org-ref-insert-cite-link' if you like the reftex interface."
137 (defcustom org-ref-cite-onclick-function
138 'org-ref-cite-click-helm
139 "Function that runs when you click on a cite link. The function must take no arguments. You may also use `org-ref-cite-onclick-minibuffer-menu' if you do not like helm."
143 (defcustom org-ref-show-citation-on-enter t
144 "If non-nil add a hook function to show the citation summary in
145 the minibuffer just by putting the cursor in a link"
150 This next variable determines the citation types that are available in org-ref. Links for each one are automatically generated, and completion functions are automatically generated. Users may add to this list in their own init files.
152 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
153 (defcustom org-ref-cite-types
154 '("cite" "nocite" ;; the default latex cite commands
155 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
156 "citet" "citet*" "citep" "citep*"
157 "citealt" "citealt*" "citealp" "citealp*"
159 "citeauthor" "citeauthor*"
160 "citeyear" "citeyear*"
161 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
163 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
165 "parencite" "Parencite"
166 "footcite" "footcitetext"
167 "textcite" "Textcite"
168 "smartcite" "Smartcite"
169 "cite*" "parencite*" "supercite"
170 "autocite" "Autocite" "autocite*" "Autocite*"
172 "citetitle" "citetitle*"
173 "citedate" "citedate*"
175 "fullcite" "footfullcite"
176 ;; "volcite" "Volcite" cannot support the syntax
177 "notecite" "Notecite"
178 "pnotecite" "Pnotecite"
180 ;; multicites. Very limited support for these.
181 "cites" "Cites" "parencites" "Parencites"
182 "footcites" "footcitetexts"
183 "smartcites" "Smartcites" "textcites" "Textcites"
184 "supercites" "autocites" "Autocites"
185 ;; for the bibentry package
188 "List of citation types known in org-ref"
189 :type '(repeat :tag "List of citation types" string)
193 We need a hook variable to store user-defined bibtex entry cleaning functions
194 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
195 (defcustom org-ref-clean-bibtex-entry-hook nil
196 "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
202 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
203 (defvar org-ref-bibliography-files
205 "variable to hold bibliography files to be searched")
208 ** org-mode / reftex setup
210 We setup reftex here. We use a custom insert cite link function defined here: [[*org-ref-insert-cite-link][org-ref-insert-cite-link]]. We setup reftex to use our org citation format.
212 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
214 (defun org-mode-reftex-setup ()
215 (and (buffer-file-name)
216 (file-exists-p (buffer-file-name))
217 (global-auto-revert-mode t)
218 ;; I do not remember why I put this next line in. It doesn't
219 ;; work for org-files. Nothing very bad happens, but it gives
220 ;; an annoying error. Commenting it out for now.
223 (make-local-variable 'reftex-cite-format)
224 (setq reftex-cite-format 'org))
226 ;; define key for inserting citations
227 (define-key org-mode-map
228 (kbd org-ref-insert-cite-key)
229 org-ref-insert-cite-function)
231 (when org-ref-show-citation-on-enter
232 (setq org-ref-message-timer
233 (run-with-idle-timer 0.5 t 'org-ref-link-message)))
235 (defun org-ref-show-link-messages ()
236 "Turn on link messages. You will see a message in the
237 minibuffer when on a cite, ref or label link."
239 (setq org-ref-message-timer
240 (run-with-idle-timer 0.5 t 'org-ref-link-message))
242 (defun org-ref-cancel-link-messages ()
243 "Stop showing messages in minibuffer when on a link."
245 (cancel-timer org-ref-message-timer))
247 ;; this approach caused the selected region to not be highlighted any more.
248 ; (add-hook 'post-command-hook 'org-ref-link-message))
249 ; (remove-hook 'post-command-hook 'org-ref-link-message))
251 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
253 (eval-after-load 'reftex-vars
255 (add-to-list 'reftex-cite-format-builtin
256 '(org "Org-mode citation"
257 ((?\C-m . "cite:%l") ; default
258 (?d . ",%l") ; for appending
264 (?h . "citeauthor:%l")
265 (?H . "citeauthor*:%l")
272 You may want to add new formats to the reftex-cite-format-builtin variable. Here is an example of adding two new formats. Note that this does not create the links.
274 #+BEGIN_SRC emacs-lisp :tangle no
276 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
277 (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l")
278 (?z . "newcite:%l"))))
281 You can define a new citation link like this:
282 #+BEGIN_SRC emacs-lisp :tangle no
283 (org-ref-define-citation-link "citez" ?z)
287 Most of this library is the creation of functional links to help with references and citations.
289 We need several general utilities for this module. They are organized here. We frequently need to remove white space from the front and back of a string. Here we do that for a string.
291 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
292 (defun org-ref-strip-string (string)
293 "strip leading and trailing whitespace from the string"
294 (replace-regexp-in-string
295 (concat search-whitespace-regexp "$" ) ""
296 (replace-regexp-in-string
297 (concat "^" search-whitespace-regexp ) "" string)))
300 It is helpful to make the previous function operate on a list of strings here.
302 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
303 (defun org-ref-split-and-strip-string (string)
304 "split key-string and strip keys. Assumes the key-string is comma delimited"
305 (mapcar 'org-ref-strip-string (split-string string ",")))
308 ** bibliography and bibliographystyle
309 *** An html bibliography
311 Reftex is no longer being developed. I want a url and doi option for formatting, so I am modifying this [[file:emacs-24.3/lisp/textmodes/reftex-cite.el::(defun%20reftex-format-citation%20(entry%20format)][function]] from reftex-cite to provide that. We need to modify the reftex-get-bib-field code a bit to remove enclosing braces and quotes so we can make nice looking links.
313 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
314 (defun org-ref-reftex-get-bib-field (field entry &optional format)
315 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
317 (setq result (reftex-get-bib-field field entry format))
318 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
319 (setq result (substring result 1 -1)))
320 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
321 (setq result (substring result 1 -1)))
324 (defun org-ref-reftex-format-citation (entry format)
325 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
326 to the format argument. The format is a string with these percent escapes.
328 In the format, the following percent escapes will be expanded.
330 %l The BibTeX label of the citation.
331 %a List of author names, see also `reftex-cite-punctuation'.
332 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
333 %A First author name only.
334 %e Works like %a, but on list of editor names. (%2e and %E work a well)
336 It is also possible to access all other BibTeX database fields:
337 %b booktitle %c chapter %d edition %h howpublished
338 %i institution %j journal %k key %m month
339 %n number %o organization %p pages %P first page
340 %r address %s school %u publisher %t title
342 %B booktitle, abbreviated %T title, abbreviated
347 Usually, only %l is needed. The other stuff is mainly for the echo area
348 display, and for (setq reftex-comment-citations t).
350 %< as a special operator kills punctuation and space around it after the
351 string has been formatted.
353 A pair of square brackets indicates an optional argument, and RefTeX
354 will prompt for the values of these arguments.
356 Beware that all this only works with BibTeX database files. When
357 citations are made from the \bibitems in an explicit thebibliography
358 environment, only %l is available."
359 ;; Format a citation from the info in the BibTeX ENTRY
361 (unless (stringp format) (setq format "\\cite{%l}"))
363 (if (and reftex-comment-citations
364 (string-match "%l" reftex-cite-comment-format))
365 (error "reftex-cite-comment-format contains invalid %%l"))
368 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
370 (let ((n (string-to-number (match-string 4 format)))
371 (l (string-to-char (match-string 5 format)))
377 (org-ref-reftex-get-bib-field "&key" entry)
378 (if reftex-comment-citations
379 reftex-cite-comment-format
381 ((= l ?a) (reftex-format-names
382 (reftex-get-bib-names "author" entry)
384 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
385 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
386 ((= l ?B) (reftex-abbreviate-title
387 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
388 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
389 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
390 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
391 ((= l ?e) (reftex-format-names
392 (reftex-get-bib-names "editor" entry)
394 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
395 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
396 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
397 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
398 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
399 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
400 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
401 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
402 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
403 ((= l ?P) (car (split-string
404 (org-ref-reftex-get-bib-field "pages" entry)
406 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
407 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
408 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
409 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
410 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
411 ;; strip enclosing brackets from title if they are there
412 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
413 ((= l ?T) (reftex-abbreviate-title
414 (org-ref-reftex-get-bib-field "title" entry)))
415 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
416 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
419 (setq b (match-beginning 2) e (match-end 2))
420 (setq b (match-beginning 3) e (match-end 3)))
421 (setq format (concat (substring format 0 b) rpl (substring format e)))))
422 (while (string-match "%%" format)
423 (setq format (replace-match "%" t t format)))
424 (while (string-match "[ ,.;:]*%<" format)
425 (setq format (replace-match "" t t format)))
426 ;; also replace carriage returns, tabs, and multiple whitespaces
427 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
430 (defun org-ref-get-bibtex-entry-citation (key)
431 "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
433 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
434 (file) (entry) (bibtex-entry) (entry-type) (format))
436 (setq file (catch 'result
437 (loop for file in org-ref-bibliography-files do
438 (if (org-ref-key-in-file-p key (file-truename file))
440 (message "%s not found in %s" key (file-truename file))))))
443 (insert-file-contents file)
444 (bibtex-search-entry key nil 0)
445 (setq bibtex-entry (bibtex-parse-entry))
446 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
447 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
449 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
451 (bibtex-narrow-to-entry)
452 (setq entry (buffer-string)))))
457 : org-ref-reftex-format-citation
459 Here is how to use the function. You call it with point in an entry in a bibtex file.
461 #+BEGIN_SRC emacs-lisp :tangle no
462 (let((org-ref-bibliography-entry-format "%a, %t, <i>%j</i>, <b>%v(%n)</b>, %p (%y). <a href=\"%U\">link</a>. <a href=\"http://dx.doi.org/%D\">doi</a>."))
463 (org-ref-get-bibtex-entry-citation "armiento-2014-high"))
466 : Armiento, Kozinsky, Hautier, , Fornari \& Ceder, High-throughput screening of perovskite alloys for piezoelectric performance and thermodynamic stability, <i>Phys. Rev. B</i>, <b>89()</b>, 134103 (2014). <a href="http://link.aps.org/doi/10.1103/PhysRevB.89.134103">link</a>. <a href="http://dx.doi.org/10.1103/PhysRevB.89.134103">doi</a>.
468 I am not sure why full author names are not used.
470 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
472 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
473 (defun org-ref-get-bibtex-keys ()
474 "return a list of unique keys in the buffer."
476 (org-element-map (org-element-parse-buffer) 'link
478 (let ((plist (nth 1 link)))
479 (when (-contains? org-ref-cite-types (plist-get plist ':type))
482 (org-ref-split-and-strip-string (plist-get plist ':path)))
483 (when (not (-contains? keys key))
484 (setq keys (append keys (list key)))))))))
485 ;; Sort keys alphabetically
486 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
490 This function gets the html for one entry.
492 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
493 (defun org-ref-get-bibtex-entry-html (key)
494 "returns an html string for the bibliography entry corresponding to key"
496 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
499 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
501 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
502 (defun org-ref-get-html-bibliography ()
503 "Create an html bibliography when there are keys"
504 (let ((keys (org-ref-get-bibtex-keys)))
506 (concat "<h1>Bibliography</h1>
508 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
512 I do not have plans to make a numbered bibliography with numbered citations anytime soon. This will require changing the way the citation links are exported, and keeping track of the numbers.
514 *** An org bibliography
515 You can export an org-file to an org-file or org-buffer (org-org-epxort-as-org). In this case, it would be useful convert the cite links to links to custom_ids, and the bibliography link to a first-level heading Bibliography with org-bibtex like headings for each entry. This code should enable this. Right now, it does not appear to work for org export though.
517 First, we get the string for a single entry.
518 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
519 (defun org-ref-get-bibtex-entry-org (key)
520 "returns an org string for the bibliography entry corresponding to key"
521 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
522 (file) (entry) (bibtex-entry) (entry-type) (format))
524 (setq file (catch 'result
525 (loop for file in org-ref-bibliography-files do
526 (if (org-ref-key-in-file-p key (file-truename file))
528 (message "%s not found in %s" key (file-truename file))))))
531 (insert-file-contents file)
532 (bibtex-search-entry key nil 0)
533 (setq entry (bibtex-parse-entry))
538 " (org-ref-reftex-get-bib-field "author" entry)
539 (org-ref-reftex-get-bib-field "title" entry)
540 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
541 (mapconcat (lambda (element) (format " :%s: %s"
542 (upcase (car element))
548 Now, we loop over the keys, and combine all the entries into a bibliography.
549 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
550 (defun org-ref-get-org-bibliography ()
551 "Create an org bibliography when there are keys"
552 (let ((keys (org-ref-get-bibtex-keys)))
554 (concat "* Bibliography
556 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
560 *** An ascii bibliography
562 This function gets the html for one entry.
564 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
565 (defun org-ref-get-bibtex-entry-ascii (key)
566 "returns an ascii string for the bibliography entry corresponding to key"
568 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
571 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
573 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
574 (defun org-ref-get-ascii-bibliography ()
575 "Create an html bibliography when there are keys"
576 (let ((keys (org-ref-get-bibtex-keys)))
582 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
588 We use a link for the bibliography so that we can click on it to open the bibliography file. The link may have more than one bibliography file in it, separated by commas. Clicking opens the file under the cursor. The bibliographies should be full filenames with the bib extension. Clicking on this link makes reftex-default-bibliography local and sets it to the list of files in the link. We need this to use reftex's searching capability.
590 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
591 (org-add-link-type "bibliography"
592 ;; this code is run on clicking. The bibliography
593 ;; may contain multiple files. this code finds the
594 ;; one you clicked on and opens it.
595 (lambda (link-string)
596 ;; get link-string boundaries
597 ;; we have to go to the beginning of the line, and then search forward
600 ;; object is the link you clicked on
601 (object (org-element-context))
603 (link-string-beginning)
607 (goto-char (org-element-property :begin object))
608 (search-forward link-string nil nil 1)
609 (setq link-string-beginning (match-beginning 0))
610 (setq link-string-end (match-end 0)))
612 ;; We set the reftex-default-bibliography
613 ;; here. it should be a local variable only in
614 ;; the current buffer. We need this for using
615 ;; reftex to do citations.
616 (set (make-local-variable 'reftex-default-bibliography)
617 (split-string (org-element-property :path object) ","))
619 ;; now if we have comma separated bibliographies
620 ;; we find the one clicked on. we want to
621 ;; search forward to next comma from point
623 (if (search-forward "," link-string-end 1 1)
624 (setq key-end (- (match-end 0) 1)) ; we found a match
625 (setq key-end (point)))) ; no comma found so take the point
626 ;; and backward to previous comma from point
628 (if (search-backward "," link-string-beginning 1 1)
629 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
630 (setq key-beginning (point)))) ; no match found
631 ;; save the key we clicked on.
632 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
633 (find-file bibfile))) ; open file on click
636 (lambda (keyword desc format)
638 ((eq format 'org) (org-ref-get-org-bibliography))
639 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
640 ((eq format 'html) (org-ref-get-html-bibliography))
642 ;; write out the latex bibliography command
643 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
644 (mapcar 'expand-file-name
645 (split-string keyword ","))
650 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.
653 \input{project-description.bbl}
656 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.
658 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
659 (org-add-link-type "nobibliography"
660 ;; this code is run on clicking. The bibliography
661 ;; may contain multiple files. this code finds the
662 ;; one you clicked on and opens it.
663 (lambda (link-string)
664 ;; get link-string boundaries
665 ;; we have to go to the beginning of the line, and then search forward
668 ;; object is the link you clicked on
669 (object (org-element-context))
671 (link-string-beginning)
675 (goto-char (org-element-property :begin object))
676 (search-forward link-string nil nil 1)
677 (setq link-string-beginning (match-beginning 0))
678 (setq link-string-end (match-end 0)))
680 ;; We set the reftex-default-bibliography
681 ;; here. it should be a local variable only in
682 ;; the current buffer. We need this for using
683 ;; reftex to do citations.
684 (set (make-local-variable 'reftex-default-bibliography)
685 (split-string (org-element-property :path object) ","))
687 ;; now if we have comma separated bibliographies
688 ;; we find the one clicked on. we want to
689 ;; search forward to next comma from point
691 (if (search-forward "," link-string-end 1 1)
692 (setq key-end (- (match-end 0) 1)) ; we found a match
693 (setq key-end (point)))) ; no comma found so take the point
694 ;; and backward to previous comma from point
696 (if (search-backward "," link-string-beginning 1 1)
697 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
698 (setq key-beginning (point)))) ; no match found
699 ;; save the key we clicked on.
700 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
701 (find-file bibfile))) ; open file on click
704 (lambda (keyword desc format)
706 ((eq format 'org) (org-ref-get-org-bibliography))
707 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
708 ((eq format 'html) (org-ref-get-html-bibliography))
710 ;; write out the latex bibliography command
712 ; (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
713 ; (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
714 ; (mapcar 'expand-file-name
715 ; (split-string keyword ","))
718 (format "\\nobibliography{%s}"
719 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
720 (mapcar 'expand-file-name
721 (split-string keyword ","))
727 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
728 (org-add-link-type "printbibliography"
729 (lambda (arg) (message "Nothing implemented for clicking here."))
730 (lambda (keyword desc format)
732 ((eq format 'org) (org-ref-get-org-bibliography))
733 ((eq format 'html) (org-ref-get-html-bibliography))
735 ;; write out the biblatex bibliography command
736 "\\printbibliography"))
740 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, ...
742 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
743 (org-add-link-type "bibliographystyle"
744 (lambda (arg) (message "Nothing implemented for clicking here."))
745 (lambda (keyword desc format)
748 ;; write out the latex bibliography command
749 (format "\\bibliographystyle{%s}" keyword)))))
752 *** Completion for bibliography link
755 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
756 (defun org-bibliography-complete-link (&optional arg)
757 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
759 (defun org-ref-insert-bibliography-link ()
760 "insert a bibliography with completion"
762 (insert (org-bibliography-complete-link)))
766 This is apparently used for biblatex.
767 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
768 (org-add-link-type "addbibresource"
769 ;; this code is run on clicking. The addbibresource
770 ;; may contain multiple files. this code finds the
771 ;; one you clicked on and opens it.
772 (lambda (link-string)
773 ;; get link-string boundaries
774 ;; we have to go to the beginning of the line, and then search forward
777 ;; object is the link you clicked on
778 (object (org-element-context))
780 (link-string-beginning)
784 (goto-char (org-element-property :begin object))
785 (search-forward link-string nil nil 1)
786 (setq link-string-beginning (match-beginning 0))
787 (setq link-string-end (match-end 0)))
789 ;; We set the reftex-default-addbibresource
790 ;; here. it should be a local variable only in
791 ;; the current buffer. We need this for using
792 ;; reftex to do citations.
793 (set (make-local-variable 'reftex-default-addbibresource)
794 (split-string (org-element-property :path object) ","))
796 ;; now if we have comma separated bibliographies
797 ;; we find the one clicked on. we want to
798 ;; search forward to next comma from point
800 (if (search-forward "," link-string-end 1 1)
801 (setq key-end (- (match-end 0) 1)) ; we found a match
802 (setq key-end (point)))) ; no comma found so take the point
803 ;; and backward to previous comma from point
805 (if (search-backward "," link-string-beginning 1 1)
806 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
807 (setq key-beginning (point)))) ; no match found
808 ;; save the key we clicked on.
809 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
810 (find-file bibfile))) ; open file on click
813 (lambda (keyword desc format)
815 ((eq format 'html) (format "")); no output for html
817 ;; write out the latex addbibresource command
818 (format "\\addbibresource{%s}" keyword)))))
823 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.
825 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
826 (defun org-ref-list-of-figures (&optional arg)
827 "Generate buffer with list of figures in them"
829 (save-excursion (widen)
830 (let* ((c-b (buffer-name))
833 (org-element-map (org-element-parse-buffer) 'link
835 "create a link for to the figure"
837 (and (string= (org-element-property :type link) "file")
839 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
840 (org-element-property :path link)))
843 (let* ((start (org-element-property :begin link))
844 (parent (car (cdr (org-element-property :parent link))))
845 (caption (caaar (plist-get parent :caption)))
846 (name (plist-get parent :name)))
849 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
850 c-b start counter (or name "") caption)
852 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
853 c-b start counter (or name "")))))))))
854 (switch-to-buffer "*List of Figures*")
855 (setq buffer-read-only nil)
858 (insert (mapconcat 'identity list-of-figures ""))
859 (setq buffer-read-only t)
860 (use-local-map (copy-keymap org-mode-map))
861 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
865 'org-ref-list-of-figures ; on click
866 (lambda (keyword desc format)
869 (format "\\listoffigures")))))
874 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
875 (defun org-ref-list-of-tables (&optional arg)
876 "Generate a buffer with a list of tables"
880 (let* ((c-b (buffer-name))
883 (org-element-map (org-element-parse-buffer 'element) 'table
885 "create a link for to the table"
887 (let ((start (org-element-property :begin table))
888 (name (org-element-property :name table))
889 (caption (caaar (org-element-property :caption table))))
892 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
893 c-b start counter (or name "") caption)
895 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
896 c-b start counter (or name ""))))))))
897 (switch-to-buffer "*List of Tables*")
898 (setq buffer-read-only nil)
901 (insert (mapconcat 'identity list-of-tables ""))
902 (setq buffer-read-only t)
903 (use-local-map (copy-keymap org-mode-map))
904 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
908 'org-ref-list-of-tables
909 (lambda (keyword desc format)
912 (format "\\listoftables")))))
916 The label link provides a way to create labels in org-mode. We make it clickable because we want to make sure labels are unique. This code will tell you how many instances of a label are found. We search for label links, LaTeX labels, and the org-mode format for labels. We probably should search for tblnames too.
917 *************** TODO search tblnames, custom_ids and check for case sensitivity
920 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
922 (defun org-ref-count-labels (label)
923 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
924 ;; for tblname, it is not enough to get word boundary
925 ;; tab-little and tab-little-2 match then.
926 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
927 (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
928 ;; this is the org-format #+label:
929 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))
934 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
935 (message (format "%s occurences" (org-ref-count-labels label))))
936 (lambda (keyword desc format)
938 ((eq format 'html) (format "(<label>%s</label>)" path))
940 (format "\\label{%s}" keyword)))))
943 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.
945 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
946 (defun org-label-store-link ()
947 "store a link to a label. The output will be a ref to that label"
948 ;; First we have to make sure we are on a label link.
949 (let* ((object (org-element-context)))
950 (when (and (equal (org-element-type object) 'link)
951 (equal (org-element-property :type object) "label"))
952 (org-store-link-props
954 :link (concat "ref:" (org-element-property :path object))))
956 ;; Store link on table
957 (when (equal (org-element-type object) 'table)
958 (org-store-link-props
960 :link (concat "ref:" (org-element-property :name object))))
962 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
963 ;; store link on heading with custom_id
964 ; (when (and (equal (org-element-type object) 'headline)
965 ; (org-entry-get (point) "CUSTOM_ID"))
966 ; (org-store-link-props
968 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
970 ;; and to #+label: lines
971 (when (and (equal (org-element-type object) 'paragraph)
972 (org-element-property :name object))
973 (org-store-link-props
975 :link (concat "ref:" (org-element-property :name object))))
978 (add-hook 'org-store-link-functions 'org-label-store-link)
982 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.
984 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
986 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
990 "on clicking goto the label. Navigate back with C-c &"
992 ;; next search from beginning of the buffer
994 ;; it is possible you would not find the label if narrowing is in effect
1001 (goto-char (point-min))
1002 (re-search-forward (format "label:%s\\b" label) nil t))
1006 (goto-char (point-min))
1007 (re-search-forward (format "\\label{%s}" label) nil t))
1009 ;; #+label: name org-definition
1011 (goto-char (point-min))
1012 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1016 (goto-char (point-min))
1017 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1019 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1020 ;; you need [[#label]] links.
1023 ; (goto-char (point-min))
1024 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1026 ;; we did not find anything, so go back to where we came
1027 (org-mark-ring-goto)
1028 (error "%s not found" label))
1030 (message "go back with (org-mark-ring-goto) `C-c &`"))
1032 (lambda (keyword desc format)
1034 ((eq format 'html) (format "(<ref>%s</ref>)" path))
1036 (format "\\ref{%s}" keyword)))))
1039 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.
1041 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1042 (defun org-ref-get-org-labels ()
1043 "find #+LABEL: labels"
1045 (goto-char (point-min))
1046 (let ((matches '()))
1047 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1048 (add-to-list 'matches (match-string-no-properties 1) t))
1052 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1053 (defun org-ref-get-custom-ids ()
1054 "return a list of custom_id properties in the buffer"
1055 (let ((results '()) custom_id)
1058 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1059 (when (not (null custom_id))
1060 (setq results (append results (list custom_id)))))))
1064 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
1065 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1066 (defun org-ref-get-latex-labels ()
1068 (goto-char (point-min))
1069 (let ((matches '()))
1070 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1071 (add-to-list 'matches (match-string-no-properties 1) t))
1075 Finally, we get the table names.
1077 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1078 (defun org-ref-get-tblnames ()
1079 (org-element-map (org-element-parse-buffer 'element) 'table
1081 (org-element-property :name table))))
1084 Now, we can put all the labels together which will give us a list of candidates.
1086 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1087 (defun org-ref-get-labels ()
1088 "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
1092 (goto-char (point-min))
1093 (let ((matches '()))
1094 (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1095 (add-to-list 'matches (match-string-no-properties 1) t))
1096 (append matches (org-ref-get-org-labels) (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
1099 Now we create the completion function. This works from the org-machinery, e.g. if you type C-c C-l to insert a link, and use completion by pressing tab.
1101 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1102 (defun org-ref-complete-link (&optional arg)
1103 "Completion function for ref links"
1105 (setq label (completing-read "label: " (org-ref-get-labels)))
1106 (format "ref:%s" label)))
1109 Alternatively, you may want to just call a function that inserts a link with completion:
1111 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1112 (defun org-ref-insert-ref-link ()
1114 (insert (org-ref-complete-link)))
1119 This refers to the page of a label in LaTeX.
1121 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1125 "on clicking goto the label. Navigate back with C-c &"
1126 (org-mark-ring-push)
1127 ;; next search from beginning of the buffer
1133 (goto-char (point-min))
1134 (re-search-forward (format "label:%s\\b" label) nil t))
1138 (goto-char (point-min))
1139 (re-search-forward (format "\\label{%s}" label) nil t))
1141 ;; #+label: name org-definition
1143 (goto-char (point-min))
1144 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1148 (goto-char (point-min))
1149 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1151 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1152 ;; you need [[#label]] links.
1155 ; (goto-char (point-min))
1156 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1158 ;; we did not find anything, so go back to where we came
1159 (org-mark-ring-goto)
1160 (error "%s not found" label))
1161 (message "go back with (org-mark-ring-goto) `C-c &`"))
1163 (lambda (keyword desc format)
1165 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1167 (format "\\pageref{%s}" keyword)))))
1170 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1171 (defun org-pageref-complete-link (&optional arg)
1172 "Completion function for ref links"
1174 (setq label (completing-read "label: " (org-ref-get-labels)))
1175 (format "ref:%s" label)))
1178 Alternatively, you may want to just call a function that inserts a link with completion:
1180 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1181 (defun org-pageref-insert-ref-link ()
1183 (insert (org-pageref-complete-link)))
1188 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.
1190 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1194 "on clicking goto the label. Navigate back with C-c &"
1195 (org-mark-ring-push)
1196 ;; next search from beginning of the buffer
1202 (goto-char (point-min))
1203 (re-search-forward (format "\\label{%s}" label) nil t))
1205 ;; we did not find anything, so go back to where we came
1206 (org-mark-ring-goto)
1207 (error "%s not found" label))
1208 (message "go back with (org-mark-ring-goto) `C-c &`"))
1210 (lambda (keyword desc format)
1212 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1214 (format "\\nameref{%s}" keyword)))))
1218 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1220 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1224 "on clicking goto the label. Navigate back with C-c &"
1225 (org-mark-ring-push)
1226 ;; next search from beginning of the buffer
1228 (goto-char (point-min))
1231 ;; search forward for the first match
1233 (re-search-forward (format "label:%s" label) nil t)
1235 (re-search-forward (format "\\label{%s}" label) nil t)
1236 ;; #+label: name org-definition
1237 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1238 (org-mark-ring-goto)
1239 (error "%s not found" label))
1240 (message "go back with (org-mark-ring-goto) `C-c &`"))
1242 (lambda (keyword desc format)
1244 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1246 (format "\\eqref{%s}" keyword)))))
1250 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.
1252 *** Implementing the click actions of cite
1254 **** Getting the key we clicked on
1255 The first thing we need is to get the bibtex key we clicked on.
1257 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1258 (defun org-ref-get-bibtex-key-under-cursor ()
1259 "returns key under the bibtex cursor. We search forward from
1260 point to get a comma, or the end of the link, and then backwards
1261 to get a comma, or the beginning of the link. that delimits the
1262 keyword we clicked on. We also strip the text properties."
1264 (let* ((object (org-element-context))
1265 (link-string (org-element-property :path object)))
1266 ;; you may click on the part before the citations. here we make
1267 ;; sure to move to the beginning so you get the first citation.
1269 (goto-char (org-element-property :begin object))
1270 (search-forward link-string (org-element-property :end object))
1271 (goto-char (match-beginning 0))
1272 ;; check if we clicked before the path and move as needed.
1273 (unless (< cp (point))
1276 (if (not (org-element-property :contents-begin object))
1277 ;; this means no description in the link
1279 ;; we need the link path start and end
1281 (goto-char (org-element-property :begin object))
1282 (search-forward link-string nil nil 1)
1283 (setq link-string-beginning (match-beginning 0))
1284 (setq link-string-end (match-end 0)))
1286 ;; The key is the text between commas, or the link boundaries
1288 (if (search-forward "," link-string-end t 1)
1289 (setq key-end (- (match-end 0) 1)) ; we found a match
1290 (setq key-end link-string-end))) ; no comma found so take the end
1291 ;; and backward to previous comma from point which defines the start character
1293 (if (search-backward "," link-string-beginning 1 1)
1294 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1295 (setq key-beginning link-string-beginning))) ; no match found
1296 ;; save the key we clicked on.
1297 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1298 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1300 ;; link with description. assume only one key
1304 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.
1306 **** Getting the bibliographies
1307 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1308 (defun org-ref-find-bibliography ()
1309 "find the bibliography in the buffer.
1310 This function sets and returns cite-bibliography-files, which is a list of files
1311 either from bibliography:f1.bib,f2.bib
1312 \bibliography{f1,f2}
1313 internal bibliographies
1315 falling back to what the user has set in org-ref-default-bibliography
1320 (goto-char (point-min))
1321 ;; look for a bibliography link
1322 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1323 (setq org-ref-bibliography-files
1324 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1325 (throw 'result org-ref-bibliography-files))
1328 ;; we did not find a bibliography link. now look for \bibliography
1329 (goto-char (point-min))
1330 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1331 ;; split, and add .bib to each file
1332 (setq org-ref-bibliography-files
1333 (mapcar (lambda (x) (concat x ".bib"))
1334 (mapcar 'org-ref-strip-string
1335 (split-string (match-string 1) ","))))
1336 (throw 'result org-ref-bibliography-files))
1338 ;; no bibliography found. maybe we need a biblatex addbibresource
1339 (goto-char (point-min))
1340 ;; look for a bibliography link
1341 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1342 (setq org-ref-bibliography-files
1343 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1344 (throw 'result org-ref-bibliography-files))
1346 ;; we did not find anything. use defaults
1347 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1349 ;; set reftex-default-bibliography so we can search
1350 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1351 org-ref-bibliography-files)
1354 **** Finding the bibliography file a key is in
1355 Now, we can see if an entry is in a file.
1357 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1358 (defun org-ref-key-in-file-p (key filename)
1359 "determine if the key is in the file"
1360 (interactive "skey: \nsFile: ")
1361 (save-current-buffer
1362 (let ((bibtex-files (list filename)))
1363 (bibtex-search-entry key t))))
1366 Finally, we want to know which file the key is in.
1368 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1369 (defun org-ref-get-bibtex-key-and-file (&optional key)
1370 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1372 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1375 (setq key (org-ref-get-bibtex-key-under-cursor)))
1376 (setq file (catch 'result
1377 (loop for file in org-ref-bibliography-files do
1378 (if (org-ref-key-in-file-p key (file-truename file))
1379 (throw 'result file)))))
1383 **** convenience functions to act on citation at point
1385 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1387 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.
1389 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1390 (defun org-ref-open-pdf-at-point ()
1391 "open the pdf for bibtex key under point if it exists"
1393 (let* ((results (org-ref-get-bibtex-key-and-file))
1395 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1396 (if (file-exists-p pdf-file)
1397 (org-open-file pdf-file)
1398 (message "no pdf found for %s" key))))
1401 (defun org-ref-open-url-at-point ()
1402 "open the url for bibtex key under point."
1404 (let* ((results (org-ref-get-bibtex-key-and-file))
1406 (bibfile (cdr results)))
1409 (insert-file-contents bibfile)
1410 (bibtex-search-entry key)
1411 ;; I like this better than bibtex-url which does not always find
1414 (let ((url (bibtex-autokey-get-field "url")))
1419 (let ((doi (bibtex-autokey-get-field "doi")))
1421 (if (string-match "^http" doi)
1423 (browse-url (format "http://dx.doi.org/%s" doi)))
1424 (throw 'done nil))))))))
1427 (defun org-ref-open-notes-at-point ()
1428 "open the notes for bibtex key under point."
1430 (let* ((results (org-ref-get-bibtex-key-and-file))
1432 (bibfile (cdr results)))
1435 (insert-file-contents bibfile)
1436 (bibtex-search-entry key)
1437 (org-ref-open-bibtex-notes)))))
1440 (defun org-ref-citation-at-point ()
1441 "give message of current citation at point"
1443 (let* ((cb (current-buffer))
1444 (results (org-ref-get-bibtex-key-and-file))
1446 (bibfile (cdr results)))
1447 (message "%s" (progn
1449 (insert-file-contents bibfile)
1450 (bibtex-search-entry key)
1451 (org-ref-bib-citation))))))
1454 (defun org-ref-open-citation-at-point ()
1455 "open bibtex file to key at point"
1457 (let* ((cb (current-buffer))
1458 (results (org-ref-get-bibtex-key-and-file))
1460 (bibfile (cdr results)))
1462 (bibtex-search-entry key)))
1465 **** the actual minibuffer menu
1466 Now, we create the menu. This is a rewrite of the cite action. This makes the function extendable by users.
1468 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1469 (defvar org-ref-cite-menu-funcs '()
1470 "Functions to run on cite click menu. Each entry is a list of (key menu-name function).
1471 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.")
1474 (defvar org-ref-user-cite-menu-funcs
1475 '(("C" "rossref" org-ref-crossref-at-point)
1476 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1477 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1478 "user-defined functions to run on bibtex key at point.")
1481 (defun org-ref-copy-entry-as-summary ()
1482 "Copy the bibtex entry for the citation at point as a summary."
1484 (save-window-excursion
1485 (org-ref-open-citation-at-point)
1486 (kill-new (org-ref-bib-citation))))
1489 (defun org-ref-copy-entry-at-point-to-file ()
1490 "Copy the bibtex entry for the citation at point to NEW-FILE.
1491 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."
1493 (let ((new-file (ido-completing-read
1495 (append org-ref-default-bibliography
1496 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1497 (key (org-ref-get-bibtex-key-under-cursor)))
1498 (save-window-excursion
1499 (org-ref-open-citation-at-point)
1500 (bibtex-copy-entry-as-kill))
1502 (let ((bibtex-files (list (file-truename new-file))))
1503 (if (assoc key (bibtex-global-key-alist))
1504 (message "That key already exists in %s" new-file)
1506 (save-window-excursion
1507 (find-file new-file)
1508 (goto-char (point-max))
1509 ;; make sure we are at the beginning of a line.
1510 (unless (looking-at "^") (insert "\n\n"))
1515 (defun org-ref-get-doi-at-point ()
1516 "Get doi for key at point."
1518 (let* ((results (org-ref-get-bibtex-key-and-file))
1520 (bibfile (cdr results))
1524 (insert-file-contents bibfile)
1525 (bibtex-search-entry key)
1526 (setq doi (bibtex-autokey-get-field "doi"))
1527 ;; in case doi is a url, remove the url part.
1528 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1531 ;; functions that operate on key at point for click menu
1532 (defun org-ref-wos-at-point ()
1533 "open the doi in wos for bibtex key under point."
1535 (doi-utils-wos (org-ref-get-doi-at-point)))
1538 (defun org-ref-wos-citing-at-point ()
1539 "open the doi in wos citing articles for bibtex key under point."
1541 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1544 (defun org-ref-wos-related-at-point ()
1545 "open the doi in wos related articles for bibtex key under point."
1547 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1550 (defun org-ref-google-scholar-at-point ()
1551 "open the doi in google scholar for bibtex key under point."
1553 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1556 (defun org-ref-pubmed-at-point ()
1557 "open the doi in pubmed for bibtex key under point."
1559 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1562 (defun org-ref-crossref-at-point ()
1563 "open the doi in crossref for bibtex key under point."
1565 (doi-utils-crossref (org-ref-get-doi-at-point)))
1568 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1569 "action when a cite link is clicked on.
1570 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."
1572 (let* ((results (org-ref-get-bibtex-key-and-file))
1574 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1575 (bibfile (cdr results))
1576 (url (save-excursion
1578 (insert-file-contents bibfile)
1579 (bibtex-search-entry key)
1580 (bibtex-autokey-get-field "url"))))
1581 (doi (save-excursion
1583 (insert-file-contents bibfile)
1584 (bibtex-search-entry key)
1585 ;; I like this better than bibtex-url which does not always find
1587 (bibtex-autokey-get-field "doi")))))
1589 (when (string= "" doi) (setq doi nil))
1590 (when (string= "" url) (setq url nil))
1591 (setq org-ref-cite-menu-funcs '())
1597 'org-ref-cite-menu-funcs
1598 '("o" "pen" org-ref-open-citation-at-point)))
1601 (when (file-exists-p pdf-file)
1603 'org-ref-cite-menu-funcs
1604 `("p" "df" ,org-ref-open-pdf-function) t))
1608 'org-ref-cite-menu-funcs
1609 '("n" "otes" org-ref-open-notes-at-point) t)
1614 'org-ref-cite-menu-funcs
1615 '("u" "rl" org-ref-open-url-at-point) t))
1620 'org-ref-cite-menu-funcs
1621 '("w" "os" org-ref-wos-at-point) t)
1624 'org-ref-cite-menu-funcs
1625 '("c" "iting" org-ref-wos-citing-at-point) t)
1628 'org-ref-cite-menu-funcs
1629 '("r" "elated" org-ref-wos-related-at-point) t)
1632 'org-ref-cite-menu-funcs
1633 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1636 'org-ref-cite-menu-funcs
1637 '("P" "ubmed" org-ref-pubmed-at-point) t))
1639 ;; add user functions
1640 (dolist (tup org-ref-user-cite-menu-funcs)
1642 'org-ref-cite-menu-funcs
1647 'org-ref-cite-menu-funcs
1648 '("q" "uit" (lambda ())) t)
1650 ;; now we make a menu
1651 ;; construct menu string as a message
1654 (let* ((results (org-ref-get-bibtex-key-and-file))
1656 (bibfile (cdr results)))
1659 (insert-file-contents bibfile)
1660 (bibtex-search-entry key)
1661 (org-ref-bib-citation))))
1665 (concat "[" (elt tup 0) "]"
1667 org-ref-cite-menu-funcs "")))
1669 (let* ((input (read-char-exclusive))
1671 (char-to-string input) org-ref-cite-menu-funcs)))
1672 ;; now run the function (2nd element in choice)
1681 : org-ref-cite-onclick-minibuffer-menu
1683 *** A function to format a cite link
1685 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.
1687 #+BEGIN_SRC emacs-lisp :tangle no
1688 ;(defun org-ref-cite-link-format (keyword desc format)
1690 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1691 ; ((eq format 'latex)
1692 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1693 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1697 *** The actual cite link
1698 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1700 #+BEGIN_SRC emacs-lisp :tangle no
1703 ; 'org-ref-cite-onclick-minibuffer-menu
1704 ; 'org-ref-cite-link-format)
1707 *** Automatic definition of the cite links
1708 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.
1710 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1711 (defmacro org-ref-make-completion-function (type)
1712 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1718 (let ((bibtex-files (org-ref-find-bibliography)))
1719 (bibtex-global-key-alist))))))
1722 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.
1724 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1725 (defmacro org-ref-make-format-function (type)
1726 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1731 (format "[[#%s][%s]]" key key))
1732 (org-ref-split-and-strip-string keyword) ","))
1739 (org-ref-split-and-strip-string keyword) ",") "]"))
1744 (format "<a href=\"#%s\">%s</a>" key key))
1745 (org-ref-split-and-strip-string keyword) ","))
1748 (if (string= (substring type -1) "s")
1749 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1750 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1751 (org-ref-split-and-strip-string keyword) ""))
1753 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1754 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1760 We create the links by mapping the function onto the list of defined link types.
1762 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1763 (defun org-ref-format-citation-description (desc)
1764 "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 ::."
1767 ((string-match "::" desc)
1768 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1769 (t (format "[%s]" desc))))
1771 (defun org-ref-define-citation-link (type &optional key)
1772 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1773 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1774 and the completion function."
1775 (interactive "sCitation Type: \ncKey: ")
1777 ;; create the formatting function
1778 (eval `(org-ref-make-format-function ,type))
1783 org-ref-cite-onclick-function
1784 (quote ,(intern (format "org-ref-format-%s" type)))))
1786 ;; create the completion function
1787 (eval `(org-ref-make-completion-function ,type))
1789 ;; store new type so it works with adding citations, which checks
1790 ;; for existence in this list
1791 (add-to-list 'org-ref-cite-types type)
1793 ;; and finally if a key is specified, we modify the reftex menu
1795 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1796 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1797 `((,key . ,(concat type ":%l")))))))
1799 ;; create all the link types and their completion functions
1800 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1803 *** org-ref-insert-cite-link
1804 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.
1806 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1807 (defun org-ref-insert-cite-link (alternative-cite)
1808 "Insert a default citation link using reftex. If you are on a link, it
1809 appends to the end of the link, otherwise, a new link is
1810 inserted. Use a prefix arg to get a menu of citation types."
1812 (org-ref-find-bibliography)
1813 (let* ((object (org-element-context))
1814 (link-string-beginning (org-element-property :begin object))
1815 (link-string-end (org-element-property :end object))
1816 (path (org-element-property :path object)))
1818 (if (not alternative-cite)
1821 ;; case where we are in a link
1822 ((and (equal (org-element-type object) 'link)
1823 (-contains? org-ref-cite-types (org-element-property :type object)))
1824 (goto-char link-string-end)
1825 ;; sometimes there are spaces at the end of the link
1826 ;; this code moves point pack until no spaces are there
1827 (while (looking-back " ") (backward-char))
1828 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1830 ;; We are next to a link, and we want to append
1833 (and (equal (org-element-type (org-element-context)) 'link)
1834 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1835 (while (looking-back " ") (backward-char))
1836 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1838 ;; insert fresh link
1841 (concat org-ref-default-citation-link
1843 (mapconcat 'identity (reftex-citation t) ",")))))
1845 ;; you pressed a C-u so we run this code
1849 cite:zhou-2004-first-lda-u,paier-2006-errat,boes-2015-estim-bulk
1853 : org-ref-insert-cite-link
1855 *** Completion in cite links
1856 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.
1858 #+BEGIN_SRC emacs-lisp :tangle no
1859 (defun org-cite-complete-link (&optional arg)
1860 "Completion function for cite links"
1862 org-ref-default-citation-link
1865 (let ((bibtex-files (org-ref-find-bibliography)))
1866 (bibtex-global-key-alist)))))
1869 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1871 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1872 (defun org-ref-insert-cite-with-completion (type)
1873 "Insert a cite link with completion"
1874 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1875 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1878 ** Storing links to a bibtex entry
1879 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.
1881 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1882 (defun org-ref-store-bibtex-entry-link ()
1883 "Save a citation link to the current bibtex entry. Saves in the default link type."
1885 (let ((link (concat org-ref-default-citation-link
1888 (bibtex-beginning-of-entry)
1889 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1890 (message "saved %s" link)
1891 (push (list link) org-stored-links)
1892 (car org-stored-links)))
1896 org-ref minimally supports index entries. To make an index in a file, you should put in the LaTeX header these lines
1899 #+LATEX_HEADER: \usepackage{makeidx}
1900 #+LATEX_HEADER: \makeindex
1903 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.
1906 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.
1911 [[index:hello!Sam@\textsl{Sam}]]
1912 [[index:Lin@\textbf{Lin}]]
1913 [[index:Joe|textit]]
1914 [[index:Lin@\textbf{Lin}]]
1915 [[index:Peter|see {hello}]]
1916 [[index:Jen|seealso{Jenny}]]
1918 index:encodings!input!cp850
1920 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1926 (lambda (path desc format)
1929 (format "\\index{%s}" path)))))
1931 ;; this will generate a temporary index of entries in the file.
1935 (let ((*index-links* '())
1936 (*initial-letters* '()))
1939 (org-element-map (org-element-parse-buffer) 'link
1941 (let ((type (nth 0 link))
1942 (plist (nth 1 link)))
1944 (when (equal (plist-get plist ':type) "index")
1947 (cons (plist-get plist :path)
1949 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
1951 (plist-get plist :begin) ;; position of link
1952 ;; grab a description
1954 (goto-char (plist-get plist :begin))
1955 (if (thing-at-point 'sentence)
1957 (replace-regexp-in-string
1958 "\n" "" (thing-at-point 'sentence))
1959 ;; or call it a link
1963 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
1965 ;; now first letters
1966 (dolist (link *index-links*)
1967 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
1969 ;; now create the index
1970 (switch-to-buffer (get-buffer-create "*index*"))
1973 (insert "#+TITLE: Index\n\n")
1974 (dolist (letter *initial-letters*)
1975 (insert (format "* %s\n" (upcase letter)))
1976 ;; now process the links
1979 (string= letter (substring (car (car *index-links*)) 0 1)))
1980 (let ((link (pop *index-links*)))
1981 (insert (format "%s %s\n\n" (car link) (cdr link))))))
1982 (switch-to-buffer "*index*")))
1984 (lambda (path desc format)
1987 (format "\\printindex")))))
1991 | 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*)) |
1992 | lambda | (path desc format) | (cond ((eq format (quote latex)) (format \printindex))) |
1995 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.
1997 #+LATEX_HEADER: \usepackage{glossaries}
1998 #+LATEX_HEADER: \makeglossaries
2000 And at the end of the document put \makeglossaries.
2002 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2005 nil ;; no follow action
2006 (lambda (path desc format)
2009 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2015 nil ;; no follow action
2016 (lambda (path desc format)
2019 (format "\\gls{%s}" path)))))
2024 nil ;; no follow action
2025 (lambda (path desc format)
2028 (format "\\glspl{%s}" path)))))
2033 nil ;; no follow action
2034 (lambda (path desc format)
2037 (format "\\Gls{%s}" path)))))
2042 nil ;; no follow action
2043 (lambda (path desc format)
2046 (format "\\Glspl{%s}" path)))))
2052 ** create simple text citation from bibtex entry
2054 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2055 (defun org-ref-bib-citation ()
2056 "From a bibtex entry, create and return a simple citation string.
2057 This assumes you are in an article."
2059 (bibtex-beginning-of-entry)
2060 (let* ((cb (current-buffer))
2061 (bibtex-expand-strings t)
2062 (entry (loop for (key . value) in (bibtex-parse-entry t)
2063 collect (cons (downcase key) value)))
2064 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2065 (year (reftex-get-bib-field "year" entry))
2066 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2067 (key (reftex-get-bib-field "=key=" entry))
2068 (journal (reftex-get-bib-field "journal" entry))
2069 (volume (reftex-get-bib-field "volume" entry))
2070 (pages (reftex-get-bib-field "pages" entry))
2071 (doi (reftex-get-bib-field "doi" entry))
2072 (url (reftex-get-bib-field "url" entry))
2074 ;;authors, "title", Journal, vol(iss):pages (year).
2075 (format "%s, \"%s\", %s, %s:%s (%s)"
2076 author title journal volume pages year)))
2080 : org-ref-bib-citation
2083 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2084 (defun org-ref-bib-html-citation ()
2085 "from a bibtex entry, create and return a simple citation with html links."
2087 (bibtex-beginning-of-entry)
2088 (let* ((cb (current-buffer))
2089 (bibtex-expand-strings t)
2090 (entry (loop for (key . value) in (bibtex-parse-entry t)
2091 collect (cons (downcase key) value)))
2092 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2093 (year (reftex-get-bib-field "year" entry))
2094 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2095 (key (reftex-get-bib-field "=key=" entry))
2096 (journal (reftex-get-bib-field "journal" entry))
2097 (volume (reftex-get-bib-field "volume" entry))
2098 (pages (reftex-get-bib-field "pages" entry))
2099 (doi (reftex-get-bib-field "doi" entry))
2100 (url (reftex-get-bib-field "url" entry))
2102 ;;authors, "title", Journal, vol(iss):pages (year).
2103 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2104 author title journal volume pages year)
2105 (when url (format " <a href=\"%s\">link</a>" url))
2106 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2110 ** open pdf from bibtex
2111 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2112 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2113 (defun org-ref-open-bibtex-pdf ()
2114 "open pdf for a bibtex entry, if it exists. assumes point is in
2115 the entry of interest in the bibfile. but does not check that."
2118 (bibtex-beginning-of-entry)
2119 (let* ((bibtex-expand-strings t)
2120 (entry (bibtex-parse-entry t))
2121 (key (reftex-get-bib-field "=key=" entry))
2122 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2124 (if (file-exists-p pdf)
2125 (org-open-link-from-string (format "[[file:%s]]" pdf))
2129 ** open notes from bibtex
2130 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2132 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2133 (defun org-ref-open-bibtex-notes ()
2134 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
2136 I never did figure out how to use reftex to make this happen
2137 non-interactively. the reftex-format-citation function did not
2138 work perfectly; there were carriage returns in the strings, and
2139 it did not put the key where it needed to be. so, below I replace
2140 the carriage returns and extra spaces with a single space and
2141 construct the heading by hand."
2144 (bibtex-beginning-of-entry)
2145 (let* ((cb (current-buffer))
2146 (bibtex-expand-strings t)
2147 (entry (loop for (key . value) in (bibtex-parse-entry t)
2148 collect (cons (downcase key) value)))
2149 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2150 (year (reftex-get-bib-field "year" entry))
2151 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2152 (key (reftex-get-bib-field "=key=" entry))
2153 (journal (reftex-get-bib-field "journal" entry))
2154 (volume (reftex-get-bib-field "volume" entry))
2155 (pages (reftex-get-bib-field "pages" entry))
2156 (doi (reftex-get-bib-field "doi" entry))
2157 (url (reftex-get-bib-field "url" entry))
2160 ;; save key to clipboard to make saving pdf later easier by pasting.
2163 (kill-ring-save (point-min) (point-max)))
2165 ;; now look for entry in the notes file
2166 (if org-ref-bibliography-notes
2167 (find-file-other-window org-ref-bibliography-notes)
2168 (error "org-ref-bib-bibliography-notes is not set to anything"))
2170 (goto-char (point-min))
2171 ;; put new entry in notes if we don't find it.
2172 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2173 (funcall org-ref-open-notes-function)
2174 ;; no entry found, so add one
2175 (insert (format "\n** TODO %s - %s" year title))
2187 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2188 key author journal year volume pages doi url key org-ref-pdf-directory key))
2192 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2193 (defun org-ref-open-notes-from-reftex ()
2194 "Call reftex, and open notes for selected entry."
2196 (let ((bibtex-key )))
2198 ;; now look for entry in the notes file
2199 (if org-ref-bibliography-notes
2200 (find-file-other-window org-ref-bibliography-notes)
2201 (error "org-ref-bib-bibliography-notes is not set to anything"))
2203 (goto-char (point-min))
2205 (re-search-forward (format
2207 (first (reftex-citation t)) nil 'end))
2208 (funcall org-ref-open-notes-function))
2211 ** open url in browser from bibtex
2213 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2215 + 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.
2217 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2218 (defun org-ref-open-in-browser ()
2219 "Open the bibtex entry at point in a browser using the url field or doi field"
2222 (bibtex-beginning-of-entry)
2224 (let ((url (bibtex-autokey-get-field "url")))
2229 (let ((doi (bibtex-autokey-get-field "doi")))
2231 (if (string-match "^http" doi)
2233 (browse-url (format "http://dx.doi.org/%s" doi)))
2235 (message "No url or doi found"))))
2239 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.
2241 *** function to upload bibtex to citeulike
2243 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2244 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2245 "with point in a bibtex entry get bibtex string and submit to citeulike.
2247 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2249 (message "uploading to citeulike")
2251 (bibtex-narrow-to-entry)
2252 (let ((startpos (point-min))
2253 (endpos (point-max))
2254 (bibtex-string (buffer-string))
2255 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2256 (with-temp-buffer (insert bibtex-string)
2257 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2260 *** The upload script
2261 Here is the python script for uploading.
2263 *************** TODO document how to get the cookies
2267 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
2269 import pickle, requests, sys
2272 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
2273 cookies = pickle.load(f)
2275 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
2277 bibtex = sys.stdin.read()
2279 data = {'pasted':bibtex,
2281 'tag_parsing':'simple',
2282 'strip_brackets':'no',
2283 'update_id':'bib-key',
2284 'btn_bibtex':'Import BibTeX file ...'}
2286 headers = {'content-type': 'multipart/form-data',
2287 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
2289 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
2293 ** Build a pdf from a bibtex file
2294 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.
2296 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2297 (defun org-ref-build-full-bibliography ()
2298 "build pdf of all bibtex entries, and open it."
2300 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2301 (bib-base (file-name-sans-extension bibfile))
2302 (texfile (concat bib-base ".tex"))
2303 (pdffile (concat bib-base ".pdf")))
2306 (insert (format "\\documentclass[12pt]{article}
2307 \\usepackage[version=3]{mhchem}
2309 \\usepackage[numbers]{natbib}
2310 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2314 \\bibliographystyle{unsrtnat}
2316 \\end{document}" bib-base))
2318 (shell-command (concat "pdflatex " bib-base))
2319 (shell-command (concat "bibtex " bib-base))
2320 (shell-command (concat "pdflatex " bib-base))
2321 (shell-command (concat "pdflatex " bib-base))
2322 (kill-buffer texfile)
2323 (org-open-file pdffile)
2327 ** Extract bibtex entries cited in an org-file
2328 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.
2330 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2331 (defun org-ref-extract-bibtex-entries ()
2332 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2334 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
2336 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2337 (tempname (make-temp-file "extract-bib"))
2338 (contents (buffer-string))
2339 (cb (current-buffer))
2340 basename texfile bibfile results)
2342 ;; open tempfile and insert org-buffer contents
2343 (find-file tempname)
2345 (setq basename (file-name-sans-extension
2346 (file-name-nondirectory buffer-file-name))
2347 texfile (concat tempname ".tex")
2348 bibfile (concat tempname ".bib"))
2350 ;; see if we have a bibliography, and insert the default one if not.
2352 (goto-char (point-min))
2353 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2354 (insert (format "\nbibliography:%s"
2355 (mapconcat 'identity reftex-default-bibliography ",")))))
2358 ;; get a latex file and extract the references
2359 (org-latex-export-to-latex)
2362 (reftex-create-bibtex-file bibfile)
2364 ;; save results of the references
2365 (setq results (buffer-string))
2367 ;; kill buffers. these are named by basename, not full path
2368 (kill-buffer (concat basename ".bib"))
2369 (kill-buffer (concat basename ".tex"))
2370 (kill-buffer basename)
2372 (delete-file bibfile)
2373 (delete-file texfile)
2374 (delete-file tempname)
2376 ;; Now back to the original org buffer and insert the results
2377 (switch-to-buffer cb)
2378 (when (not (string= "" results))
2380 (goto-char (point-max))
2382 (org-insert-heading)
2383 (insert (format " Bibtex entries
2385 ,#+BEGIN_SRC text :tangle %s
2387 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2390 ** Find bad cite links
2391 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.
2393 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2396 (defun index (substring list)
2397 "return the index of string in a list of strings"
2400 (dolist (arg list i)
2401 (if (string-match (concat "^" substring "$") arg)
2406 ;; return counter if found, otherwise return nil
2410 (defun org-ref-find-bad-citations ()
2411 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2413 Makes a new buffer with clickable links."
2415 ;; generate the list of bibtex-keys and cited keys
2416 (let* ((bibtex-files (org-ref-find-bibliography))
2417 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2418 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2419 (bad-citations '()))
2421 (org-element-map (org-element-parse-buffer) 'link
2423 (let ((plist (nth 1 link)))
2424 (when (equal (plist-get plist ':type) "cite")
2425 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2426 (when (not (index key bibtex-keys))
2427 (setq bad-citations (append bad-citations
2428 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2429 key (buffer-name)(plist-get plist ':begin)))))
2434 (switch-to-buffer-other-window "*Missing citations*")
2437 (insert "* List of bad cite links\n")
2438 (insert (mapconcat 'identity bad-citations ""))
2439 ;(setq buffer-read-only t)
2440 (use-local-map (copy-keymap org-mode-map))
2441 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2443 (when (get-buffer "*Missing citations*")
2444 (kill-buffer "*Missing citations*"))
2445 (message "No bad cite links found"))))
2448 ** Finding non-ascii characters
2449 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2451 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2452 (defun org-ref-find-non-ascii-characters ()
2453 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2455 (occur "[^[:ascii:]]"))
2458 ** Resort a bibtex entry
2459 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.
2461 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2462 (defun org-ref-sort-bibtex-entry ()
2463 "sort fields of entry in standard order and downcase them"
2465 (bibtex-beginning-of-entry)
2466 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2467 (entry (bibtex-parse-entry))
2470 (type (cdr (assoc "=type=" entry)))
2471 (key (cdr (assoc "=key=" entry))))
2473 ;; these are the fields we want to order that are in this entry
2474 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2475 ;; we do not want to reenter these fields
2476 (setq entry-fields (remove "=key=" entry-fields))
2477 (setq entry-fields (remove "=type=" entry-fields))
2479 ;;these are the other fields in the entry
2480 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2483 ;; right now we only resort articles
2484 ((string= (downcase type) "article")
2487 (concat "@article{" key ",\n"
2490 (when (member field entry-fields)
2491 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2494 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2496 (bibtex-find-entry key)
2498 (bibtex-clean-entry)
2502 ** Clean a bibtex entry
2503 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.
2504 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.
2505 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2506 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2507 "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"
2509 (bibtex-beginning-of-entry)
2511 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2512 (unless (string-match ",$" (thing-at-point 'line))
2516 ;; check for empty pages, and put eid or article id in its place
2517 (let ((entry (bibtex-parse-entry))
2518 (pages (bibtex-autokey-get-field "pages"))
2519 (year (bibtex-autokey-get-field "year"))
2520 (doi (bibtex-autokey-get-field "doi"))
2521 ;; The Journal of Chemical Physics uses eid
2522 (eid (bibtex-autokey-get-field "eid")))
2524 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2525 ;; but we only want the doi.
2526 (when (string-match "^http://dx.doi.org/" doi)
2527 (bibtex-beginning-of-entry)
2528 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2530 (bibtex-make-field "doi")
2532 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2534 ;; asap articles often set year to 0, which messes up key
2535 ;; generation. fix that.
2536 (when (string= "0" year)
2537 (bibtex-beginning-of-entry)
2538 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2540 (bibtex-make-field "year")
2542 (insert (read-string "Enter year: ")))
2544 ;; fix pages if they are empty if there is an eid to put there.
2545 (when (string= "-" pages)
2547 (bibtex-beginning-of-entry)
2548 ;; this seems like a clunky way to set the pages field.But I
2549 ;; cannot find a better way.
2550 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2552 (bibtex-make-field "pages")
2556 ;; replace naked & with \&
2558 (bibtex-narrow-to-entry)
2559 (bibtex-beginning-of-entry)
2560 (message "checking &")
2561 (replace-regexp " & " " \\\\& ")
2564 ;; generate a key, and if it duplicates an existing key, edit it.
2566 (let ((key (bibtex-generate-autokey)))
2568 ;; first we delete the existing key
2569 (bibtex-beginning-of-entry)
2570 (re-search-forward bibtex-entry-maybe-empty-head)
2571 (if (match-beginning bibtex-key-in-head)
2572 (delete-region (match-beginning bibtex-key-in-head)
2573 (match-end bibtex-key-in-head)))
2574 ;; check if the key is in the buffer
2575 (when (save-excursion
2576 (bibtex-search-entry key))
2578 (bibtex-search-entry key)
2579 (bibtex-copy-entry-as-kill)
2580 (switch-to-buffer-other-window "*duplicate entry*")
2582 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2585 (kill-new key))) ;; save key for pasting
2587 ;; run hooks. each of these operates on the entry with no arguments.
2588 ;; this did not work like i thought, it gives a symbolp error.
2589 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2594 org-ref-clean-bibtex-entry-hook)
2596 ;; sort fields within entry
2597 (org-ref-sort-bibtex-entry)
2598 ;; check for non-ascii characters
2599 (occur "[^[:ascii:]]")
2604 : org-ref-clean-bibtex-entry
2606 ** Sort the entries in a citation link by year
2607 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2609 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2610 (defun org-ref-get-citation-year (key)
2611 "get the year of an entry with key. Returns year as a string."
2613 (let* ((results (org-ref-get-bibtex-key-and-file key))
2614 (bibfile (cdr results)))
2616 (insert-file-contents bibfile)
2617 (bibtex-search-entry key nil 0)
2618 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2621 (defun org-ref-sort-citation-link ()
2622 "replace link at point with sorted link by year"
2624 (let* ((object (org-element-context))
2625 (type (org-element-property :type object))
2626 (begin (org-element-property :begin object))
2627 (end (org-element-property :end object))
2628 (link-string (org-element-property :path object))
2630 (setq keys (org-ref-split-and-strip-string link-string))
2631 (setq years (mapcar 'org-ref-get-citation-year keys))
2632 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2633 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2634 ;; now get the keys separated by commas
2635 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2636 ;; and replace the link with the sorted keys
2637 (cl--set-buffer-substring begin end (concat type ":" keys))))
2640 ** Sort entries in citation links with shift-arrow keys
2641 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2642 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2643 (defun org-ref-swap-keys (i j keys)
2644 "swap the keys in a list with index i and j"
2645 (let ((tempi (nth i keys)))
2646 (setf (nth i keys) (nth j keys))
2647 (setf (nth j keys) tempi))
2650 (defun org-ref-swap-citation-link (direction)
2651 "move citation at point in direction +1 is to the right, -1 to the left"
2653 (let* ((object (org-element-context))
2654 (type (org-element-property :type object))
2655 (begin (org-element-property :begin object))
2656 (end (org-element-property :end object))
2657 (link-string (org-element-property :path object))
2659 ;; We only want this to work on citation links
2660 (when (-contains? org-ref-cite-types type)
2661 (setq key (org-ref-get-bibtex-key-under-cursor))
2662 (setq keys (org-ref-split-and-strip-string link-string))
2663 (setq i (index key keys)) ;; defined in org-ref
2664 (if (> direction 0) ;; shift right
2665 (org-ref-swap-keys i (+ i 1) keys)
2666 (org-ref-swap-keys i (- i 1) keys))
2667 (setq keys (mapconcat 'identity keys ","))
2668 ;; and replace the link with the sorted keys
2669 (cl--set-buffer-substring begin end (concat type ":" keys " "))
2670 ;; now go forward to key so we can move with the key
2671 (re-search-forward key)
2672 (goto-char (match-beginning 0)))))
2674 ;; add hooks to make it work
2675 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2676 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2679 ** Lightweight messages about links
2680 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 add it to a hook that updates after every command, including cursor movements.
2682 ref:test citep:test label:rett
2684 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2685 (defun org-ref-get-label-context (label)
2686 "Return a string of context around a label."
2689 (goto-char (point-min))
2690 (when (re-search-forward
2691 (format "label:%s\\b" label) nil t)
2692 (throw 'result (buffer-substring
2701 (goto-char (point-min))
2702 (when (re-search-forward
2703 (format "\\label{%s}" label) nil t)
2704 (throw 'result (buffer-substring
2713 (goto-char (point-min))
2714 (when (re-search-forward
2715 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2716 (throw 'result (buffer-substring
2725 (goto-char (point-min))
2726 (when (re-search-forward
2727 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2728 (throw 'result (buffer-substring
2738 (defun org-ref-link-message ()
2739 "Print a minibuffer message about the link that point is on."
2741 (let* ((object (org-element-context))
2742 (type (org-element-property :type object)))
2746 ((-contains? org-ref-cite-types type)
2747 (message (org-ref-get-citation-string-at-point)))
2749 ;; message some context about the label we are referring to
2750 ((string= type "ref")
2751 (message (org-ref-get-label-context
2752 (org-element-property :path object))))
2754 ((string= type "eqref")
2755 (message (org-ref-get-label-context
2756 (org-element-property :path object))))
2758 ;; message the count
2759 ((string= type "label")
2760 (let ((count (org-ref-count-labels
2761 (org-element-property :path object))))
2762 ;; get plurality on occurrence correct
2764 (number-to-string count)
2766 (when (or (= count 0)
2772 I like convenience. Here are some aliases for faster typing.
2774 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2775 (defalias 'oro 'org-ref-open-citation-at-point)
2776 (defalias 'orc 'org-ref-citation-at-point)
2777 (defalias 'orp 'org-ref-open-pdf-at-point)
2778 (defalias 'oru 'org-ref-open-url-at-point)
2779 (defalias 'orn 'org-ref-open-notes-at-point)
2780 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2782 (defalias 'orib 'org-ref-insert-bibliography-link)
2783 (defalias 'oric 'org-ref-insert-cite-link)
2784 (defalias 'orir 'org-ref-insert-ref-link)
2785 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2787 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2790 [[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.
2792 1. Make the default action to insert selected keys.
2793 2. Make open entry second action
2794 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2795 (setq helm-source-bibtex
2796 '((name . "BibTeX entries")
2797 (init . helm-bibtex-init)
2798 (candidates . helm-bibtex-candidates)
2799 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
2800 (action . (("Insert citation" . helm-bibtex-insert-citation)
2801 ("Show entry" . helm-bibtex-show-entry)
2802 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
2803 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
2804 ("Insert reference" . helm-bibtex-insert-reference)
2805 ("Insert BibTeX key" . helm-bibtex-insert-key)
2806 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
2807 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
2808 ("Edit notes" . helm-bibtex-edit-notes)
2812 Now, let us define a function that inserts the cite links:
2813 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2814 (defun helm-bibtex-format-org-ref (keys)
2815 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
2816 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."
2817 (let* ((object (org-element-context)))
2819 ;; case where we are in a link
2820 ((and (equal (org-element-type object) 'link)
2823 (org-element-property :type object)))
2824 (message-box "in a link")
2825 (goto-char (org-element-property :end object))
2826 ;; sometimes there are spaces at the end of the link
2827 ;; this code moves point pack until no spaces are there
2828 (while (looking-back " ") (backward-char))
2829 (insert (concat "," (mapconcat 'identity keys ","))))
2831 ;; We are next to a link, and we want to append
2832 ;; next to a link means one character back is on a link.
2835 (and (equal (org-element-type (org-element-context)) 'link)
2838 (org-element-property :type (org-element-context)))))
2839 (message-box "at end of a link")
2840 ;; (goto-char (org-element-property :end object))
2841 (while (looking-back " ") (backward-char))
2842 (insert (concat "," (mapconcat 'identity keys ","))))
2844 ;; insert fresh link
2846 (message-box "fresh link")
2848 (concat (if helm-current-prefix-arg
2849 (helm :sources `((name . "link types")
2850 (candidates . ,org-ref-cite-types)
2851 (action . (lambda (x) x))))
2852 org-ref-default-citation-link)
2854 (s-join "," keys))))))
2855 ;; return empty string for helm
2858 (setq helm-bibtex-format-citation-functions
2859 '((org-mode . helm-bibtex-format-org-ref)))
2861 (defun org-ref-helm-insert-cite-link ()
2862 "org-ref function to use helm on the bibliography defined in the org-file."
2864 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
2867 (require 'helm-bibtex)
2870 ** A helm click menu
2871 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.
2872 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2873 (defun org-ref-get-citation-string-at-point ()
2874 "Get a string of a formatted citation"
2876 (let* ((results (org-ref-get-bibtex-key-and-file))
2878 (bibfile (cdr results)))
2881 (insert-file-contents bibfile)
2882 (bibtex-search-entry key)
2883 (org-ref-bib-citation)))))
2885 (defun org-ref-cite-candidates ()
2886 "Generate the list of possible candidates for click actions on a cite link.
2887 Checks for pdf and doi, and add appropriate functions."
2889 (let* ((results (org-ref-get-bibtex-key-and-file))
2891 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
2892 (bibfile (cdr results))
2893 (url (save-excursion
2895 (insert-file-contents bibfile)
2896 (bibtex-search-entry key)
2897 (bibtex-autokey-get-field "url"))))
2898 (doi (save-excursion
2900 (insert-file-contents bibfile)
2901 (bibtex-search-entry key)
2902 ;; I like this better than bibtex-url which does not always find
2904 (bibtex-autokey-get-field "doi"))))
2905 (candidates `(("Quit" . org-ref-citation-at-point)
2906 ("Open bibtex entry" . org-ref-open-citation-at-point))))
2907 ;; for some reason, when there is no doi or url, they are returned as "". I
2908 ;; prefer nil so we correct this here.
2909 (when (string= doi "") (setq doi nil))
2910 (when (string= url "") (setq url nil))
2912 ;; Conditional pdf functions
2913 (if (file-exists-p pdf-file)
2916 '("Open pdf" . org-ref-open-pdf-at-point)
2920 '("Try to get pdf" . (lambda ()
2921 (save-window-excursion
2922 (org-ref-open-citation-at-point)
2923 (bibtex-beginning-of-entry)
2924 (doi-utils-get-bibtex-entry-pdf))))
2930 '("Open notes" . org-ref-open-notes-at-point)
2933 ;; conditional url and doi functions
2937 '("Open in browser" . org-ref-open-url-at-point)
2942 (add-to-list 'candidates x t))
2943 `(("WOS" . org-ref-wos-at-point)
2944 ("Related articles in WOS" . org-ref-wos-related-at-point)
2945 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
2946 ("Google Scholar" . org-ref-google-scholar-at-point)
2947 ("Pubmed" . org-ref-pubmed-at-point)
2948 ("Crossref" . org-ref-crossref-at-point)
2953 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
2958 '("Copy key to clipboard" . (lambda ()
2960 (car (org-ref-get-bibtex-key-and-file)))))
2965 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
2970 '("Email bibtex entry and pdf" . (lambda ()
2972 (org-ref-open-citation-at-point)
2973 (email-bibtex-entry))))
2975 ;; finally return a numbered list of the candidates
2977 for cell in candidates
2978 collect (cons (format "%2s. %s" i (car cell))
2982 (defvar org-ref-helm-user-candidates '()
2983 "List of user-defined candidates to act when clicking on a cite link.
2984 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.
2987 ;; example of adding your own function
2989 'org-ref-helm-user-candidates
2990 '("Example" . (lambda () (message-box "You did it!")))
2993 (defun org-ref-cite-click-helm (key)
2995 1. get name and candidates before entering helm because we need the org-buffer.
2996 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer."
2998 (let ((name (org-ref-get-citation-string-at-point))
2999 (candidates (org-ref-cite-candidates))
3000 (cb (current-buffer)))
3002 (helm :sources `(((name . ,name)
3003 (candidates . ,candidates)
3004 (action . (lambda (f)
3005 (switch-to-buffer cb)
3007 ((name . "User functions")
3008 (candidates . ,org-ref-helm-user-candidates)
3009 (action . (lambda (f)
3010 (switch-to-buffer cb)
3016 : org-ref-cite-click-helm
3019 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3024 This code will tangle the elisp code out to org-ref.el and load it.
3026 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
3028 Alternatively you may use:
3030 [[elisp:(org-babel-load-file "org-ref.org")]]