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)
225 (define-key org-mode-map (kbd org-ref-insert-cite-key) org-ref-insert-cite-function))
227 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
229 (eval-after-load 'reftex-vars
231 (add-to-list 'reftex-cite-format-builtin
232 '(org "Org-mode citation"
233 ((?\C-m . "cite:%l") ; default
234 (?d . ",%l") ; for appending
240 (?h . "citeauthor:%l")
241 (?H . "citeauthor*:%l")
248 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.
250 #+BEGIN_SRC emacs-lisp :tangle no
252 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
253 (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l")
254 (?z . "newcite:%l"))))
257 You can define a new citation link like this:
258 #+BEGIN_SRC emacs-lisp :tangle no
259 (org-ref-define-citation-link "citez" ?z)
263 Most of this library is the creation of functional links to help with references and citations.
265 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.
267 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
268 (defun org-ref-strip-string (string)
269 "strip leading and trailing whitespace from the string"
270 (replace-regexp-in-string
271 (concat search-whitespace-regexp "$" ) ""
272 (replace-regexp-in-string
273 (concat "^" search-whitespace-regexp ) "" string)))
276 It is helpful to make the previous function operate on a list of strings here.
278 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
279 (defun org-ref-split-and-strip-string (string)
280 "split key-string and strip keys. Assumes the key-string is comma delimited"
281 (mapcar 'org-ref-strip-string (split-string string ",")))
284 ** bibliography and bibliographystyle
285 *** An html bibliography
287 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.
289 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
290 (defun org-ref-reftex-get-bib-field (field entry &optional format)
291 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
293 (setq result (reftex-get-bib-field field entry format))
294 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
295 (setq result (substring result 1 -1)))
296 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
297 (setq result (substring result 1 -1)))
300 (defun org-ref-reftex-format-citation (entry format)
301 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
302 to the format argument. The format is a string with these percent escapes.
304 In the format, the following percent escapes will be expanded.
306 %l The BibTeX label of the citation.
307 %a List of author names, see also `reftex-cite-punctuation'.
308 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
309 %A First author name only.
310 %e Works like %a, but on list of editor names. (%2e and %E work a well)
312 It is also possible to access all other BibTeX database fields:
313 %b booktitle %c chapter %d edition %h howpublished
314 %i institution %j journal %k key %m month
315 %n number %o organization %p pages %P first page
316 %r address %s school %u publisher %t title
318 %B booktitle, abbreviated %T title, abbreviated
323 Usually, only %l is needed. The other stuff is mainly for the echo area
324 display, and for (setq reftex-comment-citations t).
326 %< as a special operator kills punctuation and space around it after the
327 string has been formatted.
329 A pair of square brackets indicates an optional argument, and RefTeX
330 will prompt for the values of these arguments.
332 Beware that all this only works with BibTeX database files. When
333 citations are made from the \bibitems in an explicit thebibliography
334 environment, only %l is available."
335 ;; Format a citation from the info in the BibTeX ENTRY
337 (unless (stringp format) (setq format "\\cite{%l}"))
339 (if (and reftex-comment-citations
340 (string-match "%l" reftex-cite-comment-format))
341 (error "reftex-cite-comment-format contains invalid %%l"))
344 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
346 (let ((n (string-to-number (match-string 4 format)))
347 (l (string-to-char (match-string 5 format)))
353 (org-ref-reftex-get-bib-field "&key" entry)
354 (if reftex-comment-citations
355 reftex-cite-comment-format
357 ((= l ?a) (reftex-format-names
358 (reftex-get-bib-names "author" entry)
360 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
361 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
362 ((= l ?B) (reftex-abbreviate-title
363 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
364 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
365 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
366 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
367 ((= l ?e) (reftex-format-names
368 (reftex-get-bib-names "editor" entry)
370 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
371 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
372 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
373 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
374 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
375 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
376 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
377 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
378 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
379 ((= l ?P) (car (split-string
380 (org-ref-reftex-get-bib-field "pages" entry)
382 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
383 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
384 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
385 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
386 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
387 ;; strip enclosing brackets from title if they are there
388 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
389 ((= l ?T) (reftex-abbreviate-title
390 (org-ref-reftex-get-bib-field "title" entry)))
391 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
392 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
395 (setq b (match-beginning 2) e (match-end 2))
396 (setq b (match-beginning 3) e (match-end 3)))
397 (setq format (concat (substring format 0 b) rpl (substring format e)))))
398 (while (string-match "%%" format)
399 (setq format (replace-match "%" t t format)))
400 (while (string-match "[ ,.;:]*%<" format)
401 (setq format (replace-match "" t t format)))
402 ;; also replace carriage returns, tabs, and multiple whitespaces
403 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
406 (defun org-ref-get-bibtex-entry-citation (key)
407 "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
409 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
410 (file) (entry) (bibtex-entry) (entry-type) (format))
412 (setq file (catch 'result
413 (loop for file in org-ref-bibliography-files do
414 (if (org-ref-key-in-file-p key (file-truename file))
416 (message "%s not found in %s" key (file-truename file))))))
419 (insert-file-contents file)
420 (bibtex-search-entry key nil 0)
421 (setq bibtex-entry (bibtex-parse-entry))
422 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
423 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
425 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
427 (bibtex-narrow-to-entry)
428 (setq entry (buffer-string)))))
433 : org-ref-reftex-format-citation
435 Here is how to use the function. You call it with point in an entry in a bibtex file.
437 #+BEGIN_SRC emacs-lisp :tangle no
438 (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>."))
439 (org-ref-get-bibtex-entry-citation "armiento-2014-high"))
442 : 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>.
444 I am not sure why full author names are not used.
446 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
448 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
449 (defun org-ref-get-bibtex-keys ()
450 "return a list of unique keys in the buffer."
452 (org-element-map (org-element-parse-buffer) 'link
454 (let ((plist (nth 1 link)))
455 (when (-contains? org-ref-cite-types (plist-get plist ':type))
458 (org-ref-split-and-strip-string (plist-get plist ':path)))
459 (when (not (-contains? keys key))
460 (setq keys (append keys (list key)))))))))
461 ;; Sort keys alphabetically
462 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
466 This function gets the html for one entry.
468 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
469 (defun org-ref-get-bibtex-entry-html (key)
470 "returns an html string for the bibliography entry corresponding to key"
472 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
475 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
477 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
478 (defun org-ref-get-html-bibliography ()
479 "Create an html bibliography when there are keys"
480 (let ((keys (org-ref-get-bibtex-keys)))
482 (concat "<h1>Bibliography</h1>
484 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
488 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.
490 *** An org bibliography
491 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.
493 First, we get the string for a single entry.
494 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
495 (defun org-ref-get-bibtex-entry-org (key)
496 "returns an org string for the bibliography entry corresponding to key"
497 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
498 (file) (entry) (bibtex-entry) (entry-type) (format))
500 (setq file (catch 'result
501 (loop for file in org-ref-bibliography-files do
502 (if (org-ref-key-in-file-p key (file-truename file))
504 (message "%s not found in %s" key (file-truename file))))))
507 (insert-file-contents file)
508 (bibtex-search-entry key nil 0)
509 (setq entry (bibtex-parse-entry))
514 " (org-ref-reftex-get-bib-field "author" entry)
515 (org-ref-reftex-get-bib-field "title" entry)
516 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
517 (mapconcat (lambda (element) (format " :%s: %s"
518 (upcase (car element))
524 Now, we loop over the keys, and combine all the entries into a bibliography.
525 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
526 (defun org-ref-get-org-bibliography ()
527 "Create an org bibliography when there are keys"
528 (let ((keys (org-ref-get-bibtex-keys)))
530 (concat "* Bibliography
532 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
536 *** An ascii bibliography
538 This function gets the html for one entry.
540 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
541 (defun org-ref-get-bibtex-entry-ascii (key)
542 "returns an ascii string for the bibliography entry corresponding to key"
544 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
547 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
549 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
550 (defun org-ref-get-ascii-bibliography ()
551 "Create an html bibliography when there are keys"
552 (let ((keys (org-ref-get-bibtex-keys)))
558 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
564 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.
566 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
567 (org-add-link-type "bibliography"
568 ;; this code is run on clicking. The bibliography
569 ;; may contain multiple files. this code finds the
570 ;; one you clicked on and opens it.
571 (lambda (link-string)
572 ;; get link-string boundaries
573 ;; we have to go to the beginning of the line, and then search forward
576 ;; object is the link you clicked on
577 (object (org-element-context))
579 (link-string-beginning)
583 (goto-char (org-element-property :begin object))
584 (search-forward link-string nil nil 1)
585 (setq link-string-beginning (match-beginning 0))
586 (setq link-string-end (match-end 0)))
588 ;; We set the reftex-default-bibliography
589 ;; here. it should be a local variable only in
590 ;; the current buffer. We need this for using
591 ;; reftex to do citations.
592 (set (make-local-variable 'reftex-default-bibliography)
593 (split-string (org-element-property :path object) ","))
595 ;; now if we have comma separated bibliographies
596 ;; we find the one clicked on. we want to
597 ;; search forward to next comma from point
599 (if (search-forward "," link-string-end 1 1)
600 (setq key-end (- (match-end 0) 1)) ; we found a match
601 (setq key-end (point)))) ; no comma found so take the point
602 ;; and backward to previous comma from point
604 (if (search-backward "," link-string-beginning 1 1)
605 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
606 (setq key-beginning (point)))) ; no match found
607 ;; save the key we clicked on.
608 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
609 (find-file bibfile))) ; open file on click
612 (lambda (keyword desc format)
614 ((eq format 'org) (org-ref-get-org-bibliography))
615 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
616 ((eq format 'html) (org-ref-get-html-bibliography))
618 ;; write out the latex bibliography command
619 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
620 (mapcar 'expand-file-name
621 (split-string keyword ","))
626 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.
629 \input{project-description.bbl}
632 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.
634 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
635 (org-add-link-type "nobibliography"
636 ;; this code is run on clicking. The bibliography
637 ;; may contain multiple files. this code finds the
638 ;; one you clicked on and opens it.
639 (lambda (link-string)
640 ;; get link-string boundaries
641 ;; we have to go to the beginning of the line, and then search forward
644 ;; object is the link you clicked on
645 (object (org-element-context))
647 (link-string-beginning)
651 (goto-char (org-element-property :begin object))
652 (search-forward link-string nil nil 1)
653 (setq link-string-beginning (match-beginning 0))
654 (setq link-string-end (match-end 0)))
656 ;; We set the reftex-default-bibliography
657 ;; here. it should be a local variable only in
658 ;; the current buffer. We need this for using
659 ;; reftex to do citations.
660 (set (make-local-variable 'reftex-default-bibliography)
661 (split-string (org-element-property :path object) ","))
663 ;; now if we have comma separated bibliographies
664 ;; we find the one clicked on. we want to
665 ;; search forward to next comma from point
667 (if (search-forward "," link-string-end 1 1)
668 (setq key-end (- (match-end 0) 1)) ; we found a match
669 (setq key-end (point)))) ; no comma found so take the point
670 ;; and backward to previous comma from point
672 (if (search-backward "," link-string-beginning 1 1)
673 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
674 (setq key-beginning (point)))) ; no match found
675 ;; save the key we clicked on.
676 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
677 (find-file bibfile))) ; open file on click
680 (lambda (keyword desc format)
682 ((eq format 'org) (org-ref-get-org-bibliography))
683 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
684 ((eq format 'html) (org-ref-get-html-bibliography))
686 ;; write out the latex bibliography command
688 ; (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
689 ; (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
690 ; (mapcar 'expand-file-name
691 ; (split-string keyword ","))
694 (format "\\nobibliography{%s}"
695 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
696 (mapcar 'expand-file-name
697 (split-string keyword ","))
703 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
704 (org-add-link-type "printbibliography"
705 (lambda (arg) (message "Nothing implemented for clicking here."))
706 (lambda (keyword desc format)
708 ((eq format 'org) (org-ref-get-org-bibliography))
709 ((eq format 'html) (org-ref-get-html-bibliography))
711 ;; write out the biblatex bibliography command
712 "\\printbibliography"))
716 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, ...
718 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
719 (org-add-link-type "bibliographystyle"
720 (lambda (arg) (message "Nothing implemented for clicking here."))
721 (lambda (keyword desc format)
724 ;; write out the latex bibliography command
725 (format "\\bibliographystyle{%s}" keyword)))))
728 *** Completion for bibliography link
731 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
732 (defun org-bibliography-complete-link (&optional arg)
733 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
735 (defun org-ref-insert-bibliography-link ()
736 "insert a bibliography with completion"
738 (insert (org-bibliography-complete-link)))
742 This is apparently used for biblatex.
743 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
744 (org-add-link-type "addbibresource"
745 ;; this code is run on clicking. The addbibresource
746 ;; may contain multiple files. this code finds the
747 ;; one you clicked on and opens it.
748 (lambda (link-string)
749 ;; get link-string boundaries
750 ;; we have to go to the beginning of the line, and then search forward
753 ;; object is the link you clicked on
754 (object (org-element-context))
756 (link-string-beginning)
760 (goto-char (org-element-property :begin object))
761 (search-forward link-string nil nil 1)
762 (setq link-string-beginning (match-beginning 0))
763 (setq link-string-end (match-end 0)))
765 ;; We set the reftex-default-addbibresource
766 ;; here. it should be a local variable only in
767 ;; the current buffer. We need this for using
768 ;; reftex to do citations.
769 (set (make-local-variable 'reftex-default-addbibresource)
770 (split-string (org-element-property :path object) ","))
772 ;; now if we have comma separated bibliographies
773 ;; we find the one clicked on. we want to
774 ;; search forward to next comma from point
776 (if (search-forward "," link-string-end 1 1)
777 (setq key-end (- (match-end 0) 1)) ; we found a match
778 (setq key-end (point)))) ; no comma found so take the point
779 ;; and backward to previous comma from point
781 (if (search-backward "," link-string-beginning 1 1)
782 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
783 (setq key-beginning (point)))) ; no match found
784 ;; save the key we clicked on.
785 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
786 (find-file bibfile))) ; open file on click
789 (lambda (keyword desc format)
791 ((eq format 'html) (format "")); no output for html
793 ;; write out the latex addbibresource command
794 (format "\\addbibresource{%s}" keyword)))))
799 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.
801 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
802 (defun org-ref-list-of-figures (&optional arg)
803 "Generate buffer with list of figures in them"
805 (save-excursion (widen)
806 (let* ((c-b (buffer-name))
809 (org-element-map (org-element-parse-buffer) 'link
811 "create a link for to the figure"
813 (and (string= (org-element-property :type link) "file")
815 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
816 (org-element-property :path link)))
819 (let* ((start (org-element-property :begin link))
820 (parent (car (cdr (org-element-property :parent link))))
821 (caption (caaar (plist-get parent :caption)))
822 (name (plist-get parent :name)))
825 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
826 c-b start counter (or name "") caption)
828 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
829 c-b start counter (or name "")))))))))
830 (switch-to-buffer "*List of Figures*")
831 (setq buffer-read-only nil)
834 (insert (mapconcat 'identity list-of-figures ""))
835 (setq buffer-read-only t)
836 (use-local-map (copy-keymap org-mode-map))
837 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
841 'org-ref-list-of-figures ; on click
842 (lambda (keyword desc format)
845 (format "\\listoffigures")))))
850 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
851 (defun org-ref-list-of-tables (&optional arg)
852 "Generate a buffer with a list of tables"
856 (let* ((c-b (buffer-name))
859 (org-element-map (org-element-parse-buffer 'element) 'table
861 "create a link for to the table"
863 (let ((start (org-element-property :begin table))
864 (name (org-element-property :name table))
865 (caption (caaar (org-element-property :caption table))))
868 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
869 c-b start counter (or name "") caption)
871 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
872 c-b start counter (or name ""))))))))
873 (switch-to-buffer "*List of Tables*")
874 (setq buffer-read-only nil)
877 (insert (mapconcat 'identity list-of-tables ""))
878 (setq buffer-read-only t)
879 (use-local-map (copy-keymap org-mode-map))
880 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
884 'org-ref-list-of-tables
885 (lambda (keyword desc format)
888 (format "\\listoftables")))))
892 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.
893 *************** TODO search tblnames, custom_ids and check for case sensitivity
896 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
898 (defun org-ref-count-labels (label)
899 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
900 ;; for tblname, it is not enough to get word boundary
901 ;; tab-little and tab-little-2 match then.
902 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
903 (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
904 ;; this is the org-format #+label:
905 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))
910 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
911 (message (format "%s occurences" (org-ref-count-labels label))))
912 (lambda (keyword desc format)
914 ((eq format 'html) (format "(<label>%s</label>)" path))
916 (format "\\label{%s}" keyword)))))
919 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.
921 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
922 (defun org-label-store-link ()
923 "store a link to a label. The output will be a ref to that label"
924 ;; First we have to make sure we are on a label link.
925 (let* ((object (org-element-context)))
926 (when (and (equal (org-element-type object) 'link)
927 (equal (org-element-property :type object) "label"))
928 (org-store-link-props
930 :link (concat "ref:" (org-element-property :path object))))
932 ;; Store link on table
933 (when (equal (org-element-type object) 'table)
934 (org-store-link-props
936 :link (concat "ref:" (org-element-property :name object))))
938 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
939 ;; store link on heading with custom_id
940 ; (when (and (equal (org-element-type object) 'headline)
941 ; (org-entry-get (point) "CUSTOM_ID"))
942 ; (org-store-link-props
944 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
946 ;; and to #+label: lines
947 (when (and (equal (org-element-type object) 'paragraph)
948 (org-element-property :name object))
949 (org-store-link-props
951 :link (concat "ref:" (org-element-property :name object))))
954 (add-hook 'org-store-link-functions 'org-label-store-link)
958 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.
960 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
962 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
966 "on clicking goto the label. Navigate back with C-c &"
968 ;; next search from beginning of the buffer
970 ;; it is possible you would not find the label if narrowing is in effect
977 (goto-char (point-min))
978 (re-search-forward (format "label:%s\\b" label) nil t))
982 (goto-char (point-min))
983 (re-search-forward (format "\\label{%s}" label) nil t))
985 ;; #+label: name org-definition
987 (goto-char (point-min))
988 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
992 (goto-char (point-min))
993 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
995 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
996 ;; you need [[#label]] links.
999 ; (goto-char (point-min))
1000 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1002 ;; we did not find anything, so go back to where we came
1003 (org-mark-ring-goto)
1004 (error "%s not found" label))
1006 (message "go back with (org-mark-ring-goto) `C-c &`"))
1008 (lambda (keyword desc format)
1010 ((eq format 'html) (format "(<ref>%s</ref>)" path))
1012 (format "\\ref{%s}" keyword)))))
1015 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.
1017 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1018 (defun org-ref-get-org-labels ()
1019 "find #+LABEL: labels"
1021 (goto-char (point-min))
1022 (let ((matches '()))
1023 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1024 (add-to-list 'matches (match-string-no-properties 1) t))
1028 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1029 (defun org-ref-get-custom-ids ()
1030 "return a list of custom_id properties in the buffer"
1031 (let ((results '()) custom_id)
1034 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1035 (when (not (null custom_id))
1036 (setq results (append results (list custom_id)))))))
1040 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
1041 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1042 (defun org-ref-get-latex-labels ()
1044 (goto-char (point-min))
1045 (let ((matches '()))
1046 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1047 (add-to-list 'matches (match-string-no-properties 1) t))
1051 Finally, we get the table names.
1053 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1054 (defun org-ref-get-tblnames ()
1055 (org-element-map (org-element-parse-buffer 'element) 'table
1057 (org-element-property :name table))))
1060 Now, we can put all the labels together which will give us a list of candidates.
1062 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1063 (defun org-ref-get-labels ()
1064 "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
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))
1072 (append matches (org-ref-get-org-labels) (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
1075 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.
1077 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1078 (defun org-ref-complete-link (&optional arg)
1079 "Completion function for ref links"
1081 (setq label (completing-read "label: " (org-ref-get-labels)))
1082 (format "ref:%s" label)))
1085 Alternatively, you may want to just call a function that inserts a link with completion:
1087 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1088 (defun org-ref-insert-ref-link ()
1090 (insert (org-ref-complete-link)))
1095 This refers to the page of a label in LaTeX.
1097 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1101 "on clicking goto the label. Navigate back with C-c &"
1102 (org-mark-ring-push)
1103 ;; next search from beginning of the buffer
1109 (goto-char (point-min))
1110 (re-search-forward (format "label:%s\\b" label) nil t))
1114 (goto-char (point-min))
1115 (re-search-forward (format "\\label{%s}" label) nil t))
1117 ;; #+label: name org-definition
1119 (goto-char (point-min))
1120 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1124 (goto-char (point-min))
1125 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1127 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1128 ;; you need [[#label]] links.
1131 ; (goto-char (point-min))
1132 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1134 ;; we did not find anything, so go back to where we came
1135 (org-mark-ring-goto)
1136 (error "%s not found" label))
1137 (message "go back with (org-mark-ring-goto) `C-c &`"))
1139 (lambda (keyword desc format)
1141 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1143 (format "\\pageref{%s}" keyword)))))
1146 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1147 (defun org-pageref-complete-link (&optional arg)
1148 "Completion function for ref links"
1150 (setq label (completing-read "label: " (org-ref-get-labels)))
1151 (format "ref:%s" label)))
1154 Alternatively, you may want to just call a function that inserts a link with completion:
1156 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1157 (defun org-pageref-insert-ref-link ()
1159 (insert (org-pageref-complete-link)))
1164 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.
1166 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1170 "on clicking goto the label. Navigate back with C-c &"
1171 (org-mark-ring-push)
1172 ;; next search from beginning of the buffer
1178 (goto-char (point-min))
1179 (re-search-forward (format "\\label{%s}" label) nil t))
1181 ;; we did not find anything, so go back to where we came
1182 (org-mark-ring-goto)
1183 (error "%s not found" label))
1184 (message "go back with (org-mark-ring-goto) `C-c &`"))
1186 (lambda (keyword desc format)
1188 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1190 (format "\\nameref{%s}" keyword)))))
1194 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1196 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1200 "on clicking goto the label. Navigate back with C-c &"
1201 (org-mark-ring-push)
1202 ;; next search from beginning of the buffer
1204 (goto-char (point-min))
1207 ;; search forward for the first match
1209 (re-search-forward (format "label:%s" label) nil t)
1211 (re-search-forward (format "\\label{%s}" label) nil t)
1212 ;; #+label: name org-definition
1213 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1214 (org-mark-ring-goto)
1215 (error "%s not found" label))
1216 (message "go back with (org-mark-ring-goto) `C-c &`"))
1218 (lambda (keyword desc format)
1220 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1222 (format "\\eqref{%s}" keyword)))))
1226 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.
1228 *** Implementing the click actions of cite
1230 **** Getting the key we clicked on
1231 The first thing we need is to get the bibtex key we clicked on.
1233 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1234 (defun org-ref-get-bibtex-key-under-cursor ()
1235 "returns key under the bibtex cursor. We search forward from
1236 point to get a comma, or the end of the link, and then backwards
1237 to get a comma, or the beginning of the link. that delimits the
1238 keyword we clicked on. We also strip the text properties."
1240 (let* ((object (org-element-context))
1241 (link-string (org-element-property :path object)))
1242 ;; you may click on the part before the citations. here we make
1243 ;; sure to move to the beginning so you get the first citation.
1245 (goto-char (org-element-property :begin object))
1246 (search-forward link-string (org-element-property :end object))
1247 (goto-char (match-beginning 0))
1248 ;; check if we clicked before the path and move as needed.
1249 (unless (< cp (point))
1252 (if (not (org-element-property :contents-begin object))
1253 ;; this means no description in the link
1255 ;; we need the link path start and end
1257 (goto-char (org-element-property :begin object))
1258 (search-forward link-string nil nil 1)
1259 (setq link-string-beginning (match-beginning 0))
1260 (setq link-string-end (match-end 0)))
1262 ;; The key is the text between commas, or the link boundaries
1264 (if (search-forward "," link-string-end t 1)
1265 (setq key-end (- (match-end 0) 1)) ; we found a match
1266 (setq key-end link-string-end))) ; no comma found so take the end
1267 ;; and backward to previous comma from point which defines the start character
1269 (if (search-backward "," link-string-beginning 1 1)
1270 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1271 (setq key-beginning link-string-beginning))) ; no match found
1272 ;; save the key we clicked on.
1273 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1274 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1276 ;; link with description. assume only one key
1280 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.
1282 **** Getting the bibliographies
1283 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1284 (defun org-ref-find-bibliography ()
1285 "find the bibliography in the buffer.
1286 This function sets and returns cite-bibliography-files, which is a list of files
1287 either from bibliography:f1.bib,f2.bib
1288 \bibliography{f1,f2}
1289 internal bibliographies
1291 falling back to what the user has set in org-ref-default-bibliography
1296 (goto-char (point-min))
1297 ;; look for a bibliography link
1298 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1299 (setq org-ref-bibliography-files
1300 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1301 (throw 'result org-ref-bibliography-files))
1304 ;; we did not find a bibliography link. now look for \bibliography
1305 (goto-char (point-min))
1306 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1307 ;; split, and add .bib to each file
1308 (setq org-ref-bibliography-files
1309 (mapcar (lambda (x) (concat x ".bib"))
1310 (mapcar 'org-ref-strip-string
1311 (split-string (match-string 1) ","))))
1312 (throw 'result org-ref-bibliography-files))
1314 ;; no bibliography found. maybe we need a biblatex addbibresource
1315 (goto-char (point-min))
1316 ;; look for a bibliography link
1317 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1318 (setq org-ref-bibliography-files
1319 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1320 (throw 'result org-ref-bibliography-files))
1322 ;; we did not find anything. use defaults
1323 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1325 ;; set reftex-default-bibliography so we can search
1326 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1327 org-ref-bibliography-files)
1330 **** Finding the bibliography file a key is in
1331 Now, we can see if an entry is in a file.
1333 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1334 (defun org-ref-key-in-file-p (key filename)
1335 "determine if the key is in the file"
1336 (interactive "skey: \nsFile: ")
1337 (save-current-buffer
1338 (let ((bibtex-files (list filename)))
1339 (bibtex-search-entry key t))))
1342 Finally, we want to know which file the key is in.
1344 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1345 (defun org-ref-get-bibtex-key-and-file (&optional key)
1346 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1348 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1351 (setq key (org-ref-get-bibtex-key-under-cursor)))
1352 (setq file (catch 'result
1353 (loop for file in org-ref-bibliography-files do
1354 (if (org-ref-key-in-file-p key (file-truename file))
1355 (throw 'result file)))))
1359 **** convenience functions to act on citation at point
1361 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1363 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.
1365 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1366 (defun org-ref-open-pdf-at-point ()
1367 "open the pdf for bibtex key under point if it exists"
1369 (let* ((results (org-ref-get-bibtex-key-and-file))
1371 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1372 (if (file-exists-p pdf-file)
1373 (org-open-file pdf-file)
1374 (message "no pdf found for %s" key))))
1377 (defun org-ref-open-url-at-point ()
1378 "open the url for bibtex key under point."
1380 (let* ((results (org-ref-get-bibtex-key-and-file))
1382 (bibfile (cdr results)))
1385 (insert-file-contents bibfile)
1386 (bibtex-search-entry key)
1387 ;; I like this better than bibtex-url which does not always find
1390 (let ((url (bibtex-autokey-get-field "url")))
1395 (let ((doi (bibtex-autokey-get-field "doi")))
1397 (if (string-match "^http" doi)
1399 (browse-url (format "http://dx.doi.org/%s" doi)))
1400 (throw 'done nil))))))))
1403 (defun org-ref-open-notes-at-point ()
1404 "open the notes for bibtex key under point."
1406 (let* ((results (org-ref-get-bibtex-key-and-file))
1408 (bibfile (cdr results)))
1411 (insert-file-contents bibfile)
1412 (bibtex-search-entry key)
1413 (org-ref-open-bibtex-notes)))))
1416 (defun org-ref-citation-at-point ()
1417 "give message of current citation at point"
1419 (let* ((cb (current-buffer))
1420 (results (org-ref-get-bibtex-key-and-file))
1422 (bibfile (cdr results)))
1423 (message "%s" (progn
1425 (insert-file-contents bibfile)
1426 (bibtex-search-entry key)
1427 (org-ref-bib-citation))))))
1430 (defun org-ref-open-citation-at-point ()
1431 "open bibtex file to key at point"
1433 (let* ((cb (current-buffer))
1434 (results (org-ref-get-bibtex-key-and-file))
1436 (bibfile (cdr results)))
1438 (bibtex-search-entry key)))
1441 **** the actual minibuffer menu
1442 Now, we create the menu. This is a rewrite of the cite action. This makes the function extendable by users.
1444 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1445 (defvar org-ref-cite-menu-funcs '()
1446 "Functions to run on cite click menu. Each entry is a list of (key menu-name function).
1447 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.")
1450 (defvar org-ref-user-cite-menu-funcs
1451 '(("C" "rossref" org-ref-crossref-at-point)
1452 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1453 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1454 "user-defined functions to run on bibtex key at point.")
1457 (defun org-ref-copy-entry-as-summary ()
1458 "Copy the bibtex entry for the citation at point as a summary."
1460 (save-window-excursion
1461 (org-ref-open-citation-at-point)
1462 (kill-new (org-ref-bib-citation))))
1465 (defun org-ref-copy-entry-at-point-to-file ()
1466 "Copy the bibtex entry for the citation at point to NEW-FILE.
1467 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."
1469 (let ((new-file (ido-completing-read
1471 (append org-ref-default-bibliography
1472 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1473 (key (org-ref-get-bibtex-key-under-cursor)))
1474 (save-window-excursion
1475 (org-ref-open-citation-at-point)
1476 (bibtex-copy-entry-as-kill))
1478 (let ((bibtex-files (list (file-truename new-file))))
1479 (if (assoc key (bibtex-global-key-alist))
1480 (message "That key already exists in %s" new-file)
1482 (save-window-excursion
1483 (find-file new-file)
1484 (goto-char (point-max))
1485 ;; make sure we are at the beginning of a line.
1486 (unless (looking-at "^") (insert "\n\n"))
1491 (defun org-ref-get-doi-at-point ()
1492 "Get doi for key at point."
1494 (let* ((results (org-ref-get-bibtex-key-and-file))
1496 (bibfile (cdr results))
1500 (insert-file-contents bibfile)
1501 (bibtex-search-entry key)
1502 (setq doi (bibtex-autokey-get-field "doi"))
1503 ;; in case doi is a url, remove the url part.
1504 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1507 ;; functions that operate on key at point for click menu
1508 (defun org-ref-wos-at-point ()
1509 "open the doi in wos for bibtex key under point."
1511 (doi-utils-wos (org-ref-get-doi-at-point)))
1514 (defun org-ref-wos-citing-at-point ()
1515 "open the doi in wos citing articles for bibtex key under point."
1517 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1520 (defun org-ref-wos-related-at-point ()
1521 "open the doi in wos related articles for bibtex key under point."
1523 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1526 (defun org-ref-google-scholar-at-point ()
1527 "open the doi in google scholar for bibtex key under point."
1529 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1532 (defun org-ref-pubmed-at-point ()
1533 "open the doi in pubmed for bibtex key under point."
1535 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1538 (defun org-ref-crossref-at-point ()
1539 "open the doi in crossref for bibtex key under point."
1541 (doi-utils-crossref (org-ref-get-doi-at-point)))
1544 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1545 "action when a cite link is clicked on.
1546 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."
1548 (let* ((results (org-ref-get-bibtex-key-and-file))
1550 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1551 (bibfile (cdr results))
1552 (url (save-excursion
1554 (insert-file-contents bibfile)
1555 (bibtex-search-entry key)
1556 (bibtex-autokey-get-field "url"))))
1557 (doi (save-excursion
1559 (insert-file-contents bibfile)
1560 (bibtex-search-entry key)
1561 ;; I like this better than bibtex-url which does not always find
1563 (bibtex-autokey-get-field "doi")))))
1565 (when (string= "" doi) (setq doi nil))
1566 (when (string= "" url) (setq url nil))
1567 (setq org-ref-cite-menu-funcs '())
1573 'org-ref-cite-menu-funcs
1574 '("o" "pen" org-ref-open-citation-at-point)))
1577 (when (file-exists-p pdf-file)
1579 'org-ref-cite-menu-funcs
1580 `("p" "df" ,org-ref-open-pdf-function) t))
1584 'org-ref-cite-menu-funcs
1585 '("n" "otes" org-ref-open-notes-at-point) t)
1590 'org-ref-cite-menu-funcs
1591 '("u" "rl" org-ref-open-url-at-point) t))
1596 'org-ref-cite-menu-funcs
1597 '("w" "os" org-ref-wos-at-point) t)
1600 'org-ref-cite-menu-funcs
1601 '("c" "iting" org-ref-wos-citing-at-point) t)
1604 'org-ref-cite-menu-funcs
1605 '("r" "elated" org-ref-wos-related-at-point) t)
1608 'org-ref-cite-menu-funcs
1609 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1612 'org-ref-cite-menu-funcs
1613 '("P" "ubmed" org-ref-pubmed-at-point) t))
1615 ;; add user functions
1616 (dolist (tup org-ref-user-cite-menu-funcs)
1618 'org-ref-cite-menu-funcs
1623 'org-ref-cite-menu-funcs
1624 '("q" "uit" (lambda ())) t)
1626 ;; now we make a menu
1627 ;; construct menu string as a message
1630 (let* ((results (org-ref-get-bibtex-key-and-file))
1632 (bibfile (cdr results)))
1635 (insert-file-contents bibfile)
1636 (bibtex-search-entry key)
1637 (org-ref-bib-citation))))
1641 (concat "[" (elt tup 0) "]"
1643 org-ref-cite-menu-funcs "")))
1645 (let* ((input (read-char-exclusive))
1647 (char-to-string input) org-ref-cite-menu-funcs)))
1648 ;; now run the function (2nd element in choice)
1657 : org-ref-cite-onclick-minibuffer-menu
1659 *** A function to format a cite link
1661 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.
1663 #+BEGIN_SRC emacs-lisp :tangle no
1664 ;(defun org-ref-cite-link-format (keyword desc format)
1666 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1667 ; ((eq format 'latex)
1668 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1669 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1673 *** The actual cite link
1674 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1676 #+BEGIN_SRC emacs-lisp :tangle no
1679 ; 'org-ref-cite-onclick-minibuffer-menu
1680 ; 'org-ref-cite-link-format)
1683 *** Automatic definition of the cite links
1684 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.
1686 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1687 (defmacro org-ref-make-completion-function (type)
1688 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1694 (let ((bibtex-files (org-ref-find-bibliography)))
1695 (bibtex-global-key-alist))))))
1698 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.
1700 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1701 (defmacro org-ref-make-format-function (type)
1702 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1707 (format "[[#%s][%s]]" key key))
1708 (org-ref-split-and-strip-string keyword) ","))
1715 (org-ref-split-and-strip-string keyword) ",") "]"))
1720 (format "<a href=\"#%s\">%s</a>" key key))
1721 (org-ref-split-and-strip-string keyword) ","))
1724 (if (string= (substring type -1) "s")
1725 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1726 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1727 (org-ref-split-and-strip-string keyword) ""))
1729 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1730 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1736 We create the links by mapping the function onto the list of defined link types.
1738 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1739 (defun org-ref-format-citation-description (desc)
1740 "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 ::."
1743 ((string-match "::" desc)
1744 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1745 (t (format "[%s]" desc))))
1747 (defun org-ref-define-citation-link (type &optional key)
1748 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1749 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1750 and the completion function."
1751 (interactive "sCitation Type: \ncKey: ")
1753 ;; create the formatting function
1754 (eval `(org-ref-make-format-function ,type))
1759 org-ref-cite-onclick-function
1760 (quote ,(intern (format "org-ref-format-%s" type)))))
1762 ;; create the completion function
1763 (eval `(org-ref-make-completion-function ,type))
1765 ;; store new type so it works with adding citations, which checks
1766 ;; for existence in this list
1767 (add-to-list 'org-ref-cite-types type)
1769 ;; and finally if a key is specified, we modify the reftex menu
1771 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1772 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1773 `((,key . ,(concat type ":%l")))))))
1775 ;; create all the link types and their completion functions
1776 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1779 *** org-ref-insert-cite-link
1780 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.
1782 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1783 (defun org-ref-insert-cite-link (alternative-cite)
1784 "Insert a default citation link using reftex. If you are on a link, it
1785 appends to the end of the link, otherwise, a new link is
1786 inserted. Use a prefix arg to get a menu of citation types."
1788 (org-ref-find-bibliography)
1789 (let* ((object (org-element-context))
1790 (link-string-beginning (org-element-property :begin object))
1791 (link-string-end (org-element-property :end object))
1792 (path (org-element-property :path object)))
1794 (if (not alternative-cite)
1797 ;; case where we are in a link
1798 ((and (equal (org-element-type object) 'link)
1799 (-contains? org-ref-cite-types (org-element-property :type object)))
1800 (goto-char link-string-end)
1801 ;; sometimes there are spaces at the end of the link
1802 ;; this code moves point pack until no spaces are there
1803 (while (looking-back " ") (backward-char))
1804 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1806 ;; We are next to a link, and we want to append
1809 (and (equal (org-element-type (org-element-context)) 'link)
1810 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1811 (while (looking-back " ") (backward-char))
1812 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1814 ;; insert fresh link
1817 (concat org-ref-default-citation-link
1819 (mapconcat 'identity (reftex-citation t) ",")))))
1821 ;; you pressed a C-u so we run this code
1825 cite:zhou-2004-first-lda-u,paier-2006-errat,boes-2015-estim-bulk
1829 : org-ref-insert-cite-link
1831 *** Completion in cite links
1832 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.
1834 #+BEGIN_SRC emacs-lisp :tangle no
1835 (defun org-cite-complete-link (&optional arg)
1836 "Completion function for cite links"
1838 org-ref-default-citation-link
1841 (let ((bibtex-files (org-ref-find-bibliography)))
1842 (bibtex-global-key-alist)))))
1845 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1847 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1848 (defun org-ref-insert-cite-with-completion (type)
1849 "Insert a cite link with completion"
1850 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1851 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1854 ** Storing links to a bibtex entry
1855 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.
1857 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1858 (defun org-ref-store-bibtex-entry-link ()
1859 "Save a citation link to the current bibtex entry. Saves in the default link type."
1861 (let ((link (concat org-ref-default-citation-link
1864 (bibtex-beginning-of-entry)
1865 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1866 (message "saved %s" link)
1867 (push (list link) org-stored-links)
1868 (car org-stored-links)))
1872 org-ref minimally supports index entries. To make an index in a file, you should put in the LaTeX header these lines
1875 #+LATEX_HEADER: \usepackage{makeidx}
1876 #+LATEX_HEADER: \makeindex
1879 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.
1882 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.
1887 [[index:hello!Sam@\textsl{Sam}]]
1888 [[index:Lin@\textbf{Lin}]]
1889 [[index:Joe|textit]]
1890 [[index:Lin@\textbf{Lin}]]
1891 [[index:Peter|see {hello}]]
1892 [[index:Jen|seealso{Jenny}]]
1894 index:encodings!input!cp850
1896 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1902 (lambda (path desc format)
1905 (format "\\index{%s}" path)))))
1907 ;; this will generate a temporary index of entries in the file.
1911 (let ((*index-links* '())
1912 (*initial-letters* '()))
1915 (org-element-map (org-element-parse-buffer) 'link
1917 (let ((type (nth 0 link))
1918 (plist (nth 1 link)))
1920 (when (equal (plist-get plist ':type) "index")
1923 (cons (plist-get plist :path)
1925 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
1927 (plist-get plist :begin) ;; position of link
1928 ;; grab a description
1930 (goto-char (plist-get plist :begin))
1931 (if (thing-at-point 'sentence)
1933 (replace-regexp-in-string
1934 "\n" "" (thing-at-point 'sentence))
1935 ;; or call it a link
1939 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
1941 ;; now first letters
1942 (dolist (link *index-links*)
1943 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
1945 ;; now create the index
1946 (switch-to-buffer (get-buffer-create "*index*"))
1949 (insert "#+TITLE: Index\n\n")
1950 (dolist (letter *initial-letters*)
1951 (insert (format "* %s\n" (upcase letter)))
1952 ;; now process the links
1955 (string= letter (substring (car (car *index-links*)) 0 1)))
1956 (let ((link (pop *index-links*)))
1957 (insert (format "%s %s\n\n" (car link) (cdr link))))))
1958 (switch-to-buffer "*index*")))
1960 (lambda (path desc format)
1963 (format "\\printindex")))))
1967 | 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*)) |
1968 | lambda | (path desc format) | (cond ((eq format (quote latex)) (format \printindex))) |
1971 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.
1973 #+LATEX_HEADER: \usepackage{glossaries}
1974 #+LATEX_HEADER: \makeglossaries
1976 And at the end of the document put \makeglossaries.
1978 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1981 nil ;; no follow action
1982 (lambda (path desc format)
1985 (format "\\newglossaryentry{%s}{%s}" path desc)))))
1991 nil ;; no follow action
1992 (lambda (path desc format)
1995 (format "\\gls{%s}" path)))))
2000 nil ;; no follow action
2001 (lambda (path desc format)
2004 (format "\\glspl{%s}" path)))))
2009 nil ;; no follow action
2010 (lambda (path desc format)
2013 (format "\\Gls{%s}" path)))))
2018 nil ;; no follow action
2019 (lambda (path desc format)
2022 (format "\\Glspl{%s}" path)))))
2028 ** create simple text citation from bibtex entry
2030 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2031 (defun org-ref-bib-citation ()
2032 "From a bibtex entry, create and return a simple citation string.
2033 This assumes you are in an article."
2035 (bibtex-beginning-of-entry)
2036 (let* ((cb (current-buffer))
2037 (bibtex-expand-strings t)
2038 (entry (loop for (key . value) in (bibtex-parse-entry t)
2039 collect (cons (downcase key) value)))
2040 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2041 (year (reftex-get-bib-field "year" entry))
2042 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2043 (key (reftex-get-bib-field "=key=" entry))
2044 (journal (reftex-get-bib-field "journal" entry))
2045 (volume (reftex-get-bib-field "volume" entry))
2046 (pages (reftex-get-bib-field "pages" entry))
2047 (doi (reftex-get-bib-field "doi" entry))
2048 (url (reftex-get-bib-field "url" entry))
2050 ;;authors, "title", Journal, vol(iss):pages (year).
2051 (format "%s, \"%s\", %s, %s:%s (%s)"
2052 author title journal volume pages year)))
2056 : org-ref-bib-citation
2059 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2060 (defun org-ref-bib-html-citation ()
2061 "from a bibtex entry, create and return a simple citation with html links."
2063 (bibtex-beginning-of-entry)
2064 (let* ((cb (current-buffer))
2065 (bibtex-expand-strings t)
2066 (entry (loop for (key . value) in (bibtex-parse-entry t)
2067 collect (cons (downcase key) value)))
2068 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2069 (year (reftex-get-bib-field "year" entry))
2070 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2071 (key (reftex-get-bib-field "=key=" entry))
2072 (journal (reftex-get-bib-field "journal" entry))
2073 (volume (reftex-get-bib-field "volume" entry))
2074 (pages (reftex-get-bib-field "pages" entry))
2075 (doi (reftex-get-bib-field "doi" entry))
2076 (url (reftex-get-bib-field "url" entry))
2078 ;;authors, "title", Journal, vol(iss):pages (year).
2079 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2080 author title journal volume pages year)
2081 (when url (format " <a href=\"%s\">link</a>" url))
2082 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2086 ** open pdf from bibtex
2087 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2088 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2089 (defun org-ref-open-bibtex-pdf ()
2090 "open pdf for a bibtex entry, if it exists. assumes point is in
2091 the entry of interest in the bibfile. but does not check that."
2094 (bibtex-beginning-of-entry)
2095 (let* ((bibtex-expand-strings t)
2096 (entry (bibtex-parse-entry t))
2097 (key (reftex-get-bib-field "=key=" entry))
2098 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2100 (if (file-exists-p pdf)
2101 (org-open-link-from-string (format "[[file:%s]]" pdf))
2105 ** open notes from bibtex
2106 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2108 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2109 (defun org-ref-open-bibtex-notes ()
2110 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
2112 I never did figure out how to use reftex to make this happen
2113 non-interactively. the reftex-format-citation function did not
2114 work perfectly; there were carriage returns in the strings, and
2115 it did not put the key where it needed to be. so, below I replace
2116 the carriage returns and extra spaces with a single space and
2117 construct the heading by hand."
2120 (bibtex-beginning-of-entry)
2121 (let* ((cb (current-buffer))
2122 (bibtex-expand-strings t)
2123 (entry (loop for (key . value) in (bibtex-parse-entry t)
2124 collect (cons (downcase key) value)))
2125 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2126 (year (reftex-get-bib-field "year" entry))
2127 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2128 (key (reftex-get-bib-field "=key=" entry))
2129 (journal (reftex-get-bib-field "journal" entry))
2130 (volume (reftex-get-bib-field "volume" entry))
2131 (pages (reftex-get-bib-field "pages" entry))
2132 (doi (reftex-get-bib-field "doi" entry))
2133 (url (reftex-get-bib-field "url" entry))
2136 ;; save key to clipboard to make saving pdf later easier by pasting.
2139 (kill-ring-save (point-min) (point-max)))
2141 ;; now look for entry in the notes file
2142 (if org-ref-bibliography-notes
2143 (find-file-other-window org-ref-bibliography-notes)
2144 (error "org-ref-bib-bibliography-notes is not set to anything"))
2146 (goto-char (point-min))
2147 ;; put new entry in notes if we don't find it.
2148 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2149 (funcall org-ref-open-notes-function)
2150 ;; no entry found, so add one
2151 (insert (format "\n** TODO %s - %s" year title))
2163 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2164 key author journal year volume pages doi url key org-ref-pdf-directory key))
2168 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2169 (defun org-ref-open-notes-from-reftex ()
2170 "Call reftex, and open notes for selected entry."
2172 (let ((bibtex-key )))
2174 ;; now look for entry in the notes file
2175 (if org-ref-bibliography-notes
2176 (find-file-other-window org-ref-bibliography-notes)
2177 (error "org-ref-bib-bibliography-notes is not set to anything"))
2179 (goto-char (point-min))
2181 (re-search-forward (format
2183 (first (reftex-citation t)) nil 'end))
2184 (funcall org-ref-open-notes-function))
2187 ** open url in browser from bibtex
2189 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
2191 + 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.
2193 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2194 (defun org-ref-open-in-browser ()
2195 "Open the bibtex entry at point in a browser using the url field or doi field"
2198 (bibtex-beginning-of-entry)
2200 (let ((url (bibtex-autokey-get-field "url")))
2205 (let ((doi (bibtex-autokey-get-field "doi")))
2207 (if (string-match "^http" doi)
2209 (browse-url (format "http://dx.doi.org/%s" doi)))
2211 (message "No url or doi found"))))
2215 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.
2217 *** function to upload bibtex to citeulike
2219 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2220 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2221 "with point in a bibtex entry get bibtex string and submit to citeulike.
2223 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2225 (message "uploading to citeulike")
2227 (bibtex-narrow-to-entry)
2228 (let ((startpos (point-min))
2229 (endpos (point-max))
2230 (bibtex-string (buffer-string))
2231 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2232 (with-temp-buffer (insert bibtex-string)
2233 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2236 *** The upload script
2237 Here is the python script for uploading.
2239 *************** TODO document how to get the cookies
2243 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
2245 import pickle, requests, sys
2248 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
2249 cookies = pickle.load(f)
2251 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
2253 bibtex = sys.stdin.read()
2255 data = {'pasted':bibtex,
2257 'tag_parsing':'simple',
2258 'strip_brackets':'no',
2259 'update_id':'bib-key',
2260 'btn_bibtex':'Import BibTeX file ...'}
2262 headers = {'content-type': 'multipart/form-data',
2263 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
2265 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
2269 ** Build a pdf from a bibtex file
2270 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.
2272 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2273 (defun org-ref-build-full-bibliography ()
2274 "build pdf of all bibtex entries, and open it."
2276 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2277 (bib-base (file-name-sans-extension bibfile))
2278 (texfile (concat bib-base ".tex"))
2279 (pdffile (concat bib-base ".pdf")))
2282 (insert (format "\\documentclass[12pt]{article}
2283 \\usepackage[version=3]{mhchem}
2285 \\usepackage[numbers]{natbib}
2286 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2290 \\bibliographystyle{unsrtnat}
2292 \\end{document}" bib-base))
2294 (shell-command (concat "pdflatex " bib-base))
2295 (shell-command (concat "bibtex " bib-base))
2296 (shell-command (concat "pdflatex " bib-base))
2297 (shell-command (concat "pdflatex " bib-base))
2298 (kill-buffer texfile)
2299 (org-open-file pdffile)
2303 ** Extract bibtex entries cited in an org-file
2304 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.
2306 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2307 (defun org-ref-extract-bibtex-entries ()
2308 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2310 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
2312 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2313 (tempname (make-temp-file "extract-bib"))
2314 (contents (buffer-string))
2315 (cb (current-buffer))
2316 basename texfile bibfile results)
2318 ;; open tempfile and insert org-buffer contents
2319 (find-file tempname)
2321 (setq basename (file-name-sans-extension
2322 (file-name-nondirectory buffer-file-name))
2323 texfile (concat tempname ".tex")
2324 bibfile (concat tempname ".bib"))
2326 ;; see if we have a bibliography, and insert the default one if not.
2328 (goto-char (point-min))
2329 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2330 (insert (format "\nbibliography:%s"
2331 (mapconcat 'identity reftex-default-bibliography ",")))))
2334 ;; get a latex file and extract the references
2335 (org-latex-export-to-latex)
2338 (reftex-create-bibtex-file bibfile)
2340 ;; save results of the references
2341 (setq results (buffer-string))
2343 ;; kill buffers. these are named by basename, not full path
2344 (kill-buffer (concat basename ".bib"))
2345 (kill-buffer (concat basename ".tex"))
2346 (kill-buffer basename)
2348 (delete-file bibfile)
2349 (delete-file texfile)
2350 (delete-file tempname)
2352 ;; Now back to the original org buffer and insert the results
2353 (switch-to-buffer cb)
2354 (when (not (string= "" results))
2356 (goto-char (point-max))
2358 (org-insert-heading)
2359 (insert (format " Bibtex entries
2361 ,#+BEGIN_SRC text :tangle %s
2363 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2366 ** Find bad cite links
2367 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.
2369 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2372 (defun index (substring list)
2373 "return the index of string in a list of strings"
2376 (dolist (arg list i)
2377 (if (string-match (concat "^" substring "$") arg)
2382 ;; return counter if found, otherwise return nil
2386 (defun org-ref-find-bad-citations ()
2387 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2389 Makes a new buffer with clickable links."
2391 ;; generate the list of bibtex-keys and cited keys
2392 (let* ((bibtex-files (org-ref-find-bibliography))
2393 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2394 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2395 (bad-citations '()))
2397 (org-element-map (org-element-parse-buffer) 'link
2399 (let ((plist (nth 1 link)))
2400 (when (equal (plist-get plist ':type) "cite")
2401 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2402 (when (not (index key bibtex-keys))
2403 (setq bad-citations (append bad-citations
2404 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2405 key (buffer-name)(plist-get plist ':begin)))))
2410 (switch-to-buffer-other-window "*Missing citations*")
2413 (insert "* List of bad cite links\n")
2414 (insert (mapconcat 'identity bad-citations ""))
2415 ;(setq buffer-read-only t)
2416 (use-local-map (copy-keymap org-mode-map))
2417 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2419 (when (get-buffer "*Missing citations*")
2420 (kill-buffer "*Missing citations*"))
2421 (message "No bad cite links found"))))
2424 ** Finding non-ascii characters
2425 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2427 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2428 (defun org-ref-find-non-ascii-characters ()
2429 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2431 (occur "[^[:ascii:]]"))
2434 ** Resort a bibtex entry
2435 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.
2437 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2438 (defun org-ref-sort-bibtex-entry ()
2439 "sort fields of entry in standard order and downcase them"
2441 (bibtex-beginning-of-entry)
2442 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2443 (entry (bibtex-parse-entry))
2446 (type (cdr (assoc "=type=" entry)))
2447 (key (cdr (assoc "=key=" entry))))
2449 ;; these are the fields we want to order that are in this entry
2450 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2451 ;; we do not want to reenter these fields
2452 (setq entry-fields (remove "=key=" entry-fields))
2453 (setq entry-fields (remove "=type=" entry-fields))
2455 ;;these are the other fields in the entry
2456 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2459 ;; right now we only resort articles
2460 ((string= (downcase type) "article")
2463 (concat "@article{" key ",\n"
2466 (when (member field entry-fields)
2467 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2470 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2472 (bibtex-find-entry key)
2474 (bibtex-clean-entry)
2478 ** Clean a bibtex entry
2479 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.
2480 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.
2481 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2482 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2483 "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"
2485 (bibtex-beginning-of-entry)
2487 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2488 (unless (string-match ",$" (thing-at-point 'line))
2492 ;; check for empty pages, and put eid or article id in its place
2493 (let ((entry (bibtex-parse-entry))
2494 (pages (bibtex-autokey-get-field "pages"))
2495 (year (bibtex-autokey-get-field "year"))
2496 (doi (bibtex-autokey-get-field "doi"))
2497 ;; The Journal of Chemical Physics uses eid
2498 (eid (bibtex-autokey-get-field "eid")))
2500 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2501 ;; but we only want the doi.
2502 (when (string-match "^http://dx.doi.org/" doi)
2503 (bibtex-beginning-of-entry)
2504 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2506 (bibtex-make-field "doi")
2508 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2510 ;; asap articles often set year to 0, which messes up key
2511 ;; generation. fix that.
2512 (when (string= "0" year)
2513 (bibtex-beginning-of-entry)
2514 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2516 (bibtex-make-field "year")
2518 (insert (read-string "Enter year: ")))
2520 ;; fix pages if they are empty if there is an eid to put there.
2521 (when (string= "-" pages)
2523 (bibtex-beginning-of-entry)
2524 ;; this seems like a clunky way to set the pages field.But I
2525 ;; cannot find a better way.
2526 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2528 (bibtex-make-field "pages")
2532 ;; replace naked & with \&
2534 (bibtex-narrow-to-entry)
2535 (bibtex-beginning-of-entry)
2536 (message "checking &")
2537 (replace-regexp " & " " \\\\& ")
2540 ;; generate a key, and if it duplicates an existing key, edit it.
2542 (let ((key (bibtex-generate-autokey)))
2544 ;; first we delete the existing key
2545 (bibtex-beginning-of-entry)
2546 (re-search-forward bibtex-entry-maybe-empty-head)
2547 (if (match-beginning bibtex-key-in-head)
2548 (delete-region (match-beginning bibtex-key-in-head)
2549 (match-end bibtex-key-in-head)))
2550 ;; check if the key is in the buffer
2551 (when (save-excursion
2552 (bibtex-search-entry key))
2554 (bibtex-search-entry key)
2555 (bibtex-copy-entry-as-kill)
2556 (switch-to-buffer-other-window "*duplicate entry*")
2558 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2561 (kill-new key))) ;; save key for pasting
2563 ;; run hooks. each of these operates on the entry with no arguments.
2564 ;; this did not work like i thought, it gives a symbolp error.
2565 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2570 org-ref-clean-bibtex-entry-hook)
2572 ;; sort fields within entry
2573 (org-ref-sort-bibtex-entry)
2574 ;; check for non-ascii characters
2575 (occur "[^[:ascii:]]")
2580 : org-ref-clean-bibtex-entry
2582 ** Sort the entries in a citation link by year
2583 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2585 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2586 (defun org-ref-get-citation-year (key)
2587 "get the year of an entry with key. Returns year as a string."
2589 (let* ((results (org-ref-get-bibtex-key-and-file key))
2590 (bibfile (cdr results)))
2592 (insert-file-contents bibfile)
2593 (bibtex-search-entry key nil 0)
2594 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2597 (defun org-ref-sort-citation-link ()
2598 "replace link at point with sorted link by year"
2600 (let* ((object (org-element-context))
2601 (type (org-element-property :type object))
2602 (begin (org-element-property :begin object))
2603 (end (org-element-property :end object))
2604 (link-string (org-element-property :path object))
2606 (setq keys (org-ref-split-and-strip-string link-string))
2607 (setq years (mapcar 'org-ref-get-citation-year keys))
2608 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2609 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2610 ;; now get the keys separated by commas
2611 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2612 ;; and replace the link with the sorted keys
2613 (cl--set-buffer-substring begin end (concat type ":" keys))))
2616 ** Sort entries in citation links with shift-arrow keys
2617 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2618 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2619 (defun org-ref-swap-keys (i j keys)
2620 "swap the keys in a list with index i and j"
2621 (let ((tempi (nth i keys)))
2622 (setf (nth i keys) (nth j keys))
2623 (setf (nth j keys) tempi))
2626 (defun org-ref-swap-citation-link (direction)
2627 "move citation at point in direction +1 is to the right, -1 to the left"
2629 (let* ((object (org-element-context))
2630 (type (org-element-property :type object))
2631 (begin (org-element-property :begin object))
2632 (end (org-element-property :end object))
2633 (link-string (org-element-property :path object))
2635 ;; We only want this to work on citation links
2636 (when (-contains? org-ref-cite-types type)
2637 (setq key (org-ref-get-bibtex-key-under-cursor))
2638 (setq keys (org-ref-split-and-strip-string link-string))
2639 (setq i (index key keys)) ;; defined in org-ref
2640 (if (> direction 0) ;; shift right
2641 (org-ref-swap-keys i (+ i 1) keys)
2642 (org-ref-swap-keys i (- i 1) keys))
2643 (setq keys (mapconcat 'identity keys ","))
2644 ;; and replace the link with the sorted keys
2645 (cl--set-buffer-substring begin end (concat type ":" keys " "))
2646 ;; now go forward to key so we can move with the key
2647 (re-search-forward key)
2648 (goto-char (match-beginning 0)))))
2650 ;; add hooks to make it work
2651 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2652 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2655 ** Lightweight messages about links
2656 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.
2658 ref:test citep:test label:rett
2660 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2661 (defun org-ref-get-label-context (label)
2662 "Return a string of context around a label."
2665 (goto-char (point-min))
2666 (when (re-search-forward
2667 (format "label:%s\\b" label) nil t)
2668 (throw 'result (buffer-substring
2677 (goto-char (point-min))
2678 (when (re-search-forward
2679 (format "\\label{%s}" label) nil t)
2680 (throw 'result (buffer-substring
2689 (goto-char (point-min))
2690 (when (re-search-forward
2691 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2692 (throw 'result (buffer-substring
2701 (goto-char (point-min))
2702 (when (re-search-forward
2703 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2704 (throw 'result (buffer-substring
2714 (defun org-ref-link-message ()
2715 "Print a minibuffer message about the link that point is on."
2717 (let* ((object (org-element-context))
2718 (type (org-element-property :type object)))
2722 ((-contains? org-ref-cite-types type)
2723 (message (org-ref-get-citation-string-at-point)))
2725 ;; message some context about the label we are referring to
2726 ((string= type "ref")
2727 (message (org-ref-get-label-context
2728 (org-element-property :path object))))
2730 ((string= type "eqref")
2731 (message (org-ref-get-label-context
2732 (org-element-property :path object))))
2734 ;; message the count
2735 ((string= type "label")
2736 (let ((count (org-ref-count-labels
2737 (org-element-property :path object))))
2738 ;; get plurality on occurrence correct
2740 (number-to-string count)
2742 (when (or (= count 0)
2747 (when org-ref-show-citation-on-enter
2748 (add-hook 'post-command-hook 'org-ref-link-message))
2752 I like convenience. Here are some aliases for faster typing.
2754 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2755 (defalias 'oro 'org-ref-open-citation-at-point)
2756 (defalias 'orc 'org-ref-citation-at-point)
2757 (defalias 'orp 'org-ref-open-pdf-at-point)
2758 (defalias 'oru 'org-ref-open-url-at-point)
2759 (defalias 'orn 'org-ref-open-notes-at-point)
2760 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2762 (defalias 'orib 'org-ref-insert-bibliography-link)
2763 (defalias 'oric 'org-ref-insert-cite-link)
2764 (defalias 'orir 'org-ref-insert-ref-link)
2765 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2767 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2770 [[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.
2772 1. Make the default action to insert selected keys.
2773 2. Make open entry second action
2774 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2775 (setq helm-source-bibtex
2776 '((name . "BibTeX entries")
2777 (init . helm-bibtex-init)
2778 (candidates . helm-bibtex-candidates)
2779 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
2780 (action . (("Insert citation" . helm-bibtex-insert-citation)
2781 ("Show entry" . helm-bibtex-show-entry)
2782 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
2783 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
2784 ("Insert reference" . helm-bibtex-insert-reference)
2785 ("Insert BibTeX key" . helm-bibtex-insert-key)
2786 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
2787 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
2788 ("Edit notes" . helm-bibtex-edit-notes)
2792 Now, let us define a function that inserts the cite links:
2793 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2794 (defun helm-bibtex-format-org-ref (keys)
2795 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
2796 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."
2797 (let* ((object (org-element-context)))
2799 ;; case where we are in a link
2800 ((and (equal (org-element-type object) 'link)
2803 (org-element-property :type object)))
2804 (goto-char (org-element-property :end object))
2805 ;; sometimes there are spaces at the end of the link
2806 ;; this code moves point pack until no spaces are there
2807 (while (looking-back " ") (backward-char))
2808 (insert (concat "," (mapconcat 'identity keys ","))))
2810 ;; We are next to a link, and we want to append
2813 (and (equal (org-element-type (org-element-context)) 'link)
2816 (org-element-property :type (org-element-context)))))
2817 (goto-char (org-element-property :end object))
2818 (while (looking-back " ") (backward-char))
2819 (insert (concat "," (mapconcat 'identity keys ","))))
2821 ;; insert fresh link
2824 (concat (if helm-current-prefix-arg
2825 (helm :sources `((name . "link types")
2826 (candidates . ,org-ref-cite-types)
2827 (action . (lambda (x) x))))
2828 org-ref-default-citation-link)
2830 (s-join "," keys))))))
2831 ;; return empty string for helm
2834 (setq helm-bibtex-format-citation-functions
2835 '((org-mode . helm-bibtex-format-org-ref)))
2837 (defun org-ref-helm-insert-cite-link ()
2838 "org-ref function to use helm on the bibliography defined in the org-file."
2840 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
2843 (require 'helm-bibtex)
2846 ** A helm click menu
2847 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.
2848 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2849 (defun org-ref-get-citation-string-at-point ()
2850 "Get a string of a formatted citation"
2852 (let* ((results (org-ref-get-bibtex-key-and-file))
2854 (bibfile (cdr results)))
2857 (insert-file-contents bibfile)
2858 (bibtex-search-entry key)
2859 (org-ref-bib-citation)))))
2861 (defun org-ref-cite-candidates ()
2862 "Generate the list of possible candidates for click actions on a cite link.
2863 Checks for pdf and doi, and add appropriate functions."
2865 (let* ((results (org-ref-get-bibtex-key-and-file))
2867 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
2868 (bibfile (cdr results))
2869 (url (save-excursion
2871 (insert-file-contents bibfile)
2872 (bibtex-search-entry key)
2873 (bibtex-autokey-get-field "url"))))
2874 (doi (save-excursion
2876 (insert-file-contents bibfile)
2877 (bibtex-search-entry key)
2878 ;; I like this better than bibtex-url which does not always find
2880 (bibtex-autokey-get-field "doi"))))
2881 (candidates `(("Quit" . org-ref-citation-at-point)
2882 ("Open bibtex entry" . org-ref-open-citation-at-point))))
2883 ;; for some reason, when there is no doi or url, they are returned as "". I
2884 ;; prefer nil so we correct this here.
2885 (when (string= doi "") (setq doi nil))
2886 (when (string= url "") (setq url nil))
2888 ;; Conditional pdf functions
2889 (if (file-exists-p pdf-file)
2892 '("Open pdf" . org-ref-open-pdf-at-point)
2896 '("Try to get pdf" . (lambda ()
2897 (save-window-excursion
2898 (org-ref-open-citation-at-point)
2899 (bibtex-beginning-of-entry)
2900 (doi-utils-get-bibtex-entry-pdf))))
2906 '("Open notes" . org-ref-open-notes-at-point)
2909 ;; conditional url and doi functions
2913 '("Open in browser" . org-ref-open-url-at-point)
2918 (add-to-list 'candidates x t))
2919 `(("WOS" . org-ref-wos-at-point)
2920 ("Related articles in WOS" . org-ref-wos-related-at-point)
2921 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
2922 ("Google Scholar" . org-ref-google-scholar-at-point)
2923 ("Pubmed" . org-ref-pubmed-at-point)
2924 ("Crossref" . org-ref-crossref-at-point)
2929 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
2934 '("Copy key to clipboard" . (lambda ()
2936 (car (org-ref-get-bibtex-key-and-file)))))
2941 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
2946 '("Email bibtex entry and pdf" . (lambda ()
2948 (org-ref-open-citation-at-point)
2949 (email-bibtex-entry))))
2951 ;; finally return a numbered list of the candidates
2953 for cell in candidates
2954 collect (cons (format "%2s. %s" i (car cell))
2958 (defvar org-ref-helm-user-candidates '()
2959 "List of user-defined candidates to act when clicking on a cite link.
2960 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.
2963 ;; example of adding your own function
2965 'org-ref-helm-user-candidates
2966 '("Example" . (lambda () (message-box "You did it!")))
2969 (defun org-ref-cite-click-helm (key)
2971 1. get name and candidates before entering helm because we need the org-buffer.
2972 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer."
2974 (let ((name (org-ref-get-citation-string-at-point))
2975 (candidates (org-ref-cite-candidates))
2976 (cb (current-buffer)))
2978 (helm :sources `(((name . ,name)
2979 (candidates . ,candidates)
2980 (action . (lambda (f)
2981 (switch-to-buffer cb)
2983 ((name . "User functions")
2984 (candidates . ,org-ref-helm-user-candidates)
2985 (action . (lambda (f)
2986 (switch-to-buffer cb)
2992 : org-ref-cite-click-helm
2995 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
3000 This code will tangle the elisp code out to org-ref.el and load it.
3002 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
3004 Alternatively you may use:
3006 [[elisp:(org-babel-load-file "org-ref.org")]]