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>.")
97 ("book" . "%a, %t, %u (%y).")
99 ("proceedings" . "%e, %t in %S, %u (%y).")
101 ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
103 "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."
107 (defcustom org-ref-open-notes-function
113 ;;(org-tree-to-indirect-buffer)
114 (outline-previous-visible-heading 1)
115 (recenter-top-bottom 0))
116 "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")
119 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.
121 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
122 (defcustom org-ref-cite-types
123 '("cite" "nocite" ;; the default latex cite commands
124 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
125 "citet" "citet*" "citep" "citep*"
126 "citealt" "citealt*" "citealp" "citealp*"
128 "citeauthor" "citeauthor*"
129 "citeyear" "citeyear*"
130 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
132 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
134 "parencite" "Parencite"
135 "footcite" "footcitetext"
136 "textcite" "Textcite"
137 "smartcite" "Smartcite"
138 "cite*" "parencite*" "supercite"
139 "autocite" "Autocite" "autocite*" "Autocite*"
141 "citetitle" "citetitle*"
142 "citedate" "citedate*"
144 "fullcite" "footfullcite"
145 ;; "volcite" "Volcite" cannot support the syntax
146 "notecite" "Notecite"
147 "pnotecite" "Pnotecite"
149 ;; multicites. Very limited support for these.
150 "cites" "Cites" "parencites" "Parencites"
151 "footcites" "footcitetexts"
152 "smartcites" "Smartcites" "textcites" "Textcites"
153 "supercites" "autocites" "Autocites"
155 "List of citation types known in org-ref"
156 :type '(repeat :tag "List of citation types" string)
160 We need a hook variable to store user-defined bibtex entry cleaning functions
161 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
162 (defcustom org-ref-clean-bibtex-entry-hook nil
163 "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
169 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
170 (defvar org-ref-bibliography-files
172 "variable to hold bibliography files to be searched")
175 ** org-mode / reftex setup
177 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.
179 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
180 (defun org-mode-reftex-setup ()
181 (load-library "reftex")
182 (and (buffer-file-name)
183 (file-exists-p (buffer-file-name))
184 (global-auto-revert-mode t)
186 (make-local-variable 'reftex-cite-format)
187 (setq reftex-cite-format 'org)
188 (define-key org-mode-map (kbd org-ref-insert-cite-key) 'org-ref-insert-cite-link))
190 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
192 (eval-after-load 'reftex-vars
194 (add-to-list 'reftex-cite-format-builtin
195 '(org "Org-mode citation"
196 ((?\C-m . "cite:%l") ; default
197 (?d . ",%l") ; for appending
203 (?h . "citeauthor:%l")
204 (?H . "citeauthor*:%l")
211 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.
213 #+BEGIN_SRC emacs-lisp :tangle no
215 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
216 (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l")
217 (?z . "newcite:%l"))))
220 You can define a new citation link like this:
221 #+BEGIN_SRC emacs-lisp :tangle no
222 (org-ref-define-citation-link "citez" ?z)
226 Most of this library is the creation of functional links to help with references and citations.
228 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.
230 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
231 (defun org-ref-strip-string (string)
232 "strip leading and trailing whitespace from the string"
233 (replace-regexp-in-string
234 (concat search-whitespace-regexp "$" ) ""
235 (replace-regexp-in-string
236 (concat "^" search-whitespace-regexp ) "" string)))
239 It is helpful to make the previous function operate on a list of strings here.
241 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
242 (defun org-ref-split-and-strip-string (string)
243 "split key-string and strip keys. Assumes the key-string is comma delimited"
244 (mapcar 'org-ref-strip-string (split-string string ",")))
247 ** bibliography and bibliographystyle
248 *** An html bibliography
250 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.
252 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
253 (defun org-ref-reftex-get-bib-field (field entry &optional format)
254 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
256 (setq result (reftex-get-bib-field field entry format))
257 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
258 (setq result (substring result 1 -1)))
259 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
260 (setq result (substring result 1 -1)))
263 (defun org-ref-reftex-format-citation (entry format)
264 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
265 to the format argument. The format is a string with these percent escapes.
267 In the format, the following percent escapes will be expanded.
269 %l The BibTeX label of the citation.
270 %a List of author names, see also `reftex-cite-punctuation'.
271 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
272 %A First author name only.
273 %e Works like %a, but on list of editor names. (%2e and %E work a well)
275 It is also possible to access all other BibTeX database fields:
276 %b booktitle %c chapter %d edition %h howpublished
277 %i institution %j journal %k key %m month
278 %n number %o organization %p pages %P first page
279 %r address %s school %u publisher %t title
281 %B booktitle, abbreviated %T title, abbreviated
286 Usually, only %l is needed. The other stuff is mainly for the echo area
287 display, and for (setq reftex-comment-citations t).
289 %< as a special operator kills punctuation and space around it after the
290 string has been formatted.
292 A pair of square brackets indicates an optional argument, and RefTeX
293 will prompt for the values of these arguments.
295 Beware that all this only works with BibTeX database files. When
296 citations are made from the \bibitems in an explicit thebibliography
297 environment, only %l is available."
298 ;; Format a citation from the info in the BibTeX ENTRY
300 (unless (stringp format) (setq format "\\cite{%l}"))
302 (if (and reftex-comment-citations
303 (string-match "%l" reftex-cite-comment-format))
304 (error "reftex-cite-comment-format contains invalid %%l"))
307 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
309 (let ((n (string-to-number (match-string 4 format)))
310 (l (string-to-char (match-string 5 format)))
316 (org-ref-reftex-get-bib-field "&key" entry)
317 (if reftex-comment-citations
318 reftex-cite-comment-format
320 ((= l ?a) (reftex-format-names
321 (reftex-get-bib-names "author" entry)
323 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
324 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
325 ((= l ?B) (reftex-abbreviate-title
326 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
327 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
328 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
329 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
330 ((= l ?e) (reftex-format-names
331 (reftex-get-bib-names "editor" entry)
333 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
334 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
335 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
336 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
337 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
338 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
339 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
340 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
341 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
342 ((= l ?P) (car (split-string
343 (org-ref-reftex-get-bib-field "pages" entry)
345 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
346 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
347 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
348 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
349 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
350 ;; strip enclosing brackets from title if they are there
351 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
352 ((= l ?T) (reftex-abbreviate-title
353 (org-ref-reftex-get-bib-field "title" entry)))
354 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
355 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
358 (setq b (match-beginning 2) e (match-end 2))
359 (setq b (match-beginning 3) e (match-end 3)))
360 (setq format (concat (substring format 0 b) rpl (substring format e)))))
361 (while (string-match "%%" format)
362 (setq format (replace-match "%" t t format)))
363 (while (string-match "[ ,.;:]*%<" format)
364 (setq format (replace-match "" t t format)))
365 ;; also replace carriage returns, tabs, and multiple whitespaces
366 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
369 (defun org-ref-get-bibtex-entry-citation (key)
370 "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
372 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
373 (file) (entry) (bibtex-entry) (entry-type) (format))
375 (setq file (catch 'result
376 (loop for file in org-ref-bibliography-files do
377 (if (org-ref-key-in-file-p key (file-truename file))
379 (message "%s not found in %s" key (file-truename file))))))
382 (insert-file-contents file)
383 (bibtex-search-entry key nil 0)
384 (setq bibtex-entry (bibtex-parse-entry))
385 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
386 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
388 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
390 (bibtex-narrow-to-entry)
391 (setq entry (buffer-string)))))
396 : org-ref-reftex-format-citation
398 Here is how to use the function. You call it with point in an entry in a bibtex file.
400 #+BEGIN_SRC emacs-lisp :tangle no
401 (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>."))
402 (org-ref-get-bibtex-entry-citation "armiento-2014-high"))
405 : 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>.
407 I am not sure why full author names are not used.
409 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
411 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
412 (defun org-ref-get-bibtex-keys ()
413 "return a list of unique keys in the buffer."
415 (org-element-map (org-element-parse-buffer) 'link
417 (let ((plist (nth 1 link)))
418 (when (-contains? org-ref-cite-types (plist-get plist ':type))
421 (org-ref-split-and-strip-string (plist-get plist ':path)))
422 (when (not (-contains? keys key))
423 (setq keys (append keys (list key)))))))))
424 ;; Sort keys alphabetically
425 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
429 This function gets the html for one entry.
431 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
432 (defun org-ref-get-bibtex-entry-html (key)
433 "returns an html string for the bibliography entry corresponding to key"
435 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
438 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
440 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
441 (defun org-ref-get-html-bibliography ()
442 "Create an html bibliography when there are keys"
443 (let ((keys (org-ref-get-bibtex-keys)))
445 (concat "<h1>Bibliography</h1>
447 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
451 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.
453 *** An org bibliography
454 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.
456 First, we get the string for a single entry.
457 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
458 (defun org-ref-get-bibtex-entry-org (key)
459 "returns an org string for the bibliography entry corresponding to key"
460 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
461 (file) (entry) (bibtex-entry) (entry-type) (format))
463 (setq file (catch 'result
464 (loop for file in org-ref-bibliography-files do
465 (if (org-ref-key-in-file-p key (file-truename file))
467 (message "%s not found in %s" key (file-truename file))))))
470 (insert-file-contents file)
471 (bibtex-search-entry key nil 0)
472 (setq entry (bibtex-parse-entry))
477 " (org-ref-reftex-get-bib-field "author" entry)
478 (org-ref-reftex-get-bib-field "title" entry)
479 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
480 (mapconcat (lambda (element) (format " :%s: %s"
481 (upcase (car element))
487 Now, we loop over the keys, and combine all the entries into a bibliography.
488 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
489 (defun org-ref-get-org-bibliography ()
490 "Create an org bibliography when there are keys"
491 (let ((keys (org-ref-get-bibtex-keys)))
493 (concat "* Bibliography
495 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
499 *** An ascii bibliography
501 This function gets the html for one entry.
503 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
504 (defun org-ref-get-bibtex-entry-ascii (key)
505 "returns an ascii string for the bibliography entry corresponding to key"
507 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
510 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
512 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
513 (defun org-ref-get-ascii-bibliography ()
514 "Create an html bibliography when there are keys"
515 (let ((keys (org-ref-get-bibtex-keys)))
521 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
527 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.
529 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
530 (org-add-link-type "bibliography"
531 ;; this code is run on clicking. The bibliography
532 ;; may contain multiple files. this code finds the
533 ;; one you clicked on and opens it.
534 (lambda (link-string)
535 ;; get link-string boundaries
536 ;; we have to go to the beginning of the line, and then search forward
539 ;; object is the link you clicked on
540 (object (org-element-context))
542 (link-string-beginning)
546 (goto-char (org-element-property :begin object))
547 (search-forward link-string nil nil 1)
548 (setq link-string-beginning (match-beginning 0))
549 (setq link-string-end (match-end 0)))
551 ;; We set the reftex-default-bibliography
552 ;; here. it should be a local variable only in
553 ;; the current buffer. We need this for using
554 ;; reftex to do citations.
555 (set (make-local-variable 'reftex-default-bibliography)
556 (split-string (org-element-property :path object) ","))
558 ;; now if we have comma separated bibliographies
559 ;; we find the one clicked on. we want to
560 ;; search forward to next comma from point
562 (if (search-forward "," link-string-end 1 1)
563 (setq key-end (- (match-end 0) 1)) ; we found a match
564 (setq key-end (point)))) ; no comma found so take the point
565 ;; and backward to previous comma from point
567 (if (search-backward "," link-string-beginning 1 1)
568 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
569 (setq key-beginning (point)))) ; no match found
570 ;; save the key we clicked on.
571 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
572 (find-file bibfile))) ; open file on click
575 (lambda (keyword desc format)
577 ((eq format 'org) (org-ref-get-org-bibliography))
578 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
579 ((eq format 'html) (org-ref-get-html-bibliography))
581 ;; write out the latex bibliography command
582 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" (expand-file-name keyword)))))))
585 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
586 (org-add-link-type "printbibliography"
587 (lambda (arg) (message "Nothing implemented for clicking here."))
588 (lambda (keyword desc format)
590 ((eq format 'org) (org-ref-get-org-bibliography))
591 ((eq format 'html) (org-ref-get-html-bibliography))
593 ;; write out the biblatex bibliography command
594 "\\printbibliography"))
598 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, ...
600 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
601 (org-add-link-type "bibliographystyle"
602 (lambda (arg) (message "Nothing implemented for clicking here."))
603 (lambda (keyword desc format)
606 ;; write out the latex bibliography command
607 (format "\\bibliographystyle{%s}" keyword)))))
610 *** Completion for bibliography link
613 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
614 (defun org-bibliography-complete-link (&optional arg)
615 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
617 (defun org-ref-insert-bibliography-link ()
618 "insert a bibliography with completion"
620 (insert (org-bibliography-complete-link)))
624 This is apparently used for biblatex.
625 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
626 (org-add-link-type "addbibresource"
627 ;; this code is run on clicking. The addbibresource
628 ;; may contain multiple files. this code finds the
629 ;; one you clicked on and opens it.
630 (lambda (link-string)
631 ;; get link-string boundaries
632 ;; we have to go to the beginning of the line, and then search forward
635 ;; object is the link you clicked on
636 (object (org-element-context))
638 (link-string-beginning)
642 (goto-char (org-element-property :begin object))
643 (search-forward link-string nil nil 1)
644 (setq link-string-beginning (match-beginning 0))
645 (setq link-string-end (match-end 0)))
647 ;; We set the reftex-default-addbibresource
648 ;; here. it should be a local variable only in
649 ;; the current buffer. We need this for using
650 ;; reftex to do citations.
651 (set (make-local-variable 'reftex-default-addbibresource)
652 (split-string (org-element-property :path object) ","))
654 ;; now if we have comma separated bibliographies
655 ;; we find the one clicked on. we want to
656 ;; search forward to next comma from point
658 (if (search-forward "," link-string-end 1 1)
659 (setq key-end (- (match-end 0) 1)) ; we found a match
660 (setq key-end (point)))) ; no comma found so take the point
661 ;; and backward to previous comma from point
663 (if (search-backward "," link-string-beginning 1 1)
664 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
665 (setq key-beginning (point)))) ; no match found
666 ;; save the key we clicked on.
667 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
668 (find-file bibfile))) ; open file on click
671 (lambda (keyword desc format)
673 ((eq format 'html) (format "")); no output for html
675 ;; write out the latex addbibresource command
676 (format "\\addbibresource{%s}" keyword)))))
681 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.
683 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
684 (defun org-ref-list-of-figures (&optional arg)
685 "Generate buffer with list of figures in them"
687 (save-excursion (widen)
688 (let* ((c-b (buffer-name))
691 (org-element-map (org-element-parse-buffer) 'link
693 "create a link for to the figure"
695 (and (string= (org-element-property :type link) "file")
697 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
698 (org-element-property :path link)))
701 (let* ((start (org-element-property :begin link))
702 (parent (car (cdr (org-element-property :parent link))))
703 (caption (caaar (plist-get parent :caption)))
704 (name (plist-get parent :name)))
707 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
708 c-b start counter (or name "") caption)
710 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
711 c-b start counter (or name "")))))))))
712 (switch-to-buffer "*List of Figures*")
713 (setq buffer-read-only nil)
716 (insert (mapconcat 'identity list-of-figures ""))
717 (setq buffer-read-only t)
718 (use-local-map (copy-keymap org-mode-map))
719 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
723 'org-ref-list-of-figures ; on click
724 (lambda (keyword desc format)
727 (format "\\listoffigures")))))
732 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
733 (defun org-ref-list-of-tables (&optional arg)
734 "Generate a buffer with a list of tables"
738 (let* ((c-b (buffer-name))
741 (org-element-map (org-element-parse-buffer 'element) 'table
743 "create a link for to the table"
745 (let ((start (org-element-property :begin table))
746 (name (org-element-property :name table))
747 (caption (caaar (org-element-property :caption table))))
750 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
751 c-b start counter (or name "") caption)
753 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
754 c-b start counter (or name ""))))))))
755 (switch-to-buffer "*List of Tables*")
756 (setq buffer-read-only nil)
759 (insert (mapconcat 'identity list-of-tables ""))
760 (setq buffer-read-only t)
761 (use-local-map (copy-keymap org-mode-map))
762 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
766 'org-ref-list-of-tables
767 (lambda (keyword desc format)
770 (format "\\listoftables")))))
774 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.
775 *************** TODO search tblnames, custom_ids and check for case sensitivity
778 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
782 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
783 (message (format "%s occurences"
784 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
785 ;; for tblname, it is not enough to get word boundary
786 ;; tab-little and tab-little-2 match then.
787 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
788 (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
789 ;; this is the org-format #+label:
790 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))))
791 (lambda (keyword desc format)
793 ((eq format 'html) (format "(<label>%s</label>)" path))
795 (format "\\label{%s}" keyword)))))
798 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.
800 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
801 (defun org-label-store-link ()
802 "store a link to a label. The output will be a ref to that label"
803 ;; First we have to make sure we are on a label link.
804 (let* ((object (org-element-context)))
805 (when (and (equal (org-element-type object) 'link)
806 (equal (org-element-property :type object) "label"))
807 (org-store-link-props
809 :link (concat "ref:" (org-element-property :path object))))
811 ;; Store link on table
812 (when (equal (org-element-type object) 'table)
813 (org-store-link-props
815 :link (concat "ref:" (org-element-property :name object))))
817 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
818 ;; store link on heading with custom_id
819 ; (when (and (equal (org-element-type object) 'headline)
820 ; (org-entry-get (point) "CUSTOM_ID"))
821 ; (org-store-link-props
823 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
825 ;; and to #+label: lines
826 (when (and (equal (org-element-type object) 'paragraph)
827 (org-element-property :name object))
828 (org-store-link-props
830 :link (concat "ref:" (org-element-property :name object))))
833 (add-hook 'org-store-link-functions 'org-label-store-link)
837 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.
839 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
841 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
845 "on clicking goto the label. Navigate back with C-c &"
847 ;; next search from beginning of the buffer
849 ;; it is possible you would not find the label if narrowing is in effect
856 (goto-char (point-min))
857 (re-search-forward (format "label:%s\\b" label) nil t))
861 (goto-char (point-min))
862 (re-search-forward (format "\\label{%s}" label) nil t))
864 ;; #+label: name org-definition
866 (goto-char (point-min))
867 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
871 (goto-char (point-min))
872 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
874 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
875 ;; you need [[#label]] links.
878 ; (goto-char (point-min))
879 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
881 ;; we did not find anything, so go back to where we came
883 (error "%s not found" label))
884 (message "go back with (org-mark-ring-goto) `C-c &`"))
886 (lambda (keyword desc format)
888 ((eq format 'html) (format "(<ref>%s</ref>)" path))
890 (format "\\ref{%s}" keyword)))))
893 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.
895 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
896 (defun org-ref-get-custom-ids ()
897 "return a list of custom_id properties in the buffer"
898 (let ((results '()) custom_id)
901 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
902 (when (not (null custom_id))
903 (setq results (append results (list custom_id)))))))
907 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
908 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
909 (defun org-ref-get-latex-labels ()
911 (goto-char (point-min))
913 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
914 (add-to-list 'matches (match-string-no-properties 1) t))
918 Finally, we get the table names.
920 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
921 (defun org-ref-get-tblnames ()
922 (org-element-map (org-element-parse-buffer 'element) 'table
924 (org-element-property :name table))))
927 Now, we can put all the labels together which will give us a list of candidates.
929 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
930 (defun org-ref-get-labels ()
931 "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
935 (goto-char (point-min))
937 (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
938 (add-to-list 'matches (match-string-no-properties 1) t))
939 (append matches (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
942 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.
944 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
945 (defun org-ref-complete-link (&optional arg)
946 "Completion function for ref links"
948 (setq label (completing-read "label: " (org-ref-get-labels)))
949 (format "ref:%s" label)))
952 Alternatively, you may want to just call a function that inserts a link with completion:
954 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
955 (defun org-ref-insert-ref-link ()
957 (insert (org-ref-complete-link)))
962 This refers to the page of a label in LaTeX.
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
976 (goto-char (point-min))
977 (re-search-forward (format "label:%s\\b" label) nil t))
981 (goto-char (point-min))
982 (re-search-forward (format "\\label{%s}" label) nil t))
984 ;; #+label: name org-definition
986 (goto-char (point-min))
987 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
991 (goto-char (point-min))
992 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
994 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
995 ;; you need [[#label]] links.
998 ; (goto-char (point-min))
999 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1001 ;; we did not find anything, so go back to where we came
1002 (org-mark-ring-goto)
1003 (error "%s not found" label))
1004 (message "go back with (org-mark-ring-goto) `C-c &`"))
1006 (lambda (keyword desc format)
1008 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1010 (format "\\pageref{%s}" keyword)))))
1013 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1014 (defun org-pageref-complete-link (&optional arg)
1015 "Completion function for ref links"
1017 (setq label (completing-read "label: " (org-ref-get-labels)))
1018 (format "ref:%s" label)))
1021 Alternatively, you may want to just call a function that inserts a link with completion:
1023 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1024 (defun org-pageref-insert-ref-link ()
1026 (insert (org-pageref-complete-link)))
1031 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.
1033 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1037 "on clicking goto the label. Navigate back with C-c &"
1038 (org-mark-ring-push)
1039 ;; next search from beginning of the buffer
1045 (goto-char (point-min))
1046 (re-search-forward (format "\\label{%s}" label) nil t))
1048 ;; we did not find anything, so go back to where we came
1049 (org-mark-ring-goto)
1050 (error "%s not found" label))
1051 (message "go back with (org-mark-ring-goto) `C-c &`"))
1053 (lambda (keyword desc format)
1055 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1057 (format "\\nameref{%s}" keyword)))))
1061 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1063 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1067 "on clicking goto the label. Navigate back with C-c &"
1068 (org-mark-ring-push)
1069 ;; next search from beginning of the buffer
1071 (goto-char (point-min))
1074 ;; search forward for the first match
1076 (re-search-forward (format "label:%s" label) nil t)
1078 (re-search-forward (format "\\label{%s}" label) nil t)
1079 ;; #+label: name org-definition
1080 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1081 (org-mark-ring-goto)
1082 (error "%s not found" label))
1083 (message "go back with (org-mark-ring-goto) `C-c &`"))
1085 (lambda (keyword desc format)
1087 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1089 (format "\\eqref{%s}" keyword)))))
1094 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.
1096 *** Implementing the click actions of cite
1098 **** Getting the key we clicked on
1099 The first thing we need is to get the bibtex key we clicked on.
1101 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1102 (defun org-ref-get-bibtex-key-under-cursor ()
1103 "returns key under the bibtex cursor. We search forward from
1104 point to get a comma, or the end of the link, and then backwards
1105 to get a comma, or the beginning of the link. that delimits the
1106 keyword we clicked on. We also strip the text properties."
1108 (let* ((object (org-element-context))
1109 (link-string (org-element-property :path object)))
1110 ;; you may click on the part before the citations. here we make
1111 ;; sure to move to the beginning so you get the first citation.
1113 (goto-char (org-element-property :begin object))
1114 (search-forward link-string (org-element-property :end object))
1115 (goto-char (match-beginning 0))
1116 ;; check if we clicked before the path and move as needed.
1117 (unless (< cp (point))
1120 (if (not (org-element-property :contents-begin object))
1121 ;; this means no description in the link
1123 ;; we need the link path start and end
1125 (goto-char (org-element-property :begin object))
1126 (search-forward link-string nil nil 1)
1127 (setq link-string-beginning (match-beginning 0))
1128 (setq link-string-end (match-end 0)))
1130 ;; The key is the text between commas, or the link boundaries
1132 (if (search-forward "," link-string-end t 1)
1133 (setq key-end (- (match-end 0) 1)) ; we found a match
1134 (setq key-end link-string-end))) ; no comma found so take the end
1135 ;; and backward to previous comma from point which defines the start character
1137 (if (search-backward "," link-string-beginning 1 1)
1138 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1139 (setq key-beginning link-string-beginning))) ; no match found
1140 ;; save the key we clicked on.
1141 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1142 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1144 ;; link with description. assume only one key
1148 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.
1150 **** Getting the bibliographies
1151 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1152 (defun org-ref-find-bibliography ()
1153 "find the bibliography in the buffer.
1154 This function sets and returns cite-bibliography-files, which is a list of files
1155 either from bibliography:f1.bib,f2.bib
1156 \bibliography{f1,f2}
1157 internal bibliographies
1159 falling back to what the user has set in org-ref-default-bibliography
1164 (goto-char (point-min))
1165 ;; look for a bibliography link
1166 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1167 (setq org-ref-bibliography-files
1168 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1169 (throw 'result org-ref-bibliography-files))
1172 ;; we did not find a bibliography link. now look for \bibliography
1173 (goto-char (point-min))
1174 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1175 ;; split, and add .bib to each file
1176 (setq org-ref-bibliography-files
1177 (mapcar (lambda (x) (concat x ".bib"))
1178 (mapcar 'org-ref-strip-string
1179 (split-string (match-string 1) ","))))
1180 (throw 'result org-ref-bibliography-files))
1182 ;; no bibliography found. maybe we need a biblatex addbibresource
1183 (goto-char (point-min))
1184 ;; look for a bibliography link
1185 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1186 (setq org-ref-bibliography-files
1187 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1188 (throw 'result org-ref-bibliography-files))
1190 ;; we did not find anything. use defaults
1191 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1193 ;; set reftex-default-bibliography so we can search
1194 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1195 org-ref-bibliography-files)
1198 **** Finding the bibliography file a key is in
1199 Now, we can see if an entry is in a file.
1201 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1202 (defun org-ref-key-in-file-p (key filename)
1203 "determine if the key is in the file"
1204 (interactive "skey: \nsFile: ")
1205 (save-current-buffer
1206 (let ((bibtex-files (list filename)))
1207 (bibtex-search-entry key t))))
1210 Finally, we want to know which file the key is in.
1212 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1213 (defun org-ref-get-bibtex-key-and-file (&optional key)
1214 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1216 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1219 (setq key (org-ref-get-bibtex-key-under-cursor)))
1220 (setq file (catch 'result
1221 (loop for file in org-ref-bibliography-files do
1222 (if (org-ref-key-in-file-p key (file-truename file))
1223 (throw 'result file)))))
1227 **** Creating the menu for when we click on a key
1229 :ID: d7b7530b-802f-42b1-b61e-1e77da33e278
1231 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.
1233 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1234 (defun org-ref-get-menu-options ()
1235 "returns a dynamically determined string of options for the citation under point.
1237 we check to see if there is pdf, and if the key actually exists in the bibliography"
1239 (let* ((results (org-ref-get-bibtex-key-and-file))
1241 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1242 (bibfile (cdr results))
1243 m1 m2 m3 m4 m5 menu-string)
1244 (setq m1 (if bibfile
1248 (setq m3 (if (file-exists-p pdf-file)
1254 (string= (catch 'url
1258 (insert-file-contents bibfile)
1259 (bibtex-search-entry key)
1261 (string= (setq url (bibtex-autokey-get-field "url")) ""))
1265 (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1266 (throw 'url url))))) "")))
1267 "(u)rl" "(no url found)"))
1269 (setq m2 (if bibfile
1271 (setq citation (progn
1273 (insert-file-contents bibfile)
1274 (bibtex-search-entry key)
1275 (org-ref-bib-citation))))
1279 (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") " "))
1283 **** convenience functions to act on citation at point
1285 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1287 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.
1289 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1290 (defun org-ref-open-pdf-at-point ()
1291 "open the pdf for bibtex key under point if it exists"
1293 (let* ((results (org-ref-get-bibtex-key-and-file))
1295 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1296 (if (file-exists-p pdf-file)
1297 (org-open-file pdf-file)
1298 (message "no pdf found for %s" key))))
1301 (defun org-ref-open-url-at-point ()
1302 "open the url for bibtex key under point."
1304 (let* ((results (org-ref-get-bibtex-key-and-file))
1306 (bibfile (cdr results)))
1309 (insert-file-contents bibfile)
1310 (bibtex-search-entry key)
1311 ;; I like this better than bibtex-url which does not always find
1314 (let ((url (bibtex-autokey-get-field "url")))
1319 (let ((doi (bibtex-autokey-get-field "doi")))
1321 (if (string-match "^http" doi)
1323 (browse-url (format "http://dx.doi.org/%s" doi)))
1324 (throw 'done nil))))))))
1326 (defun org-ref-open-notes-at-point ()
1327 "open the notes for bibtex key under point."
1329 (let* ((results (org-ref-get-bibtex-key-and-file))
1331 (bibfile (cdr results)))
1334 (insert-file-contents bibfile)
1335 (bibtex-search-entry key)
1336 (org-ref-open-bibtex-notes)))))
1338 (defun org-ref-citation-at-point ()
1339 "give message of current citation at point"
1341 (let* ((cb (current-buffer))
1342 (results (org-ref-get-bibtex-key-and-file))
1344 (bibfile (cdr results)))
1345 (message "%s" (progn
1347 (insert-file-contents bibfile)
1348 (bibtex-search-entry key)
1349 (org-ref-bib-citation))))))
1351 (defun org-ref-open-citation-at-point ()
1352 "open bibtex file to key at point"
1354 (let* ((cb (current-buffer))
1355 (results (org-ref-get-bibtex-key-and-file))
1357 (bibfile (cdr results)))
1359 (bibtex-search-entry key)))
1362 **** the actual minibuffer menu
1363 Now, we create the menu.
1365 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1366 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1367 "use a minibuffer to select options for the citation under point.
1369 you select your option with a single key press."
1371 (let* ((choice (read-char (org-ref-get-menu-options)))
1372 (results (org-ref-get-bibtex-key-and-file))
1374 (cb (current-buffer))
1375 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1376 (bibfile (cdr results)))
1382 (bibtex-search-entry key))
1386 (org-ref-citation-at-point))
1392 (= choice ?\ )) ; space
1393 ;; this clears the minibuffer
1398 (org-ref-open-pdf-at-point))
1402 (org-ref-open-notes-at-point))
1406 (org-ref-open-url-at-point))
1408 ;; anything else we just quit.
1413 *** A function to format a cite link
1415 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.
1417 #+BEGIN_SRC emacs-lisp :tangle no
1418 ;(defun org-ref-cite-link-format (keyword desc format)
1420 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1421 ; ((eq format 'latex)
1422 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1423 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1427 *** The actual cite link
1428 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1430 #+BEGIN_SRC emacs-lisp :tangle no
1433 ; 'org-ref-cite-onclick-minibuffer-menu
1434 ; 'org-ref-cite-link-format)
1437 *** Automatic definition of the cite links
1438 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.
1440 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1441 (defmacro org-ref-make-completion-function (type)
1442 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1448 (let ((bibtex-files (org-ref-find-bibliography)))
1449 (bibtex-global-key-alist))))))
1452 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.
1454 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1455 (defmacro org-ref-make-format-function (type)
1456 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1461 (format "[[#%s][%s]]" key key))
1462 (org-ref-split-and-strip-string keyword) ","))
1469 (org-ref-split-and-strip-string keyword) ",") "]"))
1474 (format "<a href=\"#%s\">%s</a>" key key))
1475 (org-ref-split-and-strip-string keyword) ","))
1478 (if (string= (substring type -1) "s")
1479 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1480 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1481 (org-ref-split-and-strip-string keyword) ""))
1483 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1484 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1490 We create the links by mapping the function onto the list of defined link types.
1492 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1493 (defun org-ref-format-citation-description (desc)
1494 "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 ::."
1497 ((string-match "::" desc)
1498 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1499 (t (format "[%s]" desc))))
1501 (defun org-ref-define-citation-link (type &optional key)
1502 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1503 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1504 and the completion function."
1505 (interactive "sCitation Type: \ncKey: ")
1507 ;; create the formatting function
1508 (eval `(org-ref-make-format-function ,type))
1513 'org-ref-cite-onclick-minibuffer-menu
1514 (quote ,(intern (format "org-ref-format-%s" type)))))
1516 ;; create the completion function
1517 (eval `(org-ref-make-completion-function ,type))
1519 ;; store new type so it works with adding citations, which checks
1520 ;; for existence in this list
1521 (add-to-list 'org-ref-cite-types type)
1523 ;; and finally if a key is specified, we modify the reftex menu
1525 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1526 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1527 `((,key . ,(concat type ":%l")))))))
1529 ;; create all the link types and their completion functions
1530 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1533 *** org-ref-insert-cite-link
1534 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.
1536 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1537 (defun org-ref-insert-cite-link (alternative-cite)
1538 "Insert a default citation link using reftex. If you are on a link, it
1539 appends to the end of the link, otherwise, a new link is
1540 inserted. Use a prefix arg to get a menu of citation types."
1542 (org-ref-find-bibliography)
1543 (let* ((object (org-element-context))
1544 (link-string-beginning (org-element-property :begin object))
1545 (link-string-end (org-element-property :end object))
1546 (path (org-element-property :path object)))
1548 (if (not alternative-cite)
1551 ;; case where we are in a link
1552 ((and (equal (org-element-type object) 'link)
1553 (-contains? org-ref-cite-types (org-element-property :type object)))
1554 (goto-char link-string-end)
1555 ;; sometimes there are spaces at the end of the link
1556 ;; this code moves point pack until no spaces are there
1557 (while (looking-back " ") (backward-char))
1558 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1560 ;; We are next to a link, and we want to append
1563 (and (equal (org-element-type (org-element-context)) 'link)
1564 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1565 (while (looking-back " ") (backward-char))
1566 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1568 ;; insert fresh link
1571 (concat org-ref-default-citation-link
1573 (mapconcat 'identity (reftex-citation t) ",")))))
1575 ;; you pressed a C-u so we run this code
1581 : org-ref-insert-cite-link
1583 *** Completion in cite links
1584 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.
1586 #+BEGIN_SRC emacs-lisp :tangle no
1587 (defun org-cite-complete-link (&optional arg)
1588 "Completion function for cite links"
1590 org-ref-default-citation-link
1593 (let ((bibtex-files (org-ref-find-bibliography)))
1594 (bibtex-global-key-alist)))))
1597 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1599 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1600 (defun org-ref-insert-cite-with-completion (type)
1601 "Insert a cite link with completion"
1602 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1603 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1606 ** Storing links to a bibtex entry
1607 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.
1609 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1610 (defun org-ref-store-bibtex-entry-link ()
1611 "Save a citation link to the current bibtex entry. Saves in the default link type."
1613 (let ((link (concat org-ref-default-citation-link
1616 (bibtex-beginning-of-entry)
1617 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1618 (message "saved %s" link)
1619 (push (list link) org-stored-links)
1620 (car org-stored-links)))
1625 ** create simple text citation from bibtex entry
1627 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1628 (defun org-ref-bib-citation ()
1629 "from a bibtex entry, create and return a simple citation string."
1631 (bibtex-beginning-of-entry)
1632 (let* ((cb (current-buffer))
1633 (bibtex-expand-strings t)
1634 (entry (loop for (key . value) in (bibtex-parse-entry t)
1635 collect (cons (downcase key) value)))
1636 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1637 (year (reftex-get-bib-field "year" entry))
1638 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1639 (key (reftex-get-bib-field "=key=" entry))
1640 (journal (reftex-get-bib-field "journal" entry))
1641 (volume (reftex-get-bib-field "volume" entry))
1642 (pages (reftex-get-bib-field "pages" entry))
1643 (doi (reftex-get-bib-field "doi" entry))
1644 (url (reftex-get-bib-field "url" entry))
1646 ;;authors, "title", Journal, vol(iss):pages (year).
1647 (format "%s, \"%s\", %s, %s:%s (%s)"
1648 author title journal volume pages year)))
1652 : org-ref-bib-citation
1655 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1656 (defun org-ref-bib-html-citation ()
1657 "from a bibtex entry, create and return a simple citation with html links."
1659 (bibtex-beginning-of-entry)
1660 (let* ((cb (current-buffer))
1661 (bibtex-expand-strings t)
1662 (entry (loop for (key . value) in (bibtex-parse-entry t)
1663 collect (cons (downcase key) value)))
1664 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1665 (year (reftex-get-bib-field "year" entry))
1666 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1667 (key (reftex-get-bib-field "=key=" entry))
1668 (journal (reftex-get-bib-field "journal" entry))
1669 (volume (reftex-get-bib-field "volume" entry))
1670 (pages (reftex-get-bib-field "pages" entry))
1671 (doi (reftex-get-bib-field "doi" entry))
1672 (url (reftex-get-bib-field "url" entry))
1674 ;;authors, "title", Journal, vol(iss):pages (year).
1675 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1676 author title journal volume pages year)
1677 (when url (format " <a href=\"%s\">link</a>" url))
1678 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1682 ** open pdf from bibtex
1683 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1684 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1685 (defun org-ref-open-bibtex-pdf ()
1686 "open pdf for a bibtex entry, if it exists. assumes point is in
1687 the entry of interest in the bibfile. but does not check that."
1690 (bibtex-beginning-of-entry)
1691 (let* ((bibtex-expand-strings t)
1692 (entry (bibtex-parse-entry t))
1693 (key (reftex-get-bib-field "=key=" entry))
1694 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1696 (if (file-exists-p pdf)
1697 (org-open-link-from-string (format "[[file:%s]]" pdf))
1701 ** open notes from bibtex
1702 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1704 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1705 (defun org-ref-open-bibtex-notes ()
1706 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1708 I never did figure out how to use reftex to make this happen
1709 non-interactively. the reftex-format-citation function did not
1710 work perfectly; there were carriage returns in the strings, and
1711 it did not put the key where it needed to be. so, below I replace
1712 the carriage returns and extra spaces with a single space and
1713 construct the heading by hand."
1716 (bibtex-beginning-of-entry)
1717 (let* ((cb (current-buffer))
1718 (bibtex-expand-strings t)
1719 (entry (loop for (key . value) in (bibtex-parse-entry t)
1720 collect (cons (downcase key) value)))
1721 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1722 (year (reftex-get-bib-field "year" entry))
1723 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1724 (key (reftex-get-bib-field "=key=" entry))
1725 (journal (reftex-get-bib-field "journal" entry))
1726 (volume (reftex-get-bib-field "volume" entry))
1727 (pages (reftex-get-bib-field "pages" entry))
1728 (doi (reftex-get-bib-field "doi" entry))
1729 (url (reftex-get-bib-field "url" entry))
1732 ;; save key to clipboard to make saving pdf later easier by pasting.
1735 (kill-ring-save (point-min) (point-max)))
1737 ;; now look for entry in the notes file
1738 (if org-ref-bibliography-notes
1739 (find-file-other-window org-ref-bibliography-notes)
1740 (error "org-ref-bib-bibliography-notes is not set to anything"))
1742 (goto-char (point-min))
1743 ;; put new entry in notes if we don't find it.
1744 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1745 (funcall org-ref-open-notes-function)
1746 ;; no entry found, so add one
1747 (insert (format "\n** TODO %s - %s" year title))
1759 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1760 key author journal year volume pages doi url key org-ref-pdf-directory key))
1764 ** open url in browser from bibtex
1766 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1768 + 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.
1770 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1771 (defun org-ref-open-in-browser ()
1772 "Open the bibtex entry at point in a browser using the url field or doi field"
1775 (bibtex-beginning-of-entry)
1777 (let ((url (bibtex-autokey-get-field "url")))
1782 (let ((doi (bibtex-autokey-get-field "doi")))
1784 (if (string-match "^http" doi)
1786 (browse-url (format "http://dx.doi.org/%s" doi)))
1788 (message "No url or doi found"))))
1792 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.
1794 *** function to upload bibtex to citeulike
1796 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1797 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1798 "with point in a bibtex entry get bibtex string and submit to citeulike.
1800 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1802 (message "uploading to citeulike")
1804 (bibtex-narrow-to-entry)
1805 (let ((startpos (point-min))
1806 (endpos (point-max))
1807 (bibtex-string (buffer-string))
1808 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1809 (with-temp-buffer (insert bibtex-string)
1810 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1813 *** The upload script
1814 Here is the python script for uploading.
1816 *************** TODO document how to get the cookies
1820 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1822 import pickle, requests, sys
1825 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1826 cookies = pickle.load(f)
1828 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1830 bibtex = sys.stdin.read()
1832 data = {'pasted':bibtex,
1834 'tag_parsing':'simple',
1835 'strip_brackets':'no',
1836 'update_id':'bib-key',
1837 'btn_bibtex':'Import BibTeX file ...'}
1839 headers = {'content-type': 'multipart/form-data',
1840 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1842 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1846 ** Build a pdf from a bibtex file
1847 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.
1849 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1850 (defun org-ref-build-full-bibliography ()
1851 "build pdf of all bibtex entries, and open it."
1853 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1854 (bib-base (file-name-sans-extension bibfile))
1855 (texfile (concat bib-base ".tex"))
1856 (pdffile (concat bib-base ".pdf")))
1859 (insert (format "\\documentclass[12pt]{article}
1860 \\usepackage[version=3]{mhchem}
1862 \\usepackage[numbers]{natbib}
1863 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1867 \\bibliographystyle{unsrtnat}
1869 \\end{document}" bib-base))
1871 (shell-command (concat "pdflatex " bib-base))
1872 (shell-command (concat "bibtex " bib-base))
1873 (shell-command (concat "pdflatex " bib-base))
1874 (shell-command (concat "pdflatex " bib-base))
1875 (kill-buffer texfile)
1876 (org-open-file pdffile)
1880 ** Extract bibtex entries cited in an org-file
1881 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.
1883 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1884 (defun org-ref-extract-bibtex-entries ()
1885 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1887 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1889 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1890 (tempname (make-temp-file "extract-bib"))
1891 (contents (buffer-string))
1892 (cb (current-buffer))
1893 basename texfile bibfile results)
1895 ;; open tempfile and insert org-buffer contents
1896 (find-file tempname)
1898 (setq basename (file-name-sans-extension
1899 (file-name-nondirectory buffer-file-name))
1900 texfile (concat tempname ".tex")
1901 bibfile (concat tempname ".bib"))
1903 ;; see if we have a bibliography, and insert the default one if not.
1905 (goto-char (point-min))
1906 (unless (re-search-forward "^bibliography:" (point-max) 'end)
1907 (insert (format "\nbibliography:%s"
1908 (mapconcat 'identity reftex-default-bibliography ",")))))
1911 ;; get a latex file and extract the references
1912 (org-latex-export-to-latex)
1915 (reftex-create-bibtex-file bibfile)
1917 ;; save results of the references
1918 (setq results (buffer-string))
1920 ;; kill buffers. these are named by basename, not full path
1921 (kill-buffer (concat basename ".bib"))
1922 (kill-buffer (concat basename ".tex"))
1923 (kill-buffer basename)
1925 (delete-file bibfile)
1926 (delete-file texfile)
1927 (delete-file tempname)
1929 ;; Now back to the original org buffer and insert the results
1930 (switch-to-buffer cb)
1931 (when (not (string= "" results))
1933 (goto-char (point-max))
1935 (org-insert-heading)
1936 (insert (format " Bibtex entries
1938 ,#+BEGIN_SRC text :tangle %s
1940 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
1943 ** Find bad cite links
1944 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.
1946 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1949 (defun index (substring list)
1950 "return the index of string in a list of strings"
1953 (dolist (arg list i)
1954 (if (string-match (concat "^" substring "$") arg)
1959 ;; return counter if found, otherwise return nil
1963 (defun org-ref-find-bad-citations ()
1964 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
1966 Makes a new buffer with clickable links."
1968 ;; generate the list of bibtex-keys and cited keys
1969 (let* ((bibtex-files (org-ref-find-bibliography))
1970 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
1971 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
1972 (bad-citations '()))
1974 (org-element-map (org-element-parse-buffer) 'link
1976 (let ((plist (nth 1 link)))
1977 (when (equal (plist-get plist ':type) "cite")
1978 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
1979 (when (not (index key bibtex-keys))
1980 (setq bad-citations (append bad-citations
1981 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
1982 key (buffer-name)(plist-get plist ':begin)))))
1987 (switch-to-buffer-other-window "*Missing citations*")
1990 (insert "* List of bad cite links\n")
1991 (insert (mapconcat 'identity bad-citations ""))
1992 ;(setq buffer-read-only t)
1993 (use-local-map (copy-keymap org-mode-map))
1994 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
1996 (when (get-buffer "*Missing citations*")
1997 (kill-buffer "*Missing citations*"))
1998 (message "No bad cite links found"))))
2001 ** Finding non-ascii characters
2002 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2004 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2005 (defun org-ref-find-non-ascii-characters ()
2006 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2008 (occur "[^[:ascii:]]"))
2011 ** Resort a bibtex entry
2012 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.
2014 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2015 (defun org-ref-sort-bibtex-entry ()
2016 "sort fields of entry in standard order and downcase them"
2018 (bibtex-beginning-of-entry)
2019 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2020 (entry (bibtex-parse-entry))
2023 (type (cdr (assoc "=type=" entry)))
2024 (key (cdr (assoc "=key=" entry))))
2026 ;; these are the fields we want to order that are in this entry
2027 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2028 ;; we do not want to reenter these fields
2029 (setq entry-fields (remove "=key=" entry-fields))
2030 (setq entry-fields (remove "=type=" entry-fields))
2032 ;;these are the other fields in the entry
2033 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2036 ;; right now we only resort articles
2037 ((string= (downcase type) "article")
2040 (concat "@article{" key ",\n"
2043 (when (member field entry-fields)
2044 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2047 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2049 (bibtex-find-entry key)
2051 (bibtex-clean-entry)
2055 ** Clean a bibtex entry
2056 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.
2057 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.
2058 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2059 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2060 "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"
2062 (bibtex-beginning-of-entry)
2064 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2065 (unless (string-match ",$" (thing-at-point 'line))
2069 ;; check for empty pages, and put eid or article id in its place
2070 (let ((entry (bibtex-parse-entry))
2071 (pages (bibtex-autokey-get-field "pages"))
2072 (year (bibtex-autokey-get-field "year"))
2073 (doi (bibtex-autokey-get-field "doi"))
2074 ;; The Journal of Chemical Physics uses eid
2075 (eid (bibtex-autokey-get-field "eid")))
2077 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2078 ;; but we only want the doi.
2079 (when (string-match "^http://dx.doi.org/" doi)
2080 (bibtex-beginning-of-entry)
2081 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2083 (bibtex-make-field "doi")
2085 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2087 ;; asap articles often set year to 0, which messes up key
2088 ;; generation. fix that.
2089 (when (string= "0" year)
2090 (bibtex-beginning-of-entry)
2091 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2093 (bibtex-make-field "year")
2095 (insert (read-string "Enter year: ")))
2097 ;; fix pages if they are empty if there is an eid to put there.
2098 (when (string= "-" pages)
2100 (bibtex-beginning-of-entry)
2101 ;; this seems like a clunky way to set the pages field.But I
2102 ;; cannot find a better way.
2103 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2105 (bibtex-make-field "pages")
2109 ;; replace naked & with \&
2111 (bibtex-narrow-to-entry)
2112 (bibtex-beginning-of-entry)
2113 (message "checking &")
2114 (replace-regexp " & " " \\\\& ")
2117 ;; generate a key, and if it duplicates an existing key, edit it.
2119 (let ((key (bibtex-generate-autokey)))
2121 ;; first we delete the existing key
2122 (bibtex-beginning-of-entry)
2123 (re-search-forward bibtex-entry-maybe-empty-head)
2124 (if (match-beginning bibtex-key-in-head)
2125 (delete-region (match-beginning bibtex-key-in-head)
2126 (match-end bibtex-key-in-head)))
2127 ;; check if the key is in the buffer
2128 (when (save-excursion
2129 (bibtex-search-entry key))
2131 (bibtex-search-entry key)
2132 (bibtex-copy-entry-as-kill)
2133 (switch-to-buffer-other-window "*duplicate entry*")
2135 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2138 (kill-new key))) ;; save key for pasting
2140 ;; run hooks. each of these operates on the entry with no arguments.
2141 ;; this did not work like i thought, it gives a symbolp error.
2142 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2147 org-ref-clean-bibtex-entry-hook)
2149 ;; sort fields within entry
2150 (org-ref-sort-bibtex-entry)
2151 ;; check for non-ascii characters
2152 (occur "[^[:ascii:]]")
2157 : org-ref-clean-bibtex-entry
2159 ** Sort the entries in a citation link by year
2160 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2162 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2163 (defun org-ref-get-citation-year (key)
2164 "get the year of an entry with key. Returns year as a string."
2166 (let* ((results (org-ref-get-bibtex-key-and-file key))
2167 (bibfile (cdr results)))
2169 (insert-file-contents bibfile)
2170 (bibtex-search-entry key nil 0)
2171 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2174 (defun org-ref-sort-citation-link ()
2175 "replace link at point with sorted link by year"
2177 (let* ((object (org-element-context))
2178 (type (org-element-property :type object))
2179 (begin (org-element-property :begin object))
2180 (end (org-element-property :end object))
2181 (link-string (org-element-property :path object))
2183 (setq keys (org-ref-split-and-strip-string link-string))
2184 (setq years (mapcar 'org-ref-get-citation-year keys))
2185 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2186 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2187 ;; now get the keys separated by commas
2188 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2189 ;; and replace the link with the sorted keys
2190 (cl--set-buffer-substring begin end (concat type ":" keys))))
2193 ** Sort entries in citation links with shift-arrow keys
2194 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2195 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2196 (defun org-ref-swap-keys (i j keys)
2197 "swap the keys in a list with index i and j"
2198 (let ((tempi (nth i keys)))
2199 (setf (nth i keys) (nth j keys))
2200 (setf (nth j keys) tempi))
2203 (defun org-ref-swap-citation-link (direction)
2204 "move citation at point in direction +1 is to the right, -1 to the left"
2206 (let* ((object (org-element-context))
2207 (type (org-element-property :type object))
2208 (begin (org-element-property :begin object))
2209 (end (org-element-property :end object))
2210 (link-string (org-element-property :path object))
2212 ;; We only want this to work on citation links
2213 (when (-contains? org-ref-cite-types type)
2214 (setq key (org-ref-get-bibtex-key-under-cursor))
2215 (setq keys (org-ref-split-and-strip-string link-string))
2216 (setq i (index key keys)) ;; defined in org-ref
2217 (if (> direction 0) ;; shift right
2218 (org-ref-swap-keys i (+ i 1) keys)
2219 (org-ref-swap-keys i (- i 1) keys))
2220 (setq keys (mapconcat 'identity keys ","))
2221 ;; and replace the link with the sorted keys
2222 (cl--set-buffer-substring begin end (concat type ":" keys))
2223 ;; now go forward to key so we can move with the key
2224 (re-search-forward key)
2225 (goto-char (match-beginning 0)))))
2227 ;; add hooks to make it work
2228 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2229 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2232 I like convenience. Here are some aliases for faster typing.
2234 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2235 (defalias 'oro 'org-ref-open-citation-at-point)
2236 (defalias 'orc 'org-ref-citation-at-point)
2237 (defalias 'orp 'org-ref-open-pdf-at-point)
2238 (defalias 'oru 'org-ref-open-url-at-point)
2239 (defalias 'orn 'org-ref-open-notes-at-point)
2241 (defalias 'orib 'org-ref-insert-bibliography-link)
2242 (defalias 'oric 'org-ref-insert-cite-link)
2243 (defalias 'orir 'org-ref-insert-ref-link)
2244 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2246 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2249 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2256 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2258 [[elisp:(org-babel-load-file "org-ref.org")]]