#+TITLE: Org-ref - The best reference handling for org-mode #+AUTHOR: John Kitchin #+DATE: April 29, 2014 * Introduction This document is an experiment at creating a literate program to provide similar features as reftex for org-mode referencing. These features include: 1. using completion to create links 2. storing links to places, 3. Clickable links that do useful things 4. Exportable links to LaTeX 5. Utility functions for dealing with bibtex files and org-files ** Header #+BEGIN_SRC emacs-lisp :tangle org-ref.el ;;; org-ref.el --- setup bibliography, cite, ref and label org-mode links. ;; Copyright(C) 2014 John Kitchin ;; Author: John Kitchin ;; This file is not currently part of GNU Emacs. ;; This program is free software; you can redistribute it and/or ;; modify it under the terms of the GNU General Public License as ;; published by the Free Software Foundation; either version 2, or (at ;; your option) any later version. ;; This program is distributed in the hope that it will be useful, but ;; WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; General Public License for more details. ;; You should have received a copy of the GNU General Public License ;; along with this program ; see the file COPYING. If not, write to ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330, ;; Boston, MA 02111-1307, USA. ;;; Commentary: ;; ;; Lisp code to setup bibliography cite, ref and label org-mode links. also ;; sets up reftex and helm for org-mode citations. The links are clickable and ;; do things that are useful. You should really read org-ref.org for details. ;; ;; Package-Requires: ((dash) (helm) (helm-bibtex)) #+END_SRC ** requires The only external require is reftex-cite #+BEGIN_SRC emacs-lisp :tangle org-ref.el (require 'reftex-cite) (require 'dash) (require 'helm) (require 'helm-bibtex) #+END_SRC ** Custom variables 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defgroup org-ref nil "customization group for org-ref") (defcustom org-ref-bibliography-notes nil "filename to where you will put all your notes about an entry in the default bibliography." :type 'file :group 'org-ref) (defcustom org-ref-default-bibliography nil "list of bibtex files to search for. You should use full-paths for each file." :type '(repeat :tag "List of bibtex files" file) :group 'org-ref) (defcustom org-ref-pdf-directory nil "directory where pdfs are stored by key. put a trailing / in" :type 'directory :group 'org-ref) (defcustom org-ref-default-citation-link "cite" "The default type of citation link to use" :type 'string :group 'org-ref) (defcustom org-ref-insert-cite-key "C-c ]" "Keyboard shortcut to insert a citation." :type 'string :group 'org-ref) (defcustom org-ref-bibliography-entry-format '(("article" . "%a, %t, %j, %v(%n), %p (%y). link. doi.") ("book" . "%a, %t, %u (%y).") ("proceedings" . "%e, %t in %S, %u (%y).") ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)")) "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." :type 'string :group 'org-ref) (defcustom org-ref-open-notes-function (lambda () (org-show-entry) (show-branches) (show-children) (org-cycle '(64)) ;;(org-tree-to-indirect-buffer) (outline-previous-visible-heading 1) (recenter-top-bottom 0)) "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" :type 'function :group 'org-ref) (defcustom org-ref-open-pdf-function 'org-ref-open-pdf-at-point "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'." :type 'function :group 'org-ref) (defcustom org-ref-insert-cite-function 'org-ref-helm-insert-cite-link "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." :type 'function :group 'org-ref) (defcustom org-ref-cite-onclick-function 'org-ref-cite-click-helm "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." :type 'function :group 'org-ref) (defcustom org-ref-show-citation-on-enter t "If non-nil add a hook function to show the citation summary in the minibuffer just by putting the cursor in a link" :group 'org-ref) #+END_SRC 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defcustom org-ref-cite-types '("cite" "nocite" ;; the default latex cite commands ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf "citet" "citet*" "citep" "citep*" "citealt" "citealt*" "citealp" "citealp*" "citenum" "citetext" "citeauthor" "citeauthor*" "citeyear" "citeyear*" "Citet" "Citep" "Citealt" "Citealp" "Citeauthor" ;; biblatex commands ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf "Cite" "parencite" "Parencite" "footcite" "footcitetext" "textcite" "Textcite" "smartcite" "Smartcite" "cite*" "parencite*" "supercite" "autocite" "Autocite" "autocite*" "Autocite*" "Citeauthor*" "citetitle" "citetitle*" "citedate" "citedate*" "citeurl" "fullcite" "footfullcite" ;; "volcite" "Volcite" cannot support the syntax "notecite" "Notecite" "pnotecite" "Pnotecite" "fnotecite" ;; multicites. Very limited support for these. "cites" "Cites" "parencites" "Parencites" "footcites" "footcitetexts" "smartcites" "Smartcites" "textcites" "Textcites" "supercites" "autocites" "Autocites" ;; for the bibentry package "bibentry" ) "List of citation types known in org-ref" :type '(repeat :tag "List of citation types" string) :group 'org-ref) #+END_SRC We need a hook variable to store user-defined bibtex entry cleaning functions #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defcustom org-ref-clean-bibtex-entry-hook nil "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point." :group 'org-ref :type 'hook) #+END_SRC ** Program variables #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defvar org-ref-bibliography-files nil "variable to hold bibliography files to be searched") #+END_SRC ** org-mode / reftex setup 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (require 'reftex) (defun org-mode-reftex-setup () (and (buffer-file-name) (file-exists-p (buffer-file-name)) (global-auto-revert-mode t) ;; I do not remember why I put this next line in. It doesn't ;; work for org-files. Nothing very bad happens, but it gives ;; an annoying error. Commenting it out for now. ;(reftex-parse-all) ) (make-local-variable 'reftex-cite-format) (setq reftex-cite-format 'org) (define-key org-mode-map (kbd org-ref-insert-cite-key) org-ref-insert-cite-function)) (add-hook 'org-mode-hook 'org-mode-reftex-setup) (eval-after-load 'reftex-vars '(progn (add-to-list 'reftex-cite-format-builtin '(org "Org-mode citation" ((?\C-m . "cite:%l") ; default (?d . ",%l") ; for appending (?a . "autocite:%l") (?t . "citet:%l") (?T . "citet*:%l") (?p . "citep:%l") (?P . "citep*:%l") (?h . "citeauthor:%l") (?H . "citeauthor*:%l") (?y . "citeyear:%l") (?x . "citetext:%l") (?n . "nocite:%l") ))))) #+END_SRC 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. #+BEGIN_SRC emacs-lisp :tangle no ;; add new format (setf (nth 2 (assoc 'org reftex-cite-format-builtin)) (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l") (?z . "newcite:%l")))) #+END_SRC You can define a new citation link like this: #+BEGIN_SRC emacs-lisp :tangle no (org-ref-define-citation-link "citez" ?z) #+END_SRC * Links Most of this library is the creation of functional links to help with references and citations. ** General utilities 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-strip-string (string) "strip leading and trailing whitespace from the string" (replace-regexp-in-string (concat search-whitespace-regexp "$" ) "" (replace-regexp-in-string (concat "^" search-whitespace-regexp ) "" string))) #+END_SRC It is helpful to make the previous function operate on a list of strings here. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-split-and-strip-string (string) "split key-string and strip keys. Assumes the key-string is comma delimited" (mapcar 'org-ref-strip-string (split-string string ","))) #+END_SRC ** bibliography and bibliographystyle *** An html bibliography 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-reftex-get-bib-field (field entry &optional format) "similar to reftex-get-bib-field, but removes enclosing braces and quotes" (let ((result)) (setq result (reftex-get-bib-field field entry format)) (when (and (not (string= result "")) (string= "{" (substring result 0 1))) (setq result (substring result 1 -1))) (when (and (not (string= result "")) (string= "\"" (substring result 0 1))) (setq result (substring result 1 -1))) result)) (defun org-ref-reftex-format-citation (entry format) "return a formatted string for the bibtex entry (from bibtex-parse-entry) according to the format argument. The format is a string with these percent escapes. In the format, the following percent escapes will be expanded. %l The BibTeX label of the citation. %a List of author names, see also `reftex-cite-punctuation'. %2a Like %a, but abbreviate more than 2 authors like Jones et al. %A First author name only. %e Works like %a, but on list of editor names. (%2e and %E work a well) It is also possible to access all other BibTeX database fields: %b booktitle %c chapter %d edition %h howpublished %i institution %j journal %k key %m month %n number %o organization %p pages %P first page %r address %s school %u publisher %t title %v volume %y year %B booktitle, abbreviated %T title, abbreviated %U url %D doi %S series Usually, only %l is needed. The other stuff is mainly for the echo area display, and for (setq reftex-comment-citations t). %< as a special operator kills punctuation and space around it after the string has been formatted. A pair of square brackets indicates an optional argument, and RefTeX will prompt for the values of these arguments. Beware that all this only works with BibTeX database files. When citations are made from the \bibitems in an explicit thebibliography environment, only %l is available." ;; Format a citation from the info in the BibTeX ENTRY (unless (stringp format) (setq format "\\cite{%l}")) (if (and reftex-comment-citations (string-match "%l" reftex-cite-comment-format)) (error "reftex-cite-comment-format contains invalid %%l")) (while (string-match "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)" format) (let ((n (string-to-number (match-string 4 format))) (l (string-to-char (match-string 5 format))) rpl b e) (save-match-data (setq rpl (cond ((= l ?l) (concat (org-ref-reftex-get-bib-field "&key" entry) (if reftex-comment-citations reftex-cite-comment-format ""))) ((= l ?a) (reftex-format-names (reftex-get-bib-names "author" entry) (or n 2))) ((= l ?A) (car (reftex-get-bib-names "author" entry))) ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")) ((= l ?B) (reftex-abbreviate-title (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))) ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry)) ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry)) ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry)) ((= l ?e) (reftex-format-names (reftex-get-bib-names "editor" entry) (or n 2))) ((= l ?E) (car (reftex-get-bib-names "editor" entry))) ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry)) ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry)) ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry)) ((= l ?k) (org-ref-reftex-get-bib-field "key" entry)) ((= l ?m) (org-ref-reftex-get-bib-field "month" entry)) ((= l ?n) (org-ref-reftex-get-bib-field "number" entry)) ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry)) ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry)) ((= l ?P) (car (split-string (org-ref-reftex-get-bib-field "pages" entry) "[- .]+"))) ((= l ?s) (org-ref-reftex-get-bib-field "school" entry)) ((= l ?S) (org-ref-reftex-get-bib-field "series" entry)) ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry)) ((= l ?U) (org-ref-reftex-get-bib-field "url" entry)) ((= l ?r) (org-ref-reftex-get-bib-field "address" entry)) ;; strip enclosing brackets from title if they are there ((= l ?t) (org-ref-reftex-get-bib-field "title" entry)) ((= l ?T) (reftex-abbreviate-title (org-ref-reftex-get-bib-field "title" entry))) ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry)) ((= l ?y) (org-ref-reftex-get-bib-field "year" entry))))) (if (string= rpl "") (setq b (match-beginning 2) e (match-end 2)) (setq b (match-beginning 3) e (match-end 3))) (setq format (concat (substring format 0 b) rpl (substring format e))))) (while (string-match "%%" format) (setq format (replace-match "%" t t format))) (while (string-match "[ ,.;:]*%<" format) (setq format (replace-match "" t t format))) ;; also replace carriage returns, tabs, and multiple whitespaces (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format)) format) (defun org-ref-get-bibtex-entry-citation (key) "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'" (let ((org-ref-bibliography-files (org-ref-find-bibliography)) (file) (entry) (bibtex-entry) (entry-type) (format)) (setq file (catch 'result (loop for file in org-ref-bibliography-files do (if (org-ref-key-in-file-p key (file-truename file)) (throw 'result file) (message "%s not found in %s" key (file-truename file)))))) (with-temp-buffer (insert-file-contents file) (bibtex-search-entry key nil 0) (setq bibtex-entry (bibtex-parse-entry)) (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry)))) (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format))) (if format (setq entry (org-ref-reftex-format-citation bibtex-entry format)) (save-restriction (bibtex-narrow-to-entry) (setq entry (buffer-string))))) entry)) #+END_SRC #+RESULTS: : org-ref-reftex-format-citation Here is how to use the function. You call it with point in an entry in a bibtex file. #+BEGIN_SRC emacs-lisp :tangle no (let((org-ref-bibliography-entry-format "%a, %t, %j, %v(%n), %p (%y). link. doi.")) (org-ref-get-bibtex-entry-citation "armiento-2014-high")) #+END_SRC #+RESULTS: : Armiento, Kozinsky, Hautier, , Fornari \& Ceder, High-throughput screening of perovskite alloys for piezoelectric performance and thermodynamic stability, Phys. Rev. B, 89(), 134103 (2014). link. doi. I am not sure why full author names are not used. This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-bibtex-keys () "return a list of unique keys in the buffer." (let ((keys '())) (org-element-map (org-element-parse-buffer) 'link (lambda (link) (let ((plist (nth 1 link))) (when (-contains? org-ref-cite-types (plist-get plist ':type)) (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path))) (when (not (-contains? keys key)) (setq keys (append keys (list key))))))))) ;; Sort keys alphabetically (setq keys (cl-sort keys 'string-lessp :key 'downcase)) keys)) #+END_SRC This function gets the html for one entry. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-bibtex-entry-html (key) "returns an html string for the bibliography entry corresponding to key" (format "
  • [%s] %s
  • " key key (org-ref-get-bibtex-entry-citation key))) #+END_SRC Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-html-bibliography () "Create an html bibliography when there are keys" (let ((keys (org-ref-get-bibtex-keys))) (when keys (concat "

    Bibliography

    ")))) #+END_SRC 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. *** An org bibliography 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. First, we get the string for a single entry. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-bibtex-entry-org (key) "returns an org string for the bibliography entry corresponding to key" (let ((org-ref-bibliography-files (org-ref-find-bibliography)) (file) (entry) (bibtex-entry) (entry-type) (format)) (setq file (catch 'result (loop for file in org-ref-bibliography-files do (if (org-ref-key-in-file-p key (file-truename file)) (throw 'result file) (message "%s not found in %s" key (file-truename file)))))) (with-temp-buffer (insert-file-contents file) (bibtex-search-entry key nil 0) (setq entry (bibtex-parse-entry)) (format "** %s - %s :PROPERTIES: %s :END: " (org-ref-reftex-get-bib-field "author" entry) (org-ref-reftex-get-bib-field "title" entry) (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n" (mapconcat (lambda (element) (format " :%s: %s" (upcase (car element)) (cdr element))) entry "\n")))))) #+END_SRC Now, we loop over the keys, and combine all the entries into a bibliography. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-org-bibliography () "Create an org bibliography when there are keys" (let ((keys (org-ref-get-bibtex-keys))) (when keys (concat "* Bibliography " (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n") "\n")))) #+END_SRC *** An ascii bibliography This function gets the html for one entry. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-bibtex-entry-ascii (key) "returns an ascii string for the bibliography entry corresponding to key" (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key))) #+END_SRC Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-ascii-bibliography () "Create an html bibliography when there are keys" (let ((keys (org-ref-get-bibtex-keys))) (when keys (concat "Bibliography ============= " (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n") "\n")))) #+END_SRC *** the links 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "bibliography" ;; this code is run on clicking. The bibliography ;; may contain multiple files. this code finds the ;; one you clicked on and opens it. (lambda (link-string) ;; get link-string boundaries ;; we have to go to the beginning of the line, and then search forward (let* ((bibfile) ;; object is the link you clicked on (object (org-element-context)) (link-string-beginning) (link-string-end)) (save-excursion (goto-char (org-element-property :begin object)) (search-forward link-string nil nil 1) (setq link-string-beginning (match-beginning 0)) (setq link-string-end (match-end 0))) ;; We set the reftex-default-bibliography ;; here. it should be a local variable only in ;; the current buffer. We need this for using ;; reftex to do citations. (set (make-local-variable 'reftex-default-bibliography) (split-string (org-element-property :path object) ",")) ;; now if we have comma separated bibliographies ;; we find the one clicked on. we want to ;; search forward to next comma from point (save-excursion (if (search-forward "," link-string-end 1 1) (setq key-end (- (match-end 0) 1)) ; we found a match (setq key-end (point)))) ; no comma found so take the point ;; and backward to previous comma from point (save-excursion (if (search-backward "," link-string-beginning 1 1) (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match (setq key-beginning (point)))) ; no match found ;; save the key we clicked on. (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end))) (find-file bibfile))) ; open file on click ;; formatting code (lambda (keyword desc format) (cond ((eq format 'org) (org-ref-get-org-bibliography)) ((eq format 'ascii) (org-ref-get-ascii-bibliography)) ((eq format 'html) (org-ref-get-html-bibliography)) ((eq format 'latex) ;; write out the latex bibliography command (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity (mapcar 'expand-file-name (split-string keyword ",")) ","))))))) #+END_SRC 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. #+BEGIN_LaTeX \input{project-description.bbl} #+END_LaTeX 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "nobibliography" ;; this code is run on clicking. The bibliography ;; may contain multiple files. this code finds the ;; one you clicked on and opens it. (lambda (link-string) ;; get link-string boundaries ;; we have to go to the beginning of the line, and then search forward (let* ((bibfile) ;; object is the link you clicked on (object (org-element-context)) (link-string-beginning) (link-string-end)) (save-excursion (goto-char (org-element-property :begin object)) (search-forward link-string nil nil 1) (setq link-string-beginning (match-beginning 0)) (setq link-string-end (match-end 0))) ;; We set the reftex-default-bibliography ;; here. it should be a local variable only in ;; the current buffer. We need this for using ;; reftex to do citations. (set (make-local-variable 'reftex-default-bibliography) (split-string (org-element-property :path object) ",")) ;; now if we have comma separated bibliographies ;; we find the one clicked on. we want to ;; search forward to next comma from point (save-excursion (if (search-forward "," link-string-end 1 1) (setq key-end (- (match-end 0) 1)) ; we found a match (setq key-end (point)))) ; no comma found so take the point ;; and backward to previous comma from point (save-excursion (if (search-backward "," link-string-beginning 1 1) (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match (setq key-beginning (point)))) ; no match found ;; save the key we clicked on. (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end))) (find-file bibfile))) ; open file on click ;; formatting code (lambda (keyword desc format) (cond ((eq format 'org) (org-ref-get-org-bibliography)) ((eq format 'ascii) (org-ref-get-ascii-bibliography)) ((eq format 'html) (org-ref-get-html-bibliography)) ((eq format 'latex) ;; write out the latex bibliography command ; (format "{\\setbox0\\vbox{\\bibliography{%s}}}" ; (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity ; (mapcar 'expand-file-name ; (split-string keyword ",")) ; ","))) (format "\\nobibliography{%s}" (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity (mapcar 'expand-file-name (split-string keyword ",")) ","))) )))) #+END_SRC #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "printbibliography" (lambda (arg) (message "Nothing implemented for clicking here.")) (lambda (keyword desc format) (cond ((eq format 'org) (org-ref-get-org-bibliography)) ((eq format 'html) (org-ref-get-html-bibliography)) ((eq format 'latex) ;; write out the biblatex bibliography command "\\printbibliography")) )) #+END_SRC 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, ... #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "bibliographystyle" (lambda (arg) (message "Nothing implemented for clicking here.")) (lambda (keyword desc format) (cond ((eq format 'latex) ;; write out the latex bibliography command (format "\\bibliographystyle{%s}" keyword))))) #+END_SRC *** Completion for bibliography link It would be nice #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-bibliography-complete-link (&optional arg) (format "bibliography:%s" (read-file-name "enter file: " nil nil t))) (defun org-ref-insert-bibliography-link () "insert a bibliography with completion" (interactive) (insert (org-bibliography-complete-link))) #+END_SRC ** addbibresource This is apparently used for biblatex. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "addbibresource" ;; this code is run on clicking. The addbibresource ;; may contain multiple files. this code finds the ;; one you clicked on and opens it. (lambda (link-string) ;; get link-string boundaries ;; we have to go to the beginning of the line, and then search forward (let* ((bibfile) ;; object is the link you clicked on (object (org-element-context)) (link-string-beginning) (link-string-end)) (save-excursion (goto-char (org-element-property :begin object)) (search-forward link-string nil nil 1) (setq link-string-beginning (match-beginning 0)) (setq link-string-end (match-end 0))) ;; We set the reftex-default-addbibresource ;; here. it should be a local variable only in ;; the current buffer. We need this for using ;; reftex to do citations. (set (make-local-variable 'reftex-default-addbibresource) (split-string (org-element-property :path object) ",")) ;; now if we have comma separated bibliographies ;; we find the one clicked on. we want to ;; search forward to next comma from point (save-excursion (if (search-forward "," link-string-end 1 1) (setq key-end (- (match-end 0) 1)) ; we found a match (setq key-end (point)))) ; no comma found so take the point ;; and backward to previous comma from point (save-excursion (if (search-backward "," link-string-beginning 1 1) (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match (setq key-beginning (point)))) ; no match found ;; save the key we clicked on. (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end))) (find-file bibfile))) ; open file on click ;; formatting code (lambda (keyword desc format) (cond ((eq format 'html) (format "")); no output for html ((eq format 'latex) ;; write out the latex addbibresource command (format "\\addbibresource{%s}" keyword))))) #+END_SRC ** List of Figures 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-list-of-figures (&optional arg) "Generate buffer with list of figures in them" (interactive) (save-excursion (widen) (let* ((c-b (buffer-name)) (counter 0) (list-of-figures (org-element-map (org-element-parse-buffer) 'link (lambda (link) "create a link for to the figure" (when (and (string= (org-element-property :type link) "file") (string-match-p "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$" (org-element-property :path link))) (incf counter) (let* ((start (org-element-property :begin link)) (parent (car (cdr (org-element-property :parent link)))) (caption (caaar (plist-get parent :caption))) (name (plist-get parent :name))) (if caption (format "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n" c-b start counter (or name "") caption) (format "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n" c-b start counter (or name ""))))))))) (switch-to-buffer "*List of Figures*") (setq buffer-read-only nil) (org-mode) (erase-buffer) (insert (mapconcat 'identity list-of-figures "")) (setq buffer-read-only t) (use-local-map (copy-keymap org-mode-map)) (local-set-key "q" #'(lambda () (interactive) (kill-buffer)))))) (org-add-link-type "list-of-figures" 'org-ref-list-of-figures ; on click (lambda (keyword desc format) (cond ((eq format 'latex) (format "\\listoffigures"))))) #+END_SRC ** List of Tables #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-list-of-tables (&optional arg) "Generate a buffer with a list of tables" (interactive) (save-excursion (widen) (let* ((c-b (buffer-name)) (counter 0) (list-of-tables (org-element-map (org-element-parse-buffer 'element) 'table (lambda (table) "create a link for to the table" (incf counter) (let ((start (org-element-property :begin table)) (name (org-element-property :name table)) (caption (caaar (org-element-property :caption table)))) (if caption (format "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n" c-b start counter (or name "") caption) (format "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n" c-b start counter (or name "")))))))) (switch-to-buffer "*List of Tables*") (setq buffer-read-only nil) (org-mode) (erase-buffer) (insert (mapconcat 'identity list-of-tables "")) (setq buffer-read-only t) (use-local-map (copy-keymap org-mode-map)) (local-set-key "q" #'(lambda () (interactive) (kill-buffer)))))) (org-add-link-type "list-of-tables" 'org-ref-list-of-tables (lambda (keyword desc format) (cond ((eq format 'latex) (format "\\listoftables"))))) #+END_SRC ** label 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. *************** TODO search tblnames, custom_ids and check for case sensitivity *************** END #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-count-labels (label) (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t) ;; for tblname, it is not enough to get word boundary ;; tab-little and tab-little-2 match then. (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t) (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t) ;; this is the org-format #+label: (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t))) (org-add-link-type "label" (lambda (label) "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!" (message (format "%s occurences" (org-ref-count-labels label)))) (lambda (keyword desc format) (cond ((eq format 'html) (format "()" path)) ((eq format 'latex) (format "\\label{%s}" keyword))))) #+END_SRC 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-label-store-link () "store a link to a label. The output will be a ref to that label" ;; First we have to make sure we are on a label link. (let* ((object (org-element-context))) (when (and (equal (org-element-type object) 'link) (equal (org-element-property :type object) "label")) (org-store-link-props :type "ref" :link (concat "ref:" (org-element-property :path object)))) ;; Store link on table (when (equal (org-element-type object) 'table) (org-store-link-props :type "ref" :link (concat "ref:" (org-element-property :name object)))) ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID ;; store link on heading with custom_id ; (when (and (equal (org-element-type object) 'headline) ; (org-entry-get (point) "CUSTOM_ID")) ; (org-store-link-props ; :type "ref" ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID")))) ;; and to #+label: lines (when (and (equal (org-element-type object) 'paragraph) (org-element-property :name object)) (org-store-link-props :type "ref" :link (concat "ref:" (org-element-property :name object)))) )) (add-hook 'org-store-link-functions 'org-label-store-link) #+END_SRC ** ref 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. At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "ref" (lambda (label) "on clicking goto the label. Navigate back with C-c &" (org-mark-ring-push) ;; next search from beginning of the buffer ;; it is possible you would not find the label if narrowing is in effect (widen) (unless (or ;; our label links (progn (goto-char (point-min)) (re-search-forward (format "label:%s\\b" label) nil t)) ;; a latex label (progn (goto-char (point-min)) (re-search-forward (format "\\label{%s}" label) nil t)) ;; #+label: name org-definition (progn (goto-char (point-min)) (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)) ;; org tblname (progn (goto-char (point-min)) (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)) ;; Commented out because these ref links do not actually translate correctly in LaTeX. ;; you need [[#label]] links. ;; CUSTOM_ID ; (progn ; (goto-char (point-min)) ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t)) ) ;; we did not find anything, so go back to where we came (org-mark-ring-goto) (error "%s not found" label)) (org-show-entry) (message "go back with (org-mark-ring-goto) `C-c &`")) ;formatting (lambda (keyword desc format) (cond ((eq format 'html) (format "(%s)" path)) ((eq format 'latex) (format "\\ref{%s}" keyword))))) #+END_SRC 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-org-labels () "find #+LABEL: labels" (save-excursion (goto-char (point-min)) (let ((matches '())) (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t) (add-to-list 'matches (match-string-no-properties 1) t)) matches))) #+END_SRC #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-custom-ids () "return a list of custom_id properties in the buffer" (let ((results '()) custom_id) (org-map-entries (lambda () (let ((custom_id (org-entry-get (point) "CUSTOM_ID"))) (when (not (null custom_id)) (setq results (append results (list custom_id))))))) results)) #+END_SRC Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-latex-labels () (save-excursion (goto-char (point-min)) (let ((matches '())) (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t) (add-to-list 'matches (match-string-no-properties 1) t)) matches))) #+END_SRC Finally, we get the table names. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-tblnames () (org-element-map (org-element-parse-buffer 'element) 'table (lambda (table) (org-element-property :name table)))) #+END_SRC Now, we can put all the labels together which will give us a list of candidates. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-labels () "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links." (save-excursion (save-restriction (widen) (goto-char (point-min)) (let ((matches '())) (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t) (add-to-list 'matches (match-string-no-properties 1) t)) (append matches (org-ref-get-org-labels) (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids)))))) #+END_SRC 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-complete-link (&optional arg) "Completion function for ref links" (let ((label)) (setq label (completing-read "label: " (org-ref-get-labels))) (format "ref:%s" label))) #+END_SRC Alternatively, you may want to just call a function that inserts a link with completion: #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-insert-ref-link () (interactive) (insert (org-ref-complete-link))) #+END_SRC ** pageref This refers to the page of a label in LaTeX. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "pageref" (lambda (label) "on clicking goto the label. Navigate back with C-c &" (org-mark-ring-push) ;; next search from beginning of the buffer (widen) (unless (or ;; our label links (progn (goto-char (point-min)) (re-search-forward (format "label:%s\\b" label) nil t)) ;; a latex label (progn (goto-char (point-min)) (re-search-forward (format "\\label{%s}" label) nil t)) ;; #+label: name org-definition (progn (goto-char (point-min)) (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)) ;; org tblname (progn (goto-char (point-min)) (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)) ;; Commented out because these ref links do not actually translate correctly in LaTeX. ;; you need [[#label]] links. ;; CUSTOM_ID ; (progn ; (goto-char (point-min)) ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t)) ) ;; we did not find anything, so go back to where we came (org-mark-ring-goto) (error "%s not found" label)) (message "go back with (org-mark-ring-goto) `C-c &`")) ;formatting (lambda (keyword desc format) (cond ((eq format 'html) (format "(%s)" path)) ((eq format 'latex) (format "\\pageref{%s}" keyword))))) #+END_SRC #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-pageref-complete-link (&optional arg) "Completion function for ref links" (let ((label)) (setq label (completing-read "label: " (org-ref-get-labels))) (format "ref:%s" label))) #+END_SRC Alternatively, you may want to just call a function that inserts a link with completion: #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-pageref-insert-ref-link () (interactive) (insert (org-pageref-complete-link))) #+END_SRC ** nameref 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "nameref" (lambda (label) "on clicking goto the label. Navigate back with C-c &" (org-mark-ring-push) ;; next search from beginning of the buffer (widen) (unless (or ;; a latex label (progn (goto-char (point-min)) (re-search-forward (format "\\label{%s}" label) nil t)) ) ;; we did not find anything, so go back to where we came (org-mark-ring-goto) (error "%s not found" label)) (message "go back with (org-mark-ring-goto) `C-c &`")) ;formatting (lambda (keyword desc format) (cond ((eq format 'html) (format "(%s)" path)) ((eq format 'latex) (format "\\nameref{%s}" keyword))))) #+END_SRC ** eqref This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "eqref" (lambda (label) "on clicking goto the label. Navigate back with C-c &" (org-mark-ring-push) ;; next search from beginning of the buffer (widen) (goto-char (point-min)) (unless (or ;; search forward for the first match ;; our label links (re-search-forward (format "label:%s" label) nil t) ;; a latex label (re-search-forward (format "\\label{%s}" label) nil t) ;; #+label: name org-definition (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)) (org-mark-ring-goto) (error "%s not found" label)) (message "go back with (org-mark-ring-goto) `C-c &`")) ;formatting (lambda (keyword desc format) (cond ((eq format 'html) (format "(%s)" path)) ((eq format 'latex) (format "\\eqref{%s}" keyword))))) #+END_SRC ** cite 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. *** Implementing the click actions of cite **** Getting the key we clicked on The first thing we need is to get the bibtex key we clicked on. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-bibtex-key-under-cursor () "returns key under the bibtex cursor. We search forward from point to get a comma, or the end of the link, and then backwards to get a comma, or the beginning of the link. that delimits the keyword we clicked on. We also strip the text properties." (interactive) (let* ((object (org-element-context)) (link-string (org-element-property :path object))) ;; you may click on the part before the citations. here we make ;; sure to move to the beginning so you get the first citation. (let ((cp (point))) (goto-char (org-element-property :begin object)) (search-forward link-string (org-element-property :end object)) (goto-char (match-beginning 0)) ;; check if we clicked before the path and move as needed. (unless (< cp (point)) (goto-char cp))) (if (not (org-element-property :contents-begin object)) ;; this means no description in the link (progn ;; we need the link path start and end (save-excursion (goto-char (org-element-property :begin object)) (search-forward link-string nil nil 1) (setq link-string-beginning (match-beginning 0)) (setq link-string-end (match-end 0))) ;; The key is the text between commas, or the link boundaries (save-excursion (if (search-forward "," link-string-end t 1) (setq key-end (- (match-end 0) 1)) ; we found a match (setq key-end link-string-end))) ; no comma found so take the end ;; and backward to previous comma from point which defines the start character (save-excursion (if (search-backward "," link-string-beginning 1 1) (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match (setq key-beginning link-string-beginning))) ; no match found ;; save the key we clicked on. (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end))) (set-text-properties 0 (length bibtex-key) nil bibtex-key) bibtex-key) ;; link with description. assume only one key link-string))) #+END_SRC 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. **** Getting the bibliographies #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-find-bibliography () "find the bibliography in the buffer. This function sets and returns cite-bibliography-files, which is a list of files either from bibliography:f1.bib,f2.bib \bibliography{f1,f2} internal bibliographies falling back to what the user has set in org-ref-default-bibliography " (interactive) (catch 'result (save-excursion (goto-char (point-min)) ;; look for a bibliography link (when (re-search-forward "\\%s" key key) (org-ref-split-and-strip-string keyword) ","))) ; ((eq format 'latex) ; (concat "\\cite" (when desc (format "[%s]" desc)) "{" ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",") ; "}")))) #+END_SRC *** The actual cite link Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory. #+BEGIN_SRC emacs-lisp :tangle no ;(org-add-link-type ; "cite" ; 'org-ref-cite-onclick-minibuffer-menu ; 'org-ref-cite-link-format) #+END_SRC *** Automatic definition of the cite links 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defmacro org-ref-make-completion-function (type) `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg) (interactive) (format "%s:%s" ,type (completing-read "bibtex key: " (let ((bibtex-files (org-ref-find-bibliography))) (bibtex-global-key-alist)))))) #+END_SRC 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defmacro org-ref-make-format-function (type) `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format) (cond ((eq format 'org) (mapconcat (lambda (key) (format "[[#%s][%s]]" key key)) (org-ref-split-and-strip-string keyword) ",")) ((eq format 'ascii) (concat "[" (mapconcat (lambda (key) (format "%s" key)) (org-ref-split-and-strip-string keyword) ",") "]")) ((eq format 'html) (mapconcat (lambda (key) (format "%s" key key)) (org-ref-split-and-strip-string keyword) ",")) ((eq format 'latex) (if (string= (substring type -1) "s") ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}... (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key)) (org-ref-split-and-strip-string keyword) "")) ;; bibtex format (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{" (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",") "}")))))) #+END_SRC We create the links by mapping the function onto the list of defined link types. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-format-citation-description (desc) "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 ::." (interactive) (cond ((string-match "::" desc) (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results))) (t (format "[%s]" desc)))) (defun org-ref-define-citation-link (type &optional key) "add a citation link for org-ref. With optional key, set the reftex binding. For example: (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z, and the completion function." (interactive "sCitation Type: \ncKey: ") ;; create the formatting function (eval `(org-ref-make-format-function ,type)) (eval-expression `(org-add-link-type ,type org-ref-cite-onclick-function (quote ,(intern (format "org-ref-format-%s" type))))) ;; create the completion function (eval `(org-ref-make-completion-function ,type)) ;; store new type so it works with adding citations, which checks ;; for existence in this list (add-to-list 'org-ref-cite-types type) ;; and finally if a key is specified, we modify the reftex menu (when key (setf (nth 2 (assoc 'org reftex-cite-format-builtin)) (append (nth 2 (assoc 'org reftex-cite-format-builtin)) `((,key . ,(concat type ":%l"))))))) ;; create all the link types and their completion functions (mapcar 'org-ref-define-citation-link org-ref-cite-types) #+END_SRC *** org-ref-insert-cite-link 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-insert-cite-link (alternative-cite) "Insert a default citation link using reftex. If you are on a link, it appends to the end of the link, otherwise, a new link is inserted. Use a prefix arg to get a menu of citation types." (interactive "P") (org-ref-find-bibliography) (let* ((object (org-element-context)) (link-string-beginning (org-element-property :begin object)) (link-string-end (org-element-property :end object)) (path (org-element-property :path object))) (if (not alternative-cite) (cond ;; case where we are in a link ((and (equal (org-element-type object) 'link) (-contains? org-ref-cite-types (org-element-property :type object))) (goto-char link-string-end) ;; sometimes there are spaces at the end of the link ;; this code moves point pack until no spaces are there (while (looking-back " ") (backward-char)) (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ",")))) ;; We are next to a link, and we want to append ((save-excursion (backward-char) (and (equal (org-element-type (org-element-context)) 'link) (-contains? org-ref-cite-types (org-element-property :type (org-element-context))))) (while (looking-back " ") (backward-char)) (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ",")))) ;; insert fresh link (t (insert (concat org-ref-default-citation-link ":" (mapconcat 'identity (reftex-citation t) ","))))) ;; you pressed a C-u so we run this code (reftex-citation))) ) #+END_SRC cite:zhou-2004-first-lda-u,paier-2006-errat,boes-2015-estim-bulk #+RESULTS: : org-ref-insert-cite-link *** Completion in cite links 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. #+BEGIN_SRC emacs-lisp :tangle no (defun org-cite-complete-link (&optional arg) "Completion function for cite links" (format "%s:%s" org-ref-default-citation-link (completing-read "bibtex key: " (let ((bibtex-files (org-ref-find-bibliography))) (bibtex-global-key-alist))))) #+END_SRC Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-insert-cite-with-completion (type) "Insert a cite link with completion" (interactive (list (ido-completing-read "Type: " org-ref-cite-types))) (insert (funcall (intern (format "org-%s-complete-link" type))))) #+END_SRC ** Storing links to a bibtex entry 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-store-bibtex-entry-link () "Save a citation link to the current bibtex entry. Saves in the default link type." (interactive) (let ((link (concat org-ref-default-citation-link ":" (save-excursion (bibtex-beginning-of-entry) (reftex-get-bib-field "=key=" (bibtex-parse-entry)))))) (message "saved %s" link) (push (list link) org-stored-links) (car org-stored-links))) #+END_SRC ** Index entries org-ref minimally supports index entries. To make an index in a file, you should put in the LaTeX header these lines #+LATEX_HEADER: \usepackage{makeidx} #+LATEX_HEADER: \makeindex 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. 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. index:hello index:hello!Peter [[index:hello!Sam@\textsl{Sam}]] [[index:Lin@\textbf{Lin}]] [[index:Joe|textit]] [[index:Lin@\textbf{Lin}]] [[index:Peter|see {hello}]] [[index:Jen|seealso{Jenny}]] index:encodings!input!cp850 #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "index" (lambda (path) (occur path)) (lambda (path desc format) (cond ((eq format 'latex) (format "\\index{%s}" path))))) ;; this will generate a temporary index of entries in the file. (org-add-link-type "printindex" (lambda (path) (let ((*index-links* '()) (*initial-letters* '())) ;; get links (org-element-map (org-element-parse-buffer) 'link (lambda (link) (let ((type (nth 0 link)) (plist (nth 1 link))) (when (equal (plist-get plist ':type) "index") (add-to-list '*index-links* (cons (plist-get plist :path) (format "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]" (current-buffer) (plist-get plist :begin) ;; position of link ;; grab a description (save-excursion (goto-char (plist-get plist :begin)) (if (thing-at-point 'sentence) ;; get a sentence (replace-regexp-in-string "\n" "" (thing-at-point 'sentence)) ;; or call it a link "link"))))))))) ;; sort the links (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car)) ;; now first letters (dolist (link *index-links*) (add-to-list '*initial-letters* (substring (car link) 0 1) t)) ;; now create the index (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))) ;; now process the links (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*"))) ;; formatting (lambda (path desc format) (cond ((eq format 'latex) (format "\\printindex"))))) #+END_SRC #+RESULTS: | 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*)) | | lambda | (path desc format) | (cond ((eq format (quote latex)) (format \printindex))) | ** Glossary 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. #+LATEX_HEADER: \usepackage{glossaries} #+LATEX_HEADER: \makeglossaries And at the end of the document put \makeglossaries. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (org-add-link-type "newglossaryentry" nil ;; no follow action (lambda (path desc format) (cond ((eq format 'latex) (format "\\newglossaryentry{%s}{%s}" path desc))))) ;; link to entry (org-add-link-type "gls" nil ;; no follow action (lambda (path desc format) (cond ((eq format 'latex) (format "\\gls{%s}" path))))) ;; plural (org-add-link-type "glspl" nil ;; no follow action (lambda (path desc format) (cond ((eq format 'latex) (format "\\glspl{%s}" path))))) ;; capitalized link (org-add-link-type "Gls" nil ;; no follow action (lambda (path desc format) (cond ((eq format 'latex) (format "\\Gls{%s}" path))))) ;; capitalized link (org-add-link-type "Glspl" nil ;; no follow action (lambda (path desc format) (cond ((eq format 'latex) (format "\\Glspl{%s}" path))))) #+END_SRC * Utilities ** create simple text citation from bibtex entry #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-bib-citation () "From a bibtex entry, create and return a simple citation string. This assumes you are in an article." (bibtex-beginning-of-entry) (let* ((cb (current-buffer)) (bibtex-expand-strings t) (entry (loop for (key . value) in (bibtex-parse-entry t) collect (cons (downcase key) value))) (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry))) (year (reftex-get-bib-field "year" entry)) (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry))) (key (reftex-get-bib-field "=key=" entry)) (journal (reftex-get-bib-field "journal" entry)) (volume (reftex-get-bib-field "volume" entry)) (pages (reftex-get-bib-field "pages" entry)) (doi (reftex-get-bib-field "doi" entry)) (url (reftex-get-bib-field "url" entry)) ) ;;authors, "title", Journal, vol(iss):pages (year). (format "%s, \"%s\", %s, %s:%s (%s)" author title journal volume pages year))) #+END_SRC #+RESULTS: : org-ref-bib-citation #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-bib-html-citation () "from a bibtex entry, create and return a simple citation with html links." (bibtex-beginning-of-entry) (let* ((cb (current-buffer)) (bibtex-expand-strings t) (entry (loop for (key . value) in (bibtex-parse-entry t) collect (cons (downcase key) value))) (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry))) (year (reftex-get-bib-field "year" entry)) (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry))) (key (reftex-get-bib-field "=key=" entry)) (journal (reftex-get-bib-field "journal" entry)) (volume (reftex-get-bib-field "volume" entry)) (pages (reftex-get-bib-field "pages" entry)) (doi (reftex-get-bib-field "doi" entry)) (url (reftex-get-bib-field "url" entry)) ) ;;authors, "title", Journal, vol(iss):pages (year). (concat (format "%s, \"%s\", %s, %s:%s (%s)." author title journal volume pages year) (when url (format " link" url)) (when doi (format " doi" doi))) )) #+END_SRC ** open pdf from bibtex We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]]. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-open-bibtex-pdf () "open pdf for a bibtex entry, if it exists. assumes point is in the entry of interest in the bibfile. but does not check that." (interactive) (save-excursion (bibtex-beginning-of-entry) (let* ((bibtex-expand-strings t) (entry (bibtex-parse-entry t)) (key (reftex-get-bib-field "=key=" entry)) (pdf (format (concat org-ref-pdf-directory "%s.pdf") key))) (message "%s" pdf) (if (file-exists-p pdf) (org-open-link-from-string (format "[[file:%s]]" pdf)) (ding))))) #+END_SRC ** open notes from bibtex We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]]. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-open-bibtex-notes () "from a bibtex entry, open the notes if they exist, and create a heading if they do not. I never did figure out how to use reftex to make this happen non-interactively. the reftex-format-citation function did not work perfectly; there were carriage returns in the strings, and it did not put the key where it needed to be. so, below I replace the carriage returns and extra spaces with a single space and construct the heading by hand." (interactive) (bibtex-beginning-of-entry) (let* ((cb (current-buffer)) (bibtex-expand-strings t) (entry (loop for (key . value) in (bibtex-parse-entry t) collect (cons (downcase key) value))) (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry))) (year (reftex-get-bib-field "year" entry)) (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry))) (key (reftex-get-bib-field "=key=" entry)) (journal (reftex-get-bib-field "journal" entry)) (volume (reftex-get-bib-field "volume" entry)) (pages (reftex-get-bib-field "pages" entry)) (doi (reftex-get-bib-field "doi" entry)) (url (reftex-get-bib-field "url" entry)) ) ;; save key to clipboard to make saving pdf later easier by pasting. (with-temp-buffer (insert key) (kill-ring-save (point-min) (point-max))) ;; now look for entry in the notes file (if org-ref-bibliography-notes (find-file-other-window org-ref-bibliography-notes) (error "org-ref-bib-bibliography-notes is not set to anything")) (goto-char (point-min)) ;; put new entry in notes if we don't find it. (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end) (funcall org-ref-open-notes-function) ;; no entry found, so add one (insert (format "\n** TODO %s - %s" year title)) (insert (format" :PROPERTIES: :Custom_ID: %s :AUTHOR: %s :JOURNAL: %s :YEAR: %s :VOLUME: %s :PAGES: %s :DOI: %s :URL: %s :END: [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n" key author journal year volume pages doi url key org-ref-pdf-directory key)) (save-buffer)))) #+END_SRC #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-open-notes-from-reftex () "Call reftex, and open notes for selected entry." (interactive) (let ((bibtex-key ))) ;; now look for entry in the notes file (if org-ref-bibliography-notes (find-file-other-window org-ref-bibliography-notes) (error "org-ref-bib-bibliography-notes is not set to anything")) (goto-char (point-min)) (re-search-forward (format ":Custom_ID: %s$" (first (reftex-citation t)) nil 'end)) (funcall org-ref-open-notes-function)) #+END_SRC ** open url in browser from bibtex We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]]. + 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-open-in-browser () "Open the bibtex entry at point in a browser using the url field or doi field" (interactive) (save-excursion (bibtex-beginning-of-entry) (catch 'done (let ((url (bibtex-autokey-get-field "url"))) (when url (browse-url url) (throw 'done nil))) (let ((doi (bibtex-autokey-get-field "doi"))) (when doi (if (string-match "^http" doi) (browse-url doi) (browse-url (format "http://dx.doi.org/%s" doi))) (throw 'done nil))) (message "No url or doi found")))) #+END_SRC ** citeulike 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. *** function to upload bibtex to citeulike #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-upload-bibtex-entry-to-citeulike () "with point in a bibtex entry get bibtex string and submit to citeulike. Relies on the python script /upload_bibtex_citeulike.py being in the user directory." (interactive) (message "uploading to citeulike") (save-restriction (bibtex-narrow-to-entry) (let ((startpos (point-min)) (endpos (point-max)) (bibtex-string (buffer-string)) (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&"))) (with-temp-buffer (insert bibtex-string) (shell-command-on-region (point-min) (point-max) script t nil nil t))))) #+END_SRC *** The upload script Here is the python script for uploading. *************** TODO document how to get the cookies *************** END #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py #!python import pickle, requests, sys # reload cookies with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f: cookies = pickle.load(f) url = 'http://www.citeulike.org/profile/jkitchin/import_do' bibtex = sys.stdin.read() data = {'pasted':bibtex, 'to_read':2, 'tag_parsing':'simple', 'strip_brackets':'no', 'update_id':'bib-key', 'btn_bibtex':'Import BibTeX file ...'} headers = {'content-type': 'multipart/form-data', 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'} r = requests.post(url, headers=headers, data=data, cookies=cookies, files={}) print r #+END_SRC ** Build a pdf from a bibtex file 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-build-full-bibliography () "build pdf of all bibtex entries, and open it." (interactive) (let* ((bibfile (file-name-nondirectory (buffer-file-name))) (bib-base (file-name-sans-extension bibfile)) (texfile (concat bib-base ".tex")) (pdffile (concat bib-base ".pdf"))) (find-file texfile) (erase-buffer) (insert (format "\\documentclass[12pt]{article} \\usepackage[version=3]{mhchem} \\usepackage{url} \\usepackage[numbers]{natbib} \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref} \\usepackage{doi} \\begin{document} \\nocite{*} \\bibliographystyle{unsrtnat} \\bibliography{%s} \\end{document}" bib-base)) (save-buffer) (shell-command (concat "pdflatex " bib-base)) (shell-command (concat "bibtex " bib-base)) (shell-command (concat "pdflatex " bib-base)) (shell-command (concat "pdflatex " bib-base)) (kill-buffer texfile) (org-open-file pdffile) )) #+END_SRC ** Extract bibtex entries cited in an org-file 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-extract-bibtex-entries () "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer. If no bibliography is in the buffer the `reftex-default-bibliography' is used." (interactive) (let* ((temporary-file-directory (file-name-directory (buffer-file-name))) (tempname (make-temp-file "extract-bib")) (contents (buffer-string)) (cb (current-buffer)) basename texfile bibfile results) ;; open tempfile and insert org-buffer contents (find-file tempname) (insert contents) (setq basename (file-name-sans-extension (file-name-nondirectory buffer-file-name)) texfile (concat tempname ".tex") bibfile (concat tempname ".bib")) ;; see if we have a bibliography, and insert the default one if not. (save-excursion (goto-char (point-min)) (unless (re-search-forward "^bibliography:" (point-max) 'end) (insert (format "\nbibliography:%s" (mapconcat 'identity reftex-default-bibliography ","))))) (save-buffer) ;; get a latex file and extract the references (org-latex-export-to-latex) (find-file texfile) (reftex-parse-all) (reftex-create-bibtex-file bibfile) (save-buffer) ;; save results of the references (setq results (buffer-string)) ;; kill buffers. these are named by basename, not full path (kill-buffer (concat basename ".bib")) (kill-buffer (concat basename ".tex")) (kill-buffer basename) (delete-file bibfile) (delete-file texfile) (delete-file tempname) ;; Now back to the original org buffer and insert the results (switch-to-buffer cb) (when (not (string= "" results)) (save-excursion (goto-char (point-max)) (insert "\n\n") (org-insert-heading) (insert (format " Bibtex entries ,#+BEGIN_SRC text :tangle %s %s ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results)))))) #+END_SRC ** Find bad cite links 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (require 'cl) (defun index (substring list) "return the index of string in a list of strings" (let ((i 0) (found nil)) (dolist (arg list i) (if (string-match (concat "^" substring "$") arg) (progn (setq found t) (return i))) (setq i (+ i 1))) ;; return counter if found, otherwise return nil (if found i nil))) (defun org-ref-find-bad-citations () "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files. Makes a new buffer with clickable links." (interactive) ;; generate the list of bibtex-keys and cited keys (let* ((bibtex-files (org-ref-find-bibliography)) (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":")) (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist))) (bad-citations '())) (org-element-map (org-element-parse-buffer) 'link (lambda (link) (let ((plist (nth 1 link))) (when (equal (plist-get plist ':type) "cite") (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) ) (when (not (index key bibtex-keys)) (setq bad-citations (append bad-citations `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n" key (buffer-name)(plist-get plist ':begin))))) )))))) (if bad-citations (progn (switch-to-buffer-other-window "*Missing citations*") (org-mode) (erase-buffer) (insert "* List of bad cite links\n") (insert (mapconcat 'identity bad-citations "")) ;(setq buffer-read-only t) (use-local-map (copy-keymap org-mode-map)) (local-set-key "q" #'(lambda () (interactive) (kill-buffer)))) (when (get-buffer "*Missing citations*") (kill-buffer "*Missing citations*")) (message "No bad cite links found")))) #+END_SRC ** Finding non-ascii characters I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-find-non-ascii-characters () "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files" (interactive) (occur "[^[:ascii:]]")) #+END_SRC ** Resort a bibtex entry 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-sort-bibtex-entry () "sort fields of entry in standard order and downcase them" (interactive) (bibtex-beginning-of-entry) (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url")) (entry (bibtex-parse-entry)) (entry-fields) (other-fields) (type (cdr (assoc "=type=" entry))) (key (cdr (assoc "=key=" entry)))) ;; these are the fields we want to order that are in this entry (setq entry-fields (mapcar (lambda (x) (car x)) entry)) ;; we do not want to reenter these fields (setq entry-fields (remove "=key=" entry-fields)) (setq entry-fields (remove "=type=" entry-fields)) ;;these are the other fields in the entry (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields)) (cond ;; right now we only resort articles ((string= (downcase type) "article") (bibtex-kill-entry) (insert (concat "@article{" key ",\n" (mapconcat (lambda (field) (when (member field entry-fields) (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n") (mapconcat (lambda (field) (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n") "\n}\n\n")) (bibtex-find-entry key) (bibtex-fill-entry) (bibtex-clean-entry) )))) #+END_SRC ** Clean a bibtex entry 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. 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-clean-bibtex-entry(&optional keep-key) "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" (interactive "P") (bibtex-beginning-of-entry) (end-of-line) ;; some entries do not have a key or comma in first line. We check and add it, if needed. (unless (string-match ",$" (thing-at-point 'line)) (end-of-line) (insert ",")) ;; check for empty pages, and put eid or article id in its place (let ((entry (bibtex-parse-entry)) (pages (bibtex-autokey-get-field "pages")) (year (bibtex-autokey-get-field "year")) (doi (bibtex-autokey-get-field "doi")) ;; The Journal of Chemical Physics uses eid (eid (bibtex-autokey-get-field "eid"))) ;; replace http://dx.doi.org/ in doi. some journals put that in, ;; but we only want the doi. (when (string-match "^http://dx.doi.org/" doi) (bibtex-beginning-of-entry) (goto-char (car (cdr (bibtex-search-forward-field "doi" t)))) (bibtex-kill-field) (bibtex-make-field "doi") (backward-char) (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi))) ;; asap articles often set year to 0, which messes up key ;; generation. fix that. (when (string= "0" year) (bibtex-beginning-of-entry) (goto-char (car (cdr (bibtex-search-forward-field "year" t)))) (bibtex-kill-field) (bibtex-make-field "year") (backward-char) (insert (read-string "Enter year: "))) ;; fix pages if they are empty if there is an eid to put there. (when (string= "-" pages) (when eid (bibtex-beginning-of-entry) ;; this seems like a clunky way to set the pages field.But I ;; cannot find a better way. (goto-char (car (cdr (bibtex-search-forward-field "pages" t)))) (bibtex-kill-field) (bibtex-make-field "pages") (backward-char) (insert eid))) ;; replace naked & with \& (save-restriction (bibtex-narrow-to-entry) (bibtex-beginning-of-entry) (message "checking &") (replace-regexp " & " " \\\\& ") (widen)) ;; generate a key, and if it duplicates an existing key, edit it. (unless keep-key (let ((key (bibtex-generate-autokey))) ;; first we delete the existing key (bibtex-beginning-of-entry) (re-search-forward bibtex-entry-maybe-empty-head) (if (match-beginning bibtex-key-in-head) (delete-region (match-beginning bibtex-key-in-head) (match-end bibtex-key-in-head))) ;; check if the key is in the buffer (when (save-excursion (bibtex-search-entry key)) (save-excursion (bibtex-search-entry key) (bibtex-copy-entry-as-kill) (switch-to-buffer-other-window "*duplicate entry*") (bibtex-yank)) (setq key (bibtex-read-key "Duplicate Key found, edit: " key))) (insert key) (kill-new key))) ;; save key for pasting ;; run hooks. each of these operates on the entry with no arguments. ;; this did not work like i thought, it gives a symbolp error. ;; (run-hooks org-ref-clean-bibtex-entry-hook) (mapcar (lambda (x) (save-restriction (save-excursion (funcall x)))) org-ref-clean-bibtex-entry-hook) ;; sort fields within entry (org-ref-sort-bibtex-entry) ;; check for non-ascii characters (occur "[^[:ascii:]]") )) #+END_SRC #+RESULTS: : org-ref-clean-bibtex-entry ** Sort the entries in a citation link by year I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-citation-year (key) "get the year of an entry with key. Returns year as a string." (interactive) (let* ((results (org-ref-get-bibtex-key-and-file key)) (bibfile (cdr results))) (with-temp-buffer (insert-file-contents bibfile) (bibtex-search-entry key nil 0) (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t)) )))) (defun org-ref-sort-citation-link () "replace link at point with sorted link by year" (interactive) (let* ((object (org-element-context)) (type (org-element-property :type object)) (begin (org-element-property :begin object)) (end (org-element-property :end object)) (link-string (org-element-property :path object)) keys years data) (setq keys (org-ref-split-and-strip-string link-string)) (setq years (mapcar 'org-ref-get-citation-year keys)) (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys)) (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y)))))) ;; now get the keys separated by commas (setq keys (mapconcat (lambda (x) (cdr x)) data ",")) ;; and replace the link with the sorted keys (cl--set-buffer-substring begin end (concat type ":" keys)))) #+END_SRC ** Sort entries in citation links with shift-arrow keys Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-swap-keys (i j keys) "swap the keys in a list with index i and j" (let ((tempi (nth i keys))) (setf (nth i keys) (nth j keys)) (setf (nth j keys) tempi)) keys) (defun org-ref-swap-citation-link (direction) "move citation at point in direction +1 is to the right, -1 to the left" (interactive) (let* ((object (org-element-context)) (type (org-element-property :type object)) (begin (org-element-property :begin object)) (end (org-element-property :end object)) (link-string (org-element-property :path object)) key keys i) ;; We only want this to work on citation links (when (-contains? org-ref-cite-types type) (setq key (org-ref-get-bibtex-key-under-cursor)) (setq keys (org-ref-split-and-strip-string link-string)) (setq i (index key keys)) ;; defined in org-ref (if (> direction 0) ;; shift right (org-ref-swap-keys i (+ i 1) keys) (org-ref-swap-keys i (- i 1) keys)) (setq keys (mapconcat 'identity keys ",")) ;; and replace the link with the sorted keys (cl--set-buffer-substring begin end (concat type ":" keys " ")) ;; now go forward to key so we can move with the key (re-search-forward key) (goto-char (match-beginning 0))))) ;; add hooks to make it work (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1))) (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1))) #+END_SRC ** Lightweight messages about links 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. ref:test citep:test label:rett #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-label-context (label) "Return a string of context around a label." (save-excursion (catch 'result (goto-char (point-min)) (when (re-search-forward (format "label:%s\\b" label) nil t) (throw 'result (buffer-substring (progn (previous-line) (beginning-of-line) (point)) (progn (forward-line 4) (point))))) (goto-char (point-min)) (when (re-search-forward (format "\\label{%s}" label) nil t) (throw 'result (buffer-substring (progn (previous-line) (beginning-of-line) (point)) (progn (forward-line 4) (point))))) (goto-char (point-min)) (when (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t) (throw 'result (buffer-substring (progn (previous-line) (beginning-of-line) (point)) (progn (forward-line 4) (point))))) (goto-char (point-min)) (when (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t) (throw 'result (buffer-substring (progn (previous-line) (beginning-of-line) (point)) (progn (forward-line 4) (point)))))))) (defun org-ref-link-message () "Print a minibuffer message about the link that point is on." (interactive) (let* ((object (org-element-context)) (type (org-element-property :type object))) (save-excursion (cond ;; cite links ((-contains? org-ref-cite-types type) (message (org-ref-get-citation-string-at-point))) ;; message some context about the label we are referring to ((string= type "ref") (message (org-ref-get-label-context (org-element-property :path object)))) ((string= type "eqref") (message (org-ref-get-label-context (org-element-property :path object)))) ;; message the count ((string= type "label") (let ((count (org-ref-count-labels (org-element-property :path object)))) ;; get plurality on occurrence correct (message (concat (number-to-string count) " occurence" (when (or (= count 0) (> count 1)) "s"))))))))) (when org-ref-show-citation-on-enter (add-hook 'post-command-hook 'org-ref-link-message)) #+END_SRC * Aliases I like convenience. Here are some aliases for faster typing. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defalias 'oro 'org-ref-open-citation-at-point) (defalias 'orc 'org-ref-citation-at-point) (defalias 'orp 'org-ref-open-pdf-at-point) (defalias 'oru 'org-ref-open-url-at-point) (defalias 'orn 'org-ref-open-notes-at-point) (defalias 'ornr 'org-ref-open-notes-from-reftex) (defalias 'orib 'org-ref-insert-bibliography-link) (defalias 'oric 'org-ref-insert-cite-link) (defalias 'orir 'org-ref-insert-ref-link) (defalias 'orsl 'org-ref-store-bibtex-entry-link) (defalias 'orcb 'org-ref-clean-bibtex-entry) #+END_SRC * Helm interface [[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. 1. Make the default action to insert selected keys. 2. Make open entry second action #+BEGIN_SRC emacs-lisp :tangle org-ref.el (setq helm-source-bibtex '((name . "BibTeX entries") (init . helm-bibtex-init) (candidates . helm-bibtex-candidates) (filtered-candidate-transformer . helm-bibtex-candidates-formatter) (action . (("Insert citation" . helm-bibtex-insert-citation) ("Show entry" . helm-bibtex-show-entry) ("Open PDF file (if present)" . helm-bibtex-open-pdf) ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi) ("Insert reference" . helm-bibtex-insert-reference) ("Insert BibTeX key" . helm-bibtex-insert-key) ("Insert BibTeX entry" . helm-bibtex-insert-bibtex) ("Attach PDF to email" . helm-bibtex-add-PDF-attachment) ("Edit notes" . helm-bibtex-edit-notes) )))) #+END_SRC Now, let us define a function that inserts the cite links: #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun helm-bibtex-format-org-ref (keys) "Insert selected KEYS as cite link. Append KEYS if you are on a link. 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." (let* ((object (org-element-context))) (message-box "prefix is %s" helm-current-prefix-arg) (cond ;; case where we are in a link ((and (equal (org-element-type object) 'link) (-contains? org-ref-cite-types (org-element-property :type object))) (goto-char (org-element-property :end object)) ;; sometimes there are spaces at the end of the link ;; this code moves point pack until no spaces are there (while (looking-back " ") (backward-char)) (insert (concat "," (mapconcat 'identity keys ",")))) ;; We are next to a link, and we want to append ((save-excursion (backward-char) (and (equal (org-element-type (org-element-context)) 'link) (-contains? org-ref-cite-types (org-element-property :type (org-element-context))))) (goto-char (org-element-property :end object)) (while (looking-back " ") (backward-char)) (insert (concat "," (mapconcat 'identity keys ",")))) ;; insert fresh link (t (insert (concat (if helm-current-prefix-arg (ido-completing-read "Type: " org-ref-cite-types) org-ref-default-citation-link) ":" (s-join "," keys)))))) ;; return empty string for helm "") (setq helm-bibtex-format-citation-functions '((org-mode . helm-bibtex-format-org-ref))) (defun org-ref-helm-insert-cite-link () "org-ref function to use helm on the bibliography defined in the org-file." (interactive) (let ((helm-bibtex-bibliography (org-ref-find-bibliography))) (helm-bibtex))) (require 'helm-bibtex) #+END_SRC ** A helm click menu 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. #+BEGIN_SRC emacs-lisp :tangle org-ref.el (defun org-ref-get-citation-string-at-point () "Get a string of a formatted citation" (interactive) (let* ((results (org-ref-get-bibtex-key-and-file)) (key (car results)) (bibfile (cdr results))) (save-excursion (with-temp-buffer (insert-file-contents bibfile) (bibtex-search-entry key) (org-ref-bib-citation))))) (defun org-ref-cite-candidates () "Generate the list of possible candidates for click actions on a cite link. Checks for pdf and doi, and add appropriate functions." (interactive) (let* ((results (org-ref-get-bibtex-key-and-file)) (key (car results)) (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)) (bibfile (cdr results)) (url (save-excursion (with-temp-buffer (insert-file-contents bibfile) (bibtex-search-entry key) (bibtex-autokey-get-field "url")))) (doi (save-excursion (with-temp-buffer (insert-file-contents bibfile) (bibtex-search-entry key) ;; I like this better than bibtex-url which does not always find ;; the urls (bibtex-autokey-get-field "doi")))) (candidates `(("Quit" . org-ref-citation-at-point) ("Open bibtex entry" . org-ref-open-citation-at-point)))) ;; for some reason, when there is no doi or url, they are returned as "". I ;; prefer nil so we correct this here. (when (string= doi "") (setq doi nil)) (when (string= url "") (setq url nil)) ;; Conditional pdf functions (if (file-exists-p pdf-file) (add-to-list 'candidates '("Open pdf" . org-ref-open-pdf-at-point) t) (add-to-list 'candidates '("Try to get pdf" . (lambda () (save-window-excursion (org-ref-open-citation-at-point) (bibtex-beginning-of-entry) (doi-utils-get-bibtex-entry-pdf)))) t)) (add-to-list 'candidates '("Open notes" . org-ref-open-notes-at-point) t) ;; conditional url and doi functions (when (or url doi) (add-to-list 'candidates '("Open in browser" . org-ref-open-url-at-point) t)) (when doi (mapc (lambda (x) (add-to-list 'candidates x t)) `(("WOS" . org-ref-wos-at-point) ("Related articles in WOS" . org-ref-wos-related-at-point) ("Citing articles in WOS" . org-ref-wos-citing-at-point) ("Google Scholar" . org-ref-google-scholar-at-point) ("Pubmed" . org-ref-pubmed-at-point) ("Crossref" . org-ref-crossref-at-point) ))) (add-to-list 'candidates '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary) t) (add-to-list 'candidates '("Copy key to clipboard" . (lambda () (kill-new (car (org-ref-get-bibtex-key-and-file))))) t) (add-to-list 'candidates '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file) t) (add-to-list 'candidates '("Email bibtex entry and pdf" . (lambda () (save-excursion (org-ref-open-citation-at-point) (email-bibtex-entry)))) t) ;; finally return a numbered list of the candidates (loop for i from 0 for cell in candidates collect (cons (format "%2s. %s" i (car cell)) (cdr cell))))) (defvar org-ref-helm-user-candidates '() "List of user-defined candidates to act when clicking on a cite link. 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. ") ;; example of adding your own function (add-to-list 'org-ref-helm-user-candidates '("Example" . (lambda () (message-box "You did it!"))) t) (defun org-ref-cite-click-helm (key) "subtle points. 1. get name and candidates before entering helm because we need the org-buffer. 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer." (interactive) (let ((name (org-ref-get-citation-string-at-point)) (candidates (org-ref-cite-candidates)) (cb (current-buffer))) (helm :sources `(((name . ,name) (candidates . ,candidates) (action . (lambda (f) (switch-to-buffer cb) (funcall f)))) ((name . "User functions") (candidates . ,org-ref-helm-user-candidates) (action . (lambda (f) (switch-to-buffer cb) (funcall f)))) )))) #+END_SRC #+RESULTS: : org-ref-cite-click-helm * End of code #+BEGIN_SRC emacs-lisp :tangle org-ref.el (provide 'org-ref) #+END_SRC * Build :noexport: This code will tangle the elisp code out to org-ref.el and load it. [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]] Alternatively you may use: [[elisp:(org-babel-load-file "org-ref.org")]]