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.
42 ;; also sets up reftex for org-mode. The links are clickable and do
43 ;; things that are useful. You should really read org-ref.org for details.
45 ;; Package-Requires: ((dash))
49 The only external require is reftex-cite
51 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
52 (require 'reftex-cite)
57 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.
59 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
61 "customization group for org-ref")
63 (defcustom org-ref-bibliography-notes
65 "filename to where you will put all your notes about an entry in
66 the default bibliography."
70 (defcustom org-ref-default-bibliography
72 "list of bibtex files to search for. You should use full-paths for each file."
73 :type '(repeat :tag "List of bibtex files" file)
76 (defcustom org-ref-pdf-directory
78 "directory where pdfs are stored by key. put a trailing / in"
82 (defcustom org-ref-default-citation-link
84 "The default type of citation link to use"
88 (defcustom org-ref-insert-cite-key
90 "Keyboard shortcut to insert a citation."
94 (defcustom org-ref-bibliography-entry-format
95 '(("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>.")
96 ("book" . "%a, %t, %u (%y)."))
97 "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."
102 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.
104 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
105 (defcustom org-ref-cite-types
106 '("cite" "nocite" ;; the default latex cite commands
107 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
108 "citet" "citet*" "citep" "citep*"
109 "citealt" "citealt*" "citealp" "citealp*"
111 "citeauthor" "citeauthor*"
112 "citeyear" "citeyear*"
113 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
115 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
117 "parencite" "Parencite"
118 "footcite" "footcitetext"
119 "textcite" "Textcite"
120 "smartcite" "Smartcite"
121 "cite*" "parencite*" "supercite"
122 "autocite" "Autocite" "autocite*" "Autocite*"
124 "citetitle" "citetitle*"
125 "citedate" "citedate*"
127 "fullcite" "footfullcite"
128 ;; "volcite" "Volcite" cannot support the syntax
129 "notecite" "Notecite"
130 "pnotecite" "Pnotecite"
132 ;; multicites. Very limited support for these.
133 "cites" "Cites" "parencites" "Parencites"
134 "footcites" "footcitetexts"
135 "smartcites" "Smartcites" "textcites" "Textcites"
136 "supercites" "autocites" "Autocites"
138 "List of citation types known in org-ref"
139 :type '(repeat :tag "List of citation types" string)
143 We need a hook variable to store user-defined bibtex entry cleaning functions
144 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
145 (defcustom org-ref-clean-bibtex-entry-hook nil
146 "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
152 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
153 (defvar org-ref-bibliography-files
155 "variable to hold bibliography files to be searched")
158 ** org-mode / reftex setup
160 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.
162 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
163 (defun org-mode-reftex-setup ()
164 (load-library "reftex")
165 (and (buffer-file-name)
166 (file-exists-p (buffer-file-name))
167 (global-auto-revert-mode t)
169 (make-local-variable 'reftex-cite-format)
170 (setq reftex-cite-format 'org)
171 (define-key org-mode-map (kbd org-ref-insert-cite-key) 'org-ref-insert-cite-link))
173 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
175 (eval-after-load 'reftex-vars
177 (add-to-list 'reftex-cite-format-builtin
178 '(org "Org-mode citation"
179 ((?\C-m . "cite:%l") ; default
180 (?d . ",%l") ; for appending
186 (?h . "citeauthor:%l")
187 (?H . "citeauthor*:%l")
194 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.
196 #+BEGIN_SRC emacs-lisp :tangle no
198 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
199 (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l")
200 (?z . "newcite:%l"))))
203 You can define a new citation link like this:
204 #+BEGIN_SRC emacs-lisp :tangle no
205 (org-ref-define-citation-link "citez" ?z)
209 Most of this library is the creation of functional links to help with references and citations.
211 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.
213 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
214 (defun org-ref-strip-string (string)
215 "strip leading and trailing whitespace from the string"
216 (replace-regexp-in-string
217 (concat search-whitespace-regexp "$" ) ""
218 (replace-regexp-in-string
219 (concat "^" search-whitespace-regexp ) "" string)))
222 It is helpful to make the previous function operate on a list of strings here.
224 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
225 (defun org-ref-split-and-strip-string (string)
226 "split key-string and strip keys. Assumes the key-string is comma delimited"
227 (mapcar 'org-ref-strip-string (split-string string ",")))
230 ** bibliography and bibliographystyle
231 *** An html bibliography
233 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.
235 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
236 (defun org-ref-reftex-get-bib-field (field entry &optional format)
237 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
239 (setq result (reftex-get-bib-field field entry format))
240 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
241 (setq result (substring result 1 -1)))
242 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
243 (setq result (substring result 1 -1)))
246 (defun org-ref-reftex-format-citation (entry format)
247 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
248 to the format argument. The format is a string with these percent escapes.
250 In the format, the following percent escapes will be expanded.
252 %l The BibTeX label of the citation.
253 %a List of author names, see also `reftex-cite-punctuation'.
254 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
255 %A First author name only.
256 %e Works like %a, but on list of editor names. (%2e and %E work a well)
258 It is also possible to access all other BibTeX database fields:
259 %b booktitle %c chapter %d edition %h howpublished
260 %i institution %j journal %k key %m month
261 %n number %o organization %p pages %P first page
262 %r address %s school %u publisher %t title
264 %B booktitle, abbreviated %T title, abbreviated
269 Usually, only %l is needed. The other stuff is mainly for the echo area
270 display, and for (setq reftex-comment-citations t).
272 %< as a special operator kills punctuation and space around it after the
273 string has been formatted.
275 A pair of square brackets indicates an optional argument, and RefTeX
276 will prompt for the values of these arguments.
278 Beware that all this only works with BibTeX database files. When
279 citations are made from the \bibitems in an explicit thebibliography
280 environment, only %l is available."
281 ;; Format a citation from the info in the BibTeX ENTRY
283 (unless (stringp format) (setq format "\\cite{%l}"))
285 (if (and reftex-comment-citations
286 (string-match "%l" reftex-cite-comment-format))
287 (error "reftex-cite-comment-format contains invalid %%l"))
290 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
292 (let ((n (string-to-number (match-string 4 format)))
293 (l (string-to-char (match-string 5 format)))
299 (org-ref-reftex-get-bib-field "&key" entry)
300 (if reftex-comment-citations
301 reftex-cite-comment-format
303 ((= l ?a) (reftex-format-names
304 (reftex-get-bib-names "author" entry)
306 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
307 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
308 ((= l ?B) (reftex-abbreviate-title
309 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
310 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
311 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
312 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
313 ((= l ?e) (reftex-format-names
314 (reftex-get-bib-names "editor" entry)
316 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
317 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
318 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
319 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
320 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
321 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
322 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
323 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
324 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
325 ((= l ?P) (car (split-string
326 (org-ref-reftex-get-bib-field "pages" entry)
328 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
329 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
330 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
331 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
332 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
333 ;; strip enclosing brackets from title if they are there
334 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
335 ((= l ?T) (reftex-abbreviate-title
336 (org-ref-reftex-get-bib-field "title" entry)))
337 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
338 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
341 (setq b (match-beginning 2) e (match-end 2))
342 (setq b (match-beginning 3) e (match-end 3)))
343 (setq format (concat (substring format 0 b) rpl (substring format e)))))
344 (while (string-match "%%" format)
345 (setq format (replace-match "%" t t format)))
346 (while (string-match "[ ,.;:]*%<" format)
347 (setq format (replace-match "" t t format)))
348 ;; also replace carriage returns, tabs, and multiple whitespaces
349 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
352 (defun org-ref-get-bibtex-entry-citation (key)
353 "returns a string for the bibliography entry corresponding to key, and formatted according to `org-ref-bibliography-entry-format'"
355 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
356 (file) (entry) (bibtex-entry) (entry-type))
358 (setq file (catch 'result
359 (loop for file in org-ref-bibliography-files do
360 (if (org-ref-key-in-file-p key (file-truename file))
362 (message "%s not found in %s" key (file-truename file))))))
365 (insert-file-contents file)
366 (bibtex-search-entry key nil 0)
367 (setq bibtex-entry (bibtex-parse-entry))
368 (setq entry-type (cdr (assoc "=type=" bibtex-entry)))
369 (setq entry (org-ref-reftex-format-citation bibtex-entry (cdr (assoc entry-type org-ref-bibliography-entry-format)))))
374 : org-ref-reftex-format-citation
376 Here is how to use the function. You call it with point in an entry in a bibtex file.
378 #+BEGIN_SRC emacs-lisp :tangle no
379 (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>."))
380 (org-ref-get-bibtex-entry-citation "armiento-2014-high"))
383 : 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>.
385 I am not sure why full author names are not used.
387 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
389 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
390 (defun org-ref-get-bibtex-keys ()
391 "return a list of unique keys in the buffer."
393 (org-element-map (org-element-parse-buffer) 'link
395 (let ((plist (nth 1 link)))
396 (when (-contains? org-ref-cite-types (plist-get plist ':type))
399 (org-ref-split-and-strip-string (plist-get plist ':path)))
400 (when (not (-contains? keys key))
401 (setq keys (append keys (list key)))))))))
402 ;; Sort keys alphabetically
403 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
407 This function gets the html for one entry.
409 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
410 (defun org-ref-get-bibtex-entry-html (key)
411 "returns an html string for the bibliography entry corresponding to key"
413 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
416 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
418 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
419 (defun org-ref-get-html-bibliography ()
420 "Create an html bibliography when there are keys"
421 (let ((keys (org-ref-get-bibtex-keys)))
423 (concat "<h1>Bibliography</h1>
425 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
429 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.
432 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.
434 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
435 (org-add-link-type "bibliography"
436 ;; this code is run on clicking. The bibliography
437 ;; may contain multiple files. this code finds the
438 ;; one you clicked on and opens it.
439 (lambda (link-string)
440 ;; get link-string boundaries
441 ;; we have to go to the beginning of the line, and then search forward
444 ;; object is the link you clicked on
445 (object (org-element-context))
447 (link-string-beginning)
451 (goto-char (org-element-property :begin object))
452 (search-forward link-string nil nil 1)
453 (setq link-string-beginning (match-beginning 0))
454 (setq link-string-end (match-end 0)))
456 ;; We set the reftex-default-bibliography
457 ;; here. it should be a local variable only in
458 ;; the current buffer. We need this for using
459 ;; reftex to do citations.
460 (set (make-local-variable 'reftex-default-bibliography)
461 (split-string (org-element-property :path object) ","))
463 ;; now if we have comma separated bibliographies
464 ;; we find the one clicked on. we want to
465 ;; search forward to next comma from point
467 (if (search-forward "," link-string-end 1 1)
468 (setq key-end (- (match-end 0) 1)) ; we found a match
469 (setq key-end (point)))) ; no comma found so take the point
470 ;; and backward to previous comma from point
472 (if (search-backward "," link-string-beginning 1 1)
473 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
474 (setq key-beginning (point)))) ; no match found
475 ;; save the key we clicked on.
476 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
477 (find-file bibfile))) ; open file on click
480 (lambda (keyword desc format)
482 ((eq format 'html) (org-ref-get-html-bibliography))
484 ;; write out the latex bibliography command
485 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" keyword))))))
488 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
489 (org-add-link-type "printbibliography"
490 (lambda (arg) (message "Nothing implemented for clicking here."))
491 (lambda (keyword desc format)
493 ((eq format 'html) (org-ref-get-html-bibliography))
495 ;; write out the latex bibliography command
496 (format "\\printbibliography" keyword)))))
499 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, ...
501 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
502 (org-add-link-type "bibliographystyle"
503 (lambda (arg) (message "Nothing implemented for clicking here."))
504 (lambda (keyword desc format)
507 ;; write out the latex bibliography command
508 (format "\\bibliographystyle{%s}" keyword)))))
511 *** Completion for bibliography link
514 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
515 (defun org-bibliography-complete-link (&optional arg)
516 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
518 (defun org-ref-insert-bibliography-link ()
519 "insert a bibliography with completion"
521 (insert (org-bibliography-complete-link)))
525 This is apparently used for biblatex.
526 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
527 (org-add-link-type "addbibresource"
528 ;; this code is run on clicking. The addbibresource
529 ;; may contain multiple files. this code finds the
530 ;; one you clicked on and opens it.
531 (lambda (link-string)
532 ;; get link-string boundaries
533 ;; we have to go to the beginning of the line, and then search forward
536 ;; object is the link you clicked on
537 (object (org-element-context))
539 (link-string-beginning)
543 (goto-char (org-element-property :begin object))
544 (search-forward link-string nil nil 1)
545 (setq link-string-beginning (match-beginning 0))
546 (setq link-string-end (match-end 0)))
548 ;; We set the reftex-default-addbibresource
549 ;; here. it should be a local variable only in
550 ;; the current buffer. We need this for using
551 ;; reftex to do citations.
552 (set (make-local-variable 'reftex-default-addbibresource)
553 (split-string (org-element-property :path object) ","))
555 ;; now if we have comma separated bibliographies
556 ;; we find the one clicked on. we want to
557 ;; search forward to next comma from point
559 (if (search-forward "," link-string-end 1 1)
560 (setq key-end (- (match-end 0) 1)) ; we found a match
561 (setq key-end (point)))) ; no comma found so take the point
562 ;; and backward to previous comma from point
564 (if (search-backward "," link-string-beginning 1 1)
565 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
566 (setq key-beginning (point)))) ; no match found
567 ;; save the key we clicked on.
568 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
569 (find-file bibfile))) ; open file on click
572 (lambda (keyword desc format)
574 ((eq format 'html) (format "")); no output for html
576 ;; write out the latex addbibresource command
577 (format "\\addbibresource{%s}" keyword)))))
582 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.
584 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
585 (defun org-ref-list-of-figures (&optional arg)
586 "Generate buffer with list of figures in them"
588 (save-excursion (widen)
589 (let* ((c-b (buffer-name))
592 (org-element-map (org-element-parse-buffer) 'link
594 "create a link for to the figure"
596 (and (string= (org-element-property :type link) "file")
598 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
599 (org-element-property :path link)))
602 (let* ((start (org-element-property :begin link))
603 (parent (car (cdr (org-element-property :parent link))))
604 (caption (caaar (plist-get parent :caption)))
605 (name (plist-get parent :name)))
608 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
609 c-b start counter (or name "") caption)
611 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
612 c-b start counter (or name "")))))))))
613 (switch-to-buffer "*List of Figures*")
614 (setq buffer-read-only nil)
617 (insert (mapconcat 'identity list-of-figures ""))
618 (setq buffer-read-only t)
619 (use-local-map (copy-keymap org-mode-map))
620 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
624 'org-ref-list-of-figures ; on click
625 (lambda (keyword desc format)
628 (format "\\listoffigures")))))
633 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
634 (defun org-ref-list-of-tables (&optional arg)
635 "Generate a buffer with a list of tables"
639 (let* ((c-b (buffer-name))
642 (org-element-map (org-element-parse-buffer 'element) 'table
644 "create a link for to the table"
646 (let ((start (org-element-property :begin table))
647 (name (org-element-property :name table))
648 (caption (caaar (org-element-property :caption table))))
651 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
652 c-b start counter (or name "") caption)
654 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
655 c-b start counter (or name ""))))))))
656 (switch-to-buffer "*List of Tables*")
657 (setq buffer-read-only nil)
660 (insert (mapconcat 'identity list-of-tables ""))
661 (setq buffer-read-only t)
662 (use-local-map (copy-keymap org-mode-map))
663 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
667 'org-ref-list-of-tables
668 (lambda (keyword desc format)
671 (format "\\listoftables")))))
675 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.
676 *************** TODO search tblnames, custom_ids and check for case sensitivity
679 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
683 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
684 (message (format "%s occurences"
685 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
686 ;; for tblname, it is not enough to get word boundary
687 ;; tab-little and tab-little-2 match then.
688 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
689 (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
690 ;; this is the org-format #+label:
691 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))))
692 (lambda (keyword desc format)
694 ((eq format 'html) (format "(<label>%s</label>)" path))
696 (format "\\label{%s}" keyword)))))
699 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.
701 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
702 (defun org-label-store-link ()
703 "store a link to a label. The output will be a ref to that label"
704 ;; First we have to make sure we are on a label link.
705 (let* ((object (org-element-context)))
706 (when (and (equal (org-element-type object) 'link)
707 (equal (org-element-property :type object) "label"))
708 (org-store-link-props
710 :link (concat "ref:" (org-element-property :path object))))
712 ;; Store link on table
713 (when (equal (org-element-type object) 'table)
714 (org-store-link-props
716 :link (concat "ref:" (org-element-property :name object))))
718 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
719 ;; store link on heading with custom_id
720 ; (when (and (equal (org-element-type object) 'headline)
721 ; (org-entry-get (point) "CUSTOM_ID"))
722 ; (org-store-link-props
724 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
726 ;; and to #+label: lines
727 (when (and (equal (org-element-type object) 'paragraph)
728 (org-element-property :name object))
729 (org-store-link-props
731 :link (concat "ref:" (org-element-property :name object))))
734 (add-hook 'org-store-link-functions 'org-label-store-link)
738 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.
740 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
742 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
746 "on clicking goto the label. Navigate back with C-c &"
748 ;; next search from beginning of the buffer
750 ;; it is possible you would not find the label if narrowing is in effect
757 (goto-char (point-min))
758 (re-search-forward (format "label:%s\\b" label) nil t))
762 (goto-char (point-min))
763 (re-search-forward (format "\\label{%s}" label) nil t))
765 ;; #+label: name org-definition
767 (goto-char (point-min))
768 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
772 (goto-char (point-min))
773 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
775 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
776 ;; you need [[#label]] links.
779 ; (goto-char (point-min))
780 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
782 ;; we did not find anything, so go back to where we came
784 (error "%s not found" label))
785 (message "go back with (org-mark-ring-goto) `C-c &`"))
787 (lambda (keyword desc format)
789 ((eq format 'html) (format "(<ref>%s</ref>)" path))
791 (format "\\ref{%s}" keyword)))))
794 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 labels, custom_ids, and table names as potential items to make a ref link to.
796 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
797 (defun org-ref-get-custom-ids ()
798 "return a list of custom_id properties in the buffer"
799 (let ((results '()) custom_id)
802 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
803 (when (not (null custom_id))
804 (setq results (append results (list custom_id)))))))
808 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
809 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
810 (defun org-ref-get-latex-labels ()
812 (goto-char (point-min))
814 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
815 (add-to-list 'matches (match-string-no-properties 1) t))
819 Finally, we get the table names.
821 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
822 (defun org-ref-get-tblnames ()
823 (org-element-map (org-element-parse-buffer 'element) 'table
825 (org-element-property :name table))))
828 Now, we can put all the labels together which will give us a list of candidates.
830 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
831 (defun org-ref-get-labels ()
832 "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
836 (goto-char (point-min))
838 (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
839 (add-to-list 'matches (match-string-no-properties 1) t))
840 (append matches (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
843 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.
845 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
846 (defun org-ref-complete-link (&optional arg)
847 "Completion function for ref links"
849 (setq label (completing-read "label: " (org-ref-get-labels)))
850 (format "ref:%s" label)))
853 Alternatively, you may want to just call a function that inserts a link with completion:
855 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
856 (defun org-ref-insert-ref-link ()
858 (insert (org-ref-complete-link)))
863 This refers to the page of a label in LaTeX.
865 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
869 "on clicking goto the label. Navigate back with C-c &"
871 ;; next search from beginning of the buffer
877 (goto-char (point-min))
878 (re-search-forward (format "label:%s\\b" label) nil t))
882 (goto-char (point-min))
883 (re-search-forward (format "\\label{%s}" label) nil t))
885 ;; #+label: name org-definition
887 (goto-char (point-min))
888 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
892 (goto-char (point-min))
893 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
895 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
896 ;; you need [[#label]] links.
899 ; (goto-char (point-min))
900 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
902 ;; we did not find anything, so go back to where we came
904 (error "%s not found" label))
905 (message "go back with (org-mark-ring-goto) `C-c &`"))
907 (lambda (keyword desc format)
909 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
911 (format "\\pageref{%s}" keyword)))))
914 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
915 (defun org-pageref-complete-link (&optional arg)
916 "Completion function for ref links"
918 (setq label (completing-read "label: " (org-ref-get-labels)))
919 (format "ref:%s" label)))
922 Alternatively, you may want to just call a function that inserts a link with completion:
924 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
925 (defun org-pageref-insert-ref-link ()
927 (insert (org-pageref-complete-link)))
932 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.
934 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
938 "on clicking goto the label. Navigate back with C-c &"
940 ;; next search from beginning of the buffer
946 (goto-char (point-min))
947 (re-search-forward (format "\\label{%s}" label) nil t))
949 ;; we did not find anything, so go back to where we came
951 (error "%s not found" label))
952 (message "go back with (org-mark-ring-goto) `C-c &`"))
954 (lambda (keyword desc format)
956 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
958 (format "\\nameref{%s}" keyword)))))
962 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
964 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
968 "on clicking goto the label. Navigate back with C-c &"
970 ;; next search from beginning of the buffer
972 (goto-char (point-min))
975 ;; search forward for the first match
977 (re-search-forward (format "label:%s" label) nil t)
979 (re-search-forward (format "\\label{%s}" label) nil t)
980 ;; #+label: name org-definition
981 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
983 (error "%s not found" label))
984 (message "go back with (org-mark-ring-goto) `C-c &`"))
986 (lambda (keyword desc format)
988 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
990 (format "\\eqref{%s}" keyword)))))
995 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.
997 *** Implementing the click actions of cite
999 **** Getting the key we clicked on
1000 The first thing we need is to get the bibtex key we clicked on.
1002 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1003 (defun org-ref-get-bibtex-key-under-cursor ()
1004 "returns key under the bibtex cursor. We search forward from
1005 point to get a comma, or the end of the link, and then backwards
1006 to get a comma, or the beginning of the link. that delimits the
1007 keyword we clicked on. We also strip the text properties."
1009 (let* ((object (org-element-context))
1010 (link-string (org-element-property :path object)))
1012 (if (not (org-element-property :contents-begin object))
1013 ;; this means no description in the link
1015 ;; we need the link path start and end
1017 (goto-char (org-element-property :begin object))
1018 (search-forward link-string nil nil 1)
1019 (setq link-string-beginning (match-beginning 0))
1020 (setq link-string-end (match-end 0)))
1022 ;; The key is the text between commas, or the link boundaries
1024 (if (search-forward "," link-string-end t 1)
1025 (setq key-end (- (match-end 0) 1)) ; we found a match
1026 (setq key-end link-string-end))) ; no comma found so take the end
1027 ;; and backward to previous comma from point which defines the start character
1029 (if (search-backward "," link-string-beginning 1 1)
1030 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1031 (setq key-beginning link-string-beginning))) ; no match found
1032 ;; save the key we clicked on.
1033 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1034 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1036 ;; link with description. assume only one key
1040 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.
1042 **** Getting the bibliographies
1043 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1044 (defun org-ref-find-bibliography ()
1045 "find the bibliography in the buffer.
1046 This function sets and returns cite-bibliography-files, which is a list of files
1047 either from bibliography:f1.bib,f2.bib
1048 \bibliography{f1,f2}
1049 internal bibliographies
1051 falling back to what the user has set in org-ref-default-bibliography
1056 (goto-char (point-min))
1057 ;; look for a bibliography link
1058 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1059 (setq org-ref-bibliography-files
1060 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1061 (throw 'result org-ref-bibliography-files))
1064 ;; we did not find a bibliography link. now look for \bibliography
1065 (goto-char (point-min))
1066 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1067 ;; split, and add .bib to each file
1068 (setq org-ref-bibliography-files
1069 (mapcar (lambda (x) (concat x ".bib"))
1070 (mapcar 'org-ref-strip-string
1071 (split-string (match-string 1) ","))))
1072 (throw 'result org-ref-bibliography-files))
1074 ;; no bibliography found. maybe we need a biblatex addbibresource
1075 (goto-char (point-min))
1076 ;; look for a bibliography link
1077 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1078 (setq org-ref-bibliography-files
1079 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1080 (throw 'result org-ref-bibliography-files))
1082 ;; we did not find anything. use defaults
1083 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1085 ;; set reftex-default-bibliography so we can search
1086 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1087 org-ref-bibliography-files)
1090 **** Finding the bibliography file a key is in
1091 Now, we can see if an entry is in a file.
1093 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1094 (defun org-ref-key-in-file-p (key filename)
1095 "determine if the key is in the file"
1096 (interactive "skey: \nsFile: ")
1099 (insert-file-contents filename)
1101 (bibtex-search-entry key nil 0))))
1104 Finally, we want to know which file the key is in.
1106 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1107 (defun org-ref-get-bibtex-key-and-file (&optional key)
1108 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1110 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1113 (setq key (org-ref-get-bibtex-key-under-cursor)))
1114 (setq file (catch 'result
1115 (loop for file in org-ref-bibliography-files do
1116 (if (org-ref-key-in-file-p key (file-truename file))
1117 (throw 'result file)))))
1121 **** Creating the menu for when we click on a key
1123 :ID: d7b7530b-802f-42b1-b61e-1e77da33e278
1125 When we click on a cite link, we want to get a menu in the minibuffer. We need to create a string for this. We want a citation, and some options that depend on the key. We want to know if the key is found, if there is a pdf, if etc... Here we create that string.
1127 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1128 (defun org-ref-get-menu-options ()
1129 "returns a dynamically determined string of options for the citation under point.
1131 we check to see if there is pdf, and if the key actually exists in the bibliography"
1133 (let* ((results (org-ref-get-bibtex-key-and-file))
1135 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1136 (bibfile (cdr results))
1137 m1 m2 m3 m4 m5 menu-string)
1138 (setq m1 (if bibfile
1142 (setq m3 (if (file-exists-p pdf-file)
1148 (string= (catch 'url
1152 (insert-file-contents bibfile)
1153 (bibtex-search-entry key)
1155 (string= (setq url (bibtex-autokey-get-field "url")) ""))
1159 (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1160 (throw 'url url))))) "")))
1161 "(u)rl" "(no url found)"))
1163 (setq m2 (if bibfile
1165 (setq citation (progn
1167 (insert-file-contents bibfile)
1168 (bibtex-search-entry key)
1169 (org-ref-bib-citation))))
1173 (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") " "))
1177 **** convenience functions to act on citation at point
1179 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1181 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.
1183 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1184 (defun org-ref-open-pdf-at-point ()
1185 "open the pdf for bibtex key under point if it exists"
1187 (let* ((results (org-ref-get-bibtex-key-and-file))
1189 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1190 (if (file-exists-p pdf-file)
1191 (org-open-file pdf-file)
1192 (message "no pdf found for %s" key))))
1195 (defun org-ref-open-url-at-point ()
1196 "open the url for bibtex key under point."
1198 (let* ((results (org-ref-get-bibtex-key-and-file))
1200 (bibfile (cdr results)))
1203 (insert-file-contents bibfile)
1204 (bibtex-search-entry key)
1205 ;; I like this better than bibtex-url which does not always find
1208 (let ((url (bibtex-autokey-get-field "url")))
1213 (let ((doi (bibtex-autokey-get-field "doi")))
1215 (if (string-match "^http" doi)
1217 (browse-url (format "http://dx.doi.org/%s" doi)))
1218 (throw 'done nil))))))))
1220 (defun org-ref-open-notes-at-point ()
1221 "open the notes for bibtex key under point."
1223 (let* ((results (org-ref-get-bibtex-key-and-file))
1225 (bibfile (cdr results)))
1228 (insert-file-contents bibfile)
1229 (bibtex-search-entry key)
1230 (org-ref-open-bibtex-notes)))))
1232 (defun org-ref-citation-at-point ()
1233 "give message of current citation at point"
1235 (let* ((cb (current-buffer))
1236 (results (org-ref-get-bibtex-key-and-file))
1238 (bibfile (cdr results)))
1239 (message "%s" (progn
1241 (insert-file-contents bibfile)
1242 (bibtex-search-entry key)
1243 (org-ref-bib-citation))))))
1245 (defun org-ref-open-citation-at-point ()
1246 "open bibtex file to key at point"
1248 (let* ((cb (current-buffer))
1249 (results (org-ref-get-bibtex-key-and-file))
1251 (bibfile (cdr results)))
1253 (bibtex-search-entry key)))
1256 **** the actual minibuffer menu
1257 Now, we create the menu.
1259 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1260 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1261 "use a minibuffer to select options for the citation under point.
1263 you select your option with a single key press."
1265 (let* ((choice (read-char (org-ref-get-menu-options)))
1266 (results (org-ref-get-bibtex-key-and-file))
1268 (cb (current-buffer))
1269 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1270 (bibfile (cdr results)))
1276 (bibtex-search-entry key))
1280 (org-ref-citation-at-point))
1286 (= choice ?\ )) ; space
1287 ;; this clears the minibuffer
1292 (org-ref-open-pdf-at-point))
1296 (org-ref-open-notes-at-point))
1300 (org-ref-open-url-at-point))
1302 ;; anything else we just quit.
1307 *** A function to format a cite link
1309 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.
1311 #+BEGIN_SRC emacs-lisp :tangle no
1312 ;(defun org-ref-cite-link-format (keyword desc format)
1314 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1315 ; ((eq format 'latex)
1316 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1317 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1321 *** The actual cite link
1322 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1324 #+BEGIN_SRC emacs-lisp :tangle no
1327 ; 'org-ref-cite-onclick-minibuffer-menu
1328 ; 'org-ref-cite-link-format)
1331 *** Automatic definition of the cite links
1332 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.
1334 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1335 (defmacro org-ref-make-completion-function (type)
1336 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1342 (let ((bibtex-files (org-ref-find-bibliography)))
1343 (bibtex-global-key-alist))))))
1346 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.
1348 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1349 (defmacro org-ref-make-format-function (type)
1350 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1355 (format "<a href=\"#%s\">%s</a>" key key))
1356 (org-ref-split-and-strip-string keyword) ","))
1359 (if (string= (substring type -1) "s")
1360 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1361 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1362 (org-ref-split-and-strip-string keyword) ""))
1364 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1365 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1371 We create the links by mapping the function onto the list of defined link types.
1373 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1374 (defun org-ref-format-citation-description (desc)
1375 "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 ::."
1378 ((string-match "::" desc)
1379 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1380 (t (format "[%s]" desc))))
1382 (defun org-ref-define-citation-link (type &optional key)
1383 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1384 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1385 and the completion function."
1386 (interactive "sCitation Type: \ncKey: ")
1388 ;; create the formatting function
1389 (eval `(org-ref-make-format-function ,type))
1394 'org-ref-cite-onclick-minibuffer-menu
1395 (quote ,(intern (format "org-ref-format-%s" type)))))
1397 ;; create the completion function
1398 (eval `(org-ref-make-completion-function ,type))
1400 ;; store new type so it works with adding citations, which checks
1401 ;; for existence in this list
1402 (add-to-list 'org-ref-cite-types type)
1404 ;; and finally if a key is specified, we modify the reftex menu
1406 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1407 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1408 `((,key . ,(concat type ":%l")))))))
1410 ;; create all the link types and their completion functions
1411 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1414 *** org-ref-insert-cite-link
1415 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.
1417 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1418 (defun org-ref-insert-cite-link (alternative-cite)
1419 "Insert a default citation link using reftex. If you are on a link, it
1420 appends to the end of the link, otherwise, a new link is
1421 inserted. Use a prefix arg to get a menu of citation types."
1423 (org-ref-find-bibliography)
1424 (let* ((object (org-element-context))
1425 (link-string-beginning (org-element-property :begin object))
1426 (link-string-end (org-element-property :end object))
1427 (path (org-element-property :path object)))
1429 (if (not alternative-cite)
1432 ;; case where we are in a link
1433 ((and (equal (org-element-type object) 'link)
1434 (-contains? org-ref-cite-types (org-element-property :type object)))
1435 (goto-char link-string-end)
1436 ;; sometimes there are spaces at the end of the link
1437 ;; this code moves point pack until no spaces are there
1438 (while (looking-back " ") (backward-char))
1439 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1441 ;; We are next to a link, and we want to append
1444 (and (equal (org-element-type (org-element-context)) 'link)
1445 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1446 (while (looking-back " ") (backward-char))
1447 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1449 ;; insert fresh link
1452 (concat org-ref-default-citation-link
1454 (mapconcat 'identity (reftex-citation t) ",")))))
1456 ;; you pressed a C-u so we run this code
1462 : org-ref-insert-cite-link
1464 *** Completion in cite links
1465 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.
1467 #+BEGIN_SRC emacs-lisp :tangle no
1468 (defun org-cite-complete-link (&optional arg)
1469 "Completion function for cite links"
1471 org-ref-default-citation-link
1474 (let ((bibtex-files (org-ref-find-bibliography)))
1475 (bibtex-global-key-alist)))))
1478 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1480 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1481 (defun org-ref-insert-cite-with-completion (type)
1482 "Insert a cite link with completion"
1483 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1484 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1487 ** Storing links to a bibtex entry
1488 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.
1490 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1491 (defun org-ref-store-bibtex-entry-link ()
1492 "Save a citation link to the current bibtex entry. Saves in the default link type."
1494 (let ((link (concat org-ref-default-citation-link
1497 (bibtex-beginning-of-entry)
1498 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1499 (message "saved %s" link)
1500 (push (list link) org-stored-links)
1501 (car org-stored-links)))
1506 ** create simple text citation from bibtex entry
1508 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1509 (defun org-ref-bib-citation ()
1510 "from a bibtex entry, create and return a simple citation string."
1512 (bibtex-beginning-of-entry)
1513 (let* ((cb (current-buffer))
1514 (bibtex-expand-strings t)
1515 (entry (loop for (key . value) in (bibtex-parse-entry t)
1516 collect (cons (downcase key) value)))
1517 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1518 (year (reftex-get-bib-field "year" entry))
1519 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1520 (key (reftex-get-bib-field "=key=" entry))
1521 (journal (reftex-get-bib-field "journal" entry))
1522 (volume (reftex-get-bib-field "volume" entry))
1523 (pages (reftex-get-bib-field "pages" entry))
1524 (doi (reftex-get-bib-field "doi" entry))
1525 (url (reftex-get-bib-field "url" entry))
1527 ;;authors, "title", Journal, vol(iss):pages (year).
1528 (format "%s, \"%s\", %s, %s:%s (%s)"
1529 author title journal volume pages year)))
1533 : org-ref-bib-citation
1536 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1537 (defun org-ref-bib-html-citation ()
1538 "from a bibtex entry, create and return a simple citation with html links."
1540 (bibtex-beginning-of-entry)
1541 (let* ((cb (current-buffer))
1542 (bibtex-expand-strings t)
1543 (entry (loop for (key . value) in (bibtex-parse-entry t)
1544 collect (cons (downcase key) value)))
1545 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1546 (year (reftex-get-bib-field "year" entry))
1547 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1548 (key (reftex-get-bib-field "=key=" entry))
1549 (journal (reftex-get-bib-field "journal" entry))
1550 (volume (reftex-get-bib-field "volume" entry))
1551 (pages (reftex-get-bib-field "pages" entry))
1552 (doi (reftex-get-bib-field "doi" entry))
1553 (url (reftex-get-bib-field "url" entry))
1555 ;;authors, "title", Journal, vol(iss):pages (year).
1556 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1557 author title journal volume pages year)
1558 (when url (format " <a href=\"%s\">link</a>" url))
1559 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1563 ** open pdf from bibtex
1564 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1565 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1566 (defun org-ref-open-bibtex-pdf ()
1567 "open pdf for a bibtex entry, if it exists. assumes point is in
1568 the entry of interest in the bibfile. but does not check that."
1571 (bibtex-beginning-of-entry)
1572 (let* ((bibtex-expand-strings t)
1573 (entry (bibtex-parse-entry t))
1574 (key (reftex-get-bib-field "=key=" entry))
1575 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1577 (if (file-exists-p pdf)
1578 (org-open-link-from-string (format "[[file:%s]]" pdf))
1582 ** open notes from bibtex
1583 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1585 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1586 (defun org-ref-open-bibtex-notes ()
1587 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1589 I never did figure out how to use reftex to make this happen
1590 non-interactively. the reftex-format-citation function did not
1591 work perfectly; there were carriage returns in the strings, and
1592 it did not put the key where it needed to be. so, below I replace
1593 the carriage returns and extra spaces with a single space and
1594 construct the heading by hand."
1597 (bibtex-beginning-of-entry)
1598 (let* ((cb (current-buffer))
1599 (bibtex-expand-strings t)
1600 (entry (loop for (key . value) in (bibtex-parse-entry t)
1601 collect (cons (downcase key) value)))
1602 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1603 (year (reftex-get-bib-field "year" entry))
1604 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1605 (key (reftex-get-bib-field "=key=" entry))
1606 (journal (reftex-get-bib-field "journal" entry))
1607 (volume (reftex-get-bib-field "volume" entry))
1608 (pages (reftex-get-bib-field "pages" entry))
1609 (doi (reftex-get-bib-field "doi" entry))
1610 (url (reftex-get-bib-field "url" entry))
1613 ;; save key to clipboard to make saving pdf later easier by pasting.
1616 (kill-ring-save (point-min) (point-max)))
1618 ;; now look for entry in the notes file
1619 (if org-ref-bibliography-notes
1620 (find-file org-ref-bibliography-notes)
1621 (error "org-ref-bib-bibliography-notes is not set to anything"))
1623 (goto-char (point-min))
1624 ;; put new entry in notes if we don't find it.
1625 (unless (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1626 (insert (format "\n** TODO %s - %s" year title))
1638 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1639 key author journal year volume pages doi url key org-ref-pdf-directory key))
1643 ** open url in browser from bibtex
1645 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1647 + 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.
1649 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1650 (defun org-ref-open-in-browser ()
1651 "Open the bibtex entry at point in a browser using the url field or doi field"
1654 (bibtex-beginning-of-entry)
1656 (let ((url (bibtex-autokey-get-field "url")))
1661 (let ((doi (bibtex-autokey-get-field "doi")))
1663 (if (string-match "^http" doi)
1665 (browse-url (format "http://dx.doi.org/%s" doi)))
1667 (message "No url or doi found"))))
1671 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.
1673 *** function to upload bibtex to citeulike
1675 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1676 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1677 "with point in a bibtex entry get bibtex string and submit to citeulike.
1679 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1681 (message "uploading to citeulike")
1683 (bibtex-narrow-to-entry)
1684 (let ((startpos (point-min))
1685 (endpos (point-max))
1686 (bibtex-string (buffer-string))
1687 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1688 (with-temp-buffer (insert bibtex-string)
1689 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1692 *** The upload script
1693 Here is the python script for uploading.
1695 *************** TODO document how to get the cookies
1699 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1701 import pickle, requests, sys
1704 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1705 cookies = pickle.load(f)
1707 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1709 bibtex = sys.stdin.read()
1711 data = {'pasted':bibtex,
1713 'tag_parsing':'simple',
1714 'strip_brackets':'no',
1715 'update_id':'bib-key',
1716 'btn_bibtex':'Import BibTeX file ...'}
1718 headers = {'content-type': 'multipart/form-data',
1719 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1721 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1725 ** Build a pdf from a bibtex file
1726 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.
1728 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1729 (defun org-ref-build-full-bibliography ()
1730 "build pdf of all bibtex entries, and open it."
1732 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1733 (bib-base (file-name-sans-extension bibfile))
1734 (texfile (concat bib-base ".tex"))
1735 (pdffile (concat bib-base ".pdf")))
1738 (insert (format "\\documentclass[12pt]{article}
1739 \\usepackage[version=3]{mhchem}
1741 \\usepackage[numbers]{natbib}
1742 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1746 \\bibliographystyle{unsrtnat}
1748 \\end{document}" bib-base))
1750 (shell-command (concat "pdflatex " bib-base))
1751 (shell-command (concat "bibtex " bib-base))
1752 (shell-command (concat "pdflatex " bib-base))
1753 (shell-command (concat "pdflatex " bib-base))
1754 (kill-buffer texfile)
1755 (org-open-file pdffile)
1759 ** Extract bibtex entries cited in an org-file
1760 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.
1762 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1763 (defun org-ref-extract-bibtex-entries ()
1764 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1766 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1768 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1769 (tempname (make-temp-file "extract-bib"))
1770 (contents (buffer-string))
1771 (cb (current-buffer))
1772 basename texfile bibfile results)
1774 ;; open tempfile and insert org-buffer contents
1775 (find-file tempname)
1777 (setq basename (file-name-sans-extension
1778 (file-name-nondirectory buffer-file-name))
1779 texfile (concat tempname ".tex")
1780 bibfile (concat tempname ".bib"))
1782 ;; see if we have a bibliography, and insert the default one if not.
1784 (goto-char (point-min))
1785 (unless (re-search-forward "^bibliography:" (point-max) 'end)
1786 (insert (format "\nbibliography:%s"
1787 (mapconcat 'identity reftex-default-bibliography ",")))))
1790 ;; get a latex file and extract the references
1791 (org-latex-export-to-latex)
1794 (reftex-create-bibtex-file bibfile)
1796 ;; save results of the references
1797 (setq results (buffer-string))
1799 ;; kill buffers. these are named by basename, not full path
1800 (kill-buffer (concat basename ".bib"))
1801 (kill-buffer (concat basename ".tex"))
1802 (kill-buffer basename)
1804 (delete-file bibfile)
1805 (delete-file texfile)
1806 (delete-file tempname)
1808 ;; Now back to the original org buffer and insert the results
1809 (switch-to-buffer cb)
1810 (when (not (string= "" results))
1812 (goto-char (point-max))
1814 (org-insert-heading)
1815 (insert (format " Bibtex entries
1817 ,#+BEGIN_SRC text :tangle %s
1819 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
1822 ** Find bad cite links
1823 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.
1825 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1828 (defun index (substring list)
1829 "return the index of string in a list of strings"
1832 (dolist (arg list i)
1833 (if (string-match (concat "^" substring "$") arg)
1838 ;; return counter if found, otherwise return nil
1842 (defun org-ref-find-bad-citations ()
1843 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
1845 Makes a new buffer with clickable links."
1847 ;; generate the list of bibtex-keys and cited keys
1848 (let* ((bibtex-files (org-ref-find-bibliography))
1849 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
1850 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
1851 (bad-citations '()))
1853 (org-element-map (org-element-parse-buffer) 'link
1855 (let ((plist (nth 1 link)))
1856 (when (equal (plist-get plist ':type) "cite")
1857 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
1858 (when (not (index key bibtex-keys))
1859 (setq bad-citations (append bad-citations
1860 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
1861 key (buffer-name)(plist-get plist ':begin)))))
1866 (switch-to-buffer-other-window "*Missing citations*")
1869 (insert "* List of bad cite links\n")
1870 (insert (mapconcat 'identity bad-citations ""))
1871 ;(setq buffer-read-only t)
1872 (use-local-map (copy-keymap org-mode-map))
1873 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
1875 (when (get-buffer "*Missing citations*")
1876 (kill-buffer "*Missing citations*"))
1877 (message "No bad cite links found"))))
1880 ** Finding non-ascii characters
1881 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
1883 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1884 (defun org-ref-find-non-ascii-characters ()
1885 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
1887 (occur "[^[:ascii:]]"))
1890 ** Resort a bibtex entry
1891 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.
1893 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1894 (defun org-ref-sort-bibtex-entry ()
1895 "sort fields of entry in standard order and downcase them"
1897 (bibtex-beginning-of-entry)
1898 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
1899 (entry (bibtex-parse-entry))
1902 (type (cdr (assoc "=type=" entry)))
1903 (key (cdr (assoc "=key=" entry))))
1905 ;; these are the fields we want to order that are in this entry
1906 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
1907 ;; we do not want to reenter these fields
1908 (setq entry-fields (remove "=key=" entry-fields))
1909 (setq entry-fields (remove "=type=" entry-fields))
1911 ;;these are the other fields in the entry
1912 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
1915 ;; right now we only resort articles
1916 ((string= (downcase type) "article")
1919 (concat "@article{" key ",\n"
1922 (when (member field entry-fields)
1923 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
1926 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
1928 (bibtex-find-entry key)
1930 (bibtex-clean-entry)
1934 ** Clean a bibtex entry
1935 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.
1936 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.
1937 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1938 (defun org-ref-clean-bibtex-entry(&optional keep-key)
1939 "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"
1941 (bibtex-beginning-of-entry)
1943 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
1944 (unless (string-match ",$" (thing-at-point 'line))
1948 ;; check for empty pages, and put eid or article id in its place
1949 (let ((entry (bibtex-parse-entry))
1950 (pages (bibtex-autokey-get-field "pages"))
1951 (year (bibtex-autokey-get-field "year"))
1952 (doi (bibtex-autokey-get-field "doi"))
1953 ;; The Journal of Chemical Physics uses eid
1954 (eid (bibtex-autokey-get-field "eid")))
1956 ;; replace http://dx.doi.org/ in doi. some journals put that in,
1957 ;; but we only want the doi.
1958 (when (string-match "^http://dx.doi.org/" doi)
1959 (bibtex-beginning-of-entry)
1960 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
1962 (bibtex-make-field "doi")
1964 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
1966 ;; asap articles often set year to 0, which messes up key
1967 ;; generation. fix that.
1968 (when (string= "0" year)
1969 (bibtex-beginning-of-entry)
1970 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
1972 (bibtex-make-field "year")
1974 (insert (read-string "Enter year: ")))
1976 ;; fix pages if they are empty if there is an eid to put there.
1977 (when (string= "-" pages)
1979 (bibtex-beginning-of-entry)
1980 ;; this seems like a clunky way to set the pages field.But I
1981 ;; cannot find a better way.
1982 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
1984 (bibtex-make-field "pages")
1988 ;; replace naked & with \&
1990 (bibtex-narrow-to-entry)
1991 (bibtex-beginning-of-entry)
1992 (message "checking &")
1993 (replace-regexp " & " " \\\\& ")
1996 ;; generate a key, and if it duplicates an existing key, edit it.
1998 (let ((key (bibtex-generate-autokey)))
2000 ;; first we delete the existing key
2001 (bibtex-beginning-of-entry)
2002 (re-search-forward bibtex-entry-maybe-empty-head)
2003 (if (match-beginning bibtex-key-in-head)
2004 (delete-region (match-beginning bibtex-key-in-head)
2005 (match-end bibtex-key-in-head)))
2006 ;; check if the key is in the buffer
2007 (when (save-excursion
2008 (bibtex-search-entry key))
2010 (bibtex-search-entry key)
2011 (bibtex-copy-entry-as-kill)
2012 (switch-to-buffer-other-window "*duplicate entry*")
2014 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2017 (kill-new key))) ;; save key for pasting
2019 ;; run hooks. each of these operates on the entry with no arguments.
2020 ;; this did not work like i thought, it gives a symbolp error.
2021 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2026 org-ref-clean-bibtex-entry-hook)
2028 ;; sort fields within entry
2029 (org-ref-sort-bibtex-entry)
2030 ;; check for non-ascii characters
2031 (occur "[^[:ascii:]]")
2036 : org-ref-clean-bibtex-entry
2038 ** Sort the entries in a citation link by year
2039 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2041 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2042 (defun org-ref-get-citation-year (key)
2043 "get the year of an entry with key. Returns year as a string."
2045 (let* ((results (org-ref-get-bibtex-key-and-file key))
2046 (bibfile (cdr results)))
2048 (insert-file-contents bibfile)
2049 (bibtex-search-entry key nil 0)
2050 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2053 (defun org-ref-sort-citation-link ()
2054 "replace link at point with sorted link by year"
2056 (let* ((object (org-element-context))
2057 (type (org-element-property :type object))
2058 (begin (org-element-property :begin object))
2059 (end (org-element-property :end object))
2060 (link-string (org-element-property :path object))
2062 (setq keys (org-ref-split-and-strip-string link-string))
2063 (setq years (mapcar 'org-ref-get-citation-year keys))
2064 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2065 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2066 ;; now get the keys separated by commas
2067 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2068 ;; and replace the link with the sorted keys
2069 (cl--set-buffer-substring begin end (concat type ":" keys))))
2072 ** Sort entries in citation links with shift-arrow keys
2073 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2074 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2075 (defun org-ref-swap-keys (i j keys)
2076 "swap the keys in a list with index i and j"
2077 (let ((tempi (nth i keys)))
2078 (setf (nth i keys) (nth j keys))
2079 (setf (nth j keys) tempi))
2082 (defun org-ref-swap-citation-link (direction)
2083 "move citation at point in direction +1 is to the right, -1 to the left"
2085 (let* ((object (org-element-context))
2086 (type (org-element-property :type object))
2087 (begin (org-element-property :begin object))
2088 (end (org-element-property :end object))
2089 (link-string (org-element-property :path object))
2091 ;; We only want this to work on citation links
2092 (when (-contains? org-ref-cite-types type)
2093 (setq key (org-ref-get-bibtex-key-under-cursor))
2094 (setq keys (org-ref-split-and-strip-string link-string))
2095 (setq i (index key keys)) ;; defined in org-ref
2096 (if (> direction 0) ;; shift right
2097 (org-ref-swap-keys i (+ i 1) keys)
2098 (org-ref-swap-keys i (- i 1) keys))
2099 (setq keys (mapconcat 'identity keys ","))
2100 ;; and replace the link with the sorted keys
2101 (cl--set-buffer-substring begin end (concat type ":" keys))
2102 ;; now go forward to key so we can move with the key
2103 (re-search-forward key)
2104 (goto-char (match-beginning 0)))))
2106 ;; add hooks to make it work
2107 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2108 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2111 I like convenience. Here are some aliases for faster typing.
2113 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2114 (defalias 'oro 'org-ref-open-citation-at-point)
2115 (defalias 'orc 'org-ref-citation-at-point)
2116 (defalias 'orp 'org-ref-open-pdf-at-point)
2117 (defalias 'oru 'org-ref-open-url-at-point)
2118 (defalias 'orn 'org-ref-open-notes-at-point)
2120 (defalias 'orib 'org-ref-insert-bibliography-link)
2121 (defalias 'oric 'org-ref-insert-cite-link)
2122 (defalias 'orir 'org-ref-insert-ref-link)
2123 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2125 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2128 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2135 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2137 [[elisp:(org-babel-load-file "org-ref.org")]]