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"
154 ;; for the bibentry package
157 "List of citation types known in org-ref"
158 :type '(repeat :tag "List of citation types" string)
162 We need a hook variable to store user-defined bibtex entry cleaning functions
163 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
164 (defcustom org-ref-clean-bibtex-entry-hook nil
165 "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
171 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
172 (defvar org-ref-bibliography-files
174 "variable to hold bibliography files to be searched")
177 ** org-mode / reftex setup
179 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.
181 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
182 (defun org-mode-reftex-setup ()
183 (load-library "reftex")
184 (and (buffer-file-name)
185 (file-exists-p (buffer-file-name))
186 (global-auto-revert-mode t)
188 (make-local-variable 'reftex-cite-format)
189 (setq reftex-cite-format 'org)
190 (define-key org-mode-map (kbd org-ref-insert-cite-key) 'org-ref-insert-cite-link))
192 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
194 (eval-after-load 'reftex-vars
196 (add-to-list 'reftex-cite-format-builtin
197 '(org "Org-mode citation"
198 ((?\C-m . "cite:%l") ; default
199 (?d . ",%l") ; for appending
205 (?h . "citeauthor:%l")
206 (?H . "citeauthor*:%l")
213 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.
215 #+BEGIN_SRC emacs-lisp :tangle no
217 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
218 (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l")
219 (?z . "newcite:%l"))))
222 You can define a new citation link like this:
223 #+BEGIN_SRC emacs-lisp :tangle no
224 (org-ref-define-citation-link "citez" ?z)
228 Most of this library is the creation of functional links to help with references and citations.
230 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.
232 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
233 (defun org-ref-strip-string (string)
234 "strip leading and trailing whitespace from the string"
235 (replace-regexp-in-string
236 (concat search-whitespace-regexp "$" ) ""
237 (replace-regexp-in-string
238 (concat "^" search-whitespace-regexp ) "" string)))
241 It is helpful to make the previous function operate on a list of strings here.
243 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
244 (defun org-ref-split-and-strip-string (string)
245 "split key-string and strip keys. Assumes the key-string is comma delimited"
246 (mapcar 'org-ref-strip-string (split-string string ",")))
249 ** bibliography and bibliographystyle
250 *** An html bibliography
252 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.
254 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
255 (defun org-ref-reftex-get-bib-field (field entry &optional format)
256 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
258 (setq result (reftex-get-bib-field field entry format))
259 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
260 (setq result (substring result 1 -1)))
261 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
262 (setq result (substring result 1 -1)))
265 (defun org-ref-reftex-format-citation (entry format)
266 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
267 to the format argument. The format is a string with these percent escapes.
269 In the format, the following percent escapes will be expanded.
271 %l The BibTeX label of the citation.
272 %a List of author names, see also `reftex-cite-punctuation'.
273 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
274 %A First author name only.
275 %e Works like %a, but on list of editor names. (%2e and %E work a well)
277 It is also possible to access all other BibTeX database fields:
278 %b booktitle %c chapter %d edition %h howpublished
279 %i institution %j journal %k key %m month
280 %n number %o organization %p pages %P first page
281 %r address %s school %u publisher %t title
283 %B booktitle, abbreviated %T title, abbreviated
288 Usually, only %l is needed. The other stuff is mainly for the echo area
289 display, and for (setq reftex-comment-citations t).
291 %< as a special operator kills punctuation and space around it after the
292 string has been formatted.
294 A pair of square brackets indicates an optional argument, and RefTeX
295 will prompt for the values of these arguments.
297 Beware that all this only works with BibTeX database files. When
298 citations are made from the \bibitems in an explicit thebibliography
299 environment, only %l is available."
300 ;; Format a citation from the info in the BibTeX ENTRY
302 (unless (stringp format) (setq format "\\cite{%l}"))
304 (if (and reftex-comment-citations
305 (string-match "%l" reftex-cite-comment-format))
306 (error "reftex-cite-comment-format contains invalid %%l"))
309 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
311 (let ((n (string-to-number (match-string 4 format)))
312 (l (string-to-char (match-string 5 format)))
318 (org-ref-reftex-get-bib-field "&key" entry)
319 (if reftex-comment-citations
320 reftex-cite-comment-format
322 ((= l ?a) (reftex-format-names
323 (reftex-get-bib-names "author" entry)
325 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
326 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
327 ((= l ?B) (reftex-abbreviate-title
328 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
329 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
330 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
331 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
332 ((= l ?e) (reftex-format-names
333 (reftex-get-bib-names "editor" entry)
335 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
336 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
337 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
338 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
339 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
340 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
341 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
342 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
343 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
344 ((= l ?P) (car (split-string
345 (org-ref-reftex-get-bib-field "pages" entry)
347 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
348 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
349 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
350 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
351 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
352 ;; strip enclosing brackets from title if they are there
353 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
354 ((= l ?T) (reftex-abbreviate-title
355 (org-ref-reftex-get-bib-field "title" entry)))
356 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
357 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
360 (setq b (match-beginning 2) e (match-end 2))
361 (setq b (match-beginning 3) e (match-end 3)))
362 (setq format (concat (substring format 0 b) rpl (substring format e)))))
363 (while (string-match "%%" format)
364 (setq format (replace-match "%" t t format)))
365 (while (string-match "[ ,.;:]*%<" format)
366 (setq format (replace-match "" t t format)))
367 ;; also replace carriage returns, tabs, and multiple whitespaces
368 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
371 (defun org-ref-get-bibtex-entry-citation (key)
372 "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
374 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
375 (file) (entry) (bibtex-entry) (entry-type) (format))
377 (setq file (catch 'result
378 (loop for file in org-ref-bibliography-files do
379 (if (org-ref-key-in-file-p key (file-truename file))
381 (message "%s not found in %s" key (file-truename file))))))
384 (insert-file-contents file)
385 (bibtex-search-entry key nil 0)
386 (setq bibtex-entry (bibtex-parse-entry))
387 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
388 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
390 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
392 (bibtex-narrow-to-entry)
393 (setq entry (buffer-string)))))
398 : org-ref-reftex-format-citation
400 Here is how to use the function. You call it with point in an entry in a bibtex file.
402 #+BEGIN_SRC emacs-lisp :tangle no
403 (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>."))
404 (org-ref-get-bibtex-entry-citation "armiento-2014-high"))
407 : 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>.
409 I am not sure why full author names are not used.
411 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
413 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
414 (defun org-ref-get-bibtex-keys ()
415 "return a list of unique keys in the buffer."
417 (org-element-map (org-element-parse-buffer) 'link
419 (let ((plist (nth 1 link)))
420 (when (-contains? org-ref-cite-types (plist-get plist ':type))
423 (org-ref-split-and-strip-string (plist-get plist ':path)))
424 (when (not (-contains? keys key))
425 (setq keys (append keys (list key)))))))))
426 ;; Sort keys alphabetically
427 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
431 This function gets the html for one entry.
433 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
434 (defun org-ref-get-bibtex-entry-html (key)
435 "returns an html string for the bibliography entry corresponding to key"
437 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
440 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
442 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
443 (defun org-ref-get-html-bibliography ()
444 "Create an html bibliography when there are keys"
445 (let ((keys (org-ref-get-bibtex-keys)))
447 (concat "<h1>Bibliography</h1>
449 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
453 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.
455 *** An org bibliography
456 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.
458 First, we get the string for a single entry.
459 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
460 (defun org-ref-get-bibtex-entry-org (key)
461 "returns an org string for the bibliography entry corresponding to key"
462 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
463 (file) (entry) (bibtex-entry) (entry-type) (format))
465 (setq file (catch 'result
466 (loop for file in org-ref-bibliography-files do
467 (if (org-ref-key-in-file-p key (file-truename file))
469 (message "%s not found in %s" key (file-truename file))))))
472 (insert-file-contents file)
473 (bibtex-search-entry key nil 0)
474 (setq entry (bibtex-parse-entry))
479 " (org-ref-reftex-get-bib-field "author" entry)
480 (org-ref-reftex-get-bib-field "title" entry)
481 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
482 (mapconcat (lambda (element) (format " :%s: %s"
483 (upcase (car element))
489 Now, we loop over the keys, and combine all the entries into a bibliography.
490 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
491 (defun org-ref-get-org-bibliography ()
492 "Create an org bibliography when there are keys"
493 (let ((keys (org-ref-get-bibtex-keys)))
495 (concat "* Bibliography
497 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
501 *** An ascii bibliography
503 This function gets the html for one entry.
505 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
506 (defun org-ref-get-bibtex-entry-ascii (key)
507 "returns an ascii string for the bibliography entry corresponding to key"
509 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
512 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
514 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
515 (defun org-ref-get-ascii-bibliography ()
516 "Create an html bibliography when there are keys"
517 (let ((keys (org-ref-get-bibtex-keys)))
523 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
529 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.
531 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
532 (org-add-link-type "bibliography"
533 ;; this code is run on clicking. The bibliography
534 ;; may contain multiple files. this code finds the
535 ;; one you clicked on and opens it.
536 (lambda (link-string)
537 ;; get link-string boundaries
538 ;; we have to go to the beginning of the line, and then search forward
541 ;; object is the link you clicked on
542 (object (org-element-context))
544 (link-string-beginning)
548 (goto-char (org-element-property :begin object))
549 (search-forward link-string nil nil 1)
550 (setq link-string-beginning (match-beginning 0))
551 (setq link-string-end (match-end 0)))
553 ;; We set the reftex-default-bibliography
554 ;; here. it should be a local variable only in
555 ;; the current buffer. We need this for using
556 ;; reftex to do citations.
557 (set (make-local-variable 'reftex-default-bibliography)
558 (split-string (org-element-property :path object) ","))
560 ;; now if we have comma separated bibliographies
561 ;; we find the one clicked on. we want to
562 ;; search forward to next comma from point
564 (if (search-forward "," link-string-end 1 1)
565 (setq key-end (- (match-end 0) 1)) ; we found a match
566 (setq key-end (point)))) ; no comma found so take the point
567 ;; and backward to previous comma from point
569 (if (search-backward "," link-string-beginning 1 1)
570 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
571 (setq key-beginning (point)))) ; no match found
572 ;; save the key we clicked on.
573 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
574 (find-file bibfile))) ; open file on click
577 (lambda (keyword desc format)
579 ((eq format 'org) (org-ref-get-org-bibliography))
580 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
581 ((eq format 'html) (org-ref-get-html-bibliography))
583 ;; write out the latex bibliography command
584 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
585 (mapcar 'expand-file-name
586 (split-string keyword ","))
591 Believe it or not, sometimes it makes sense /not/ to include the bibliography in a document (e.g. when you are required to submit references as a separate file). To generate the references, in another file, you must make a little tex file with these contents, and then compile it.
594 \input{project-description.bbl}
597 Here, we make a =nobibliography= link that acts like the bibliography, enables creation of the bbl file, but does not put an actual bibliography in the file.
599 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
600 (org-add-link-type "nobibliography"
601 ;; this code is run on clicking. The bibliography
602 ;; may contain multiple files. this code finds the
603 ;; one you clicked on and opens it.
604 (lambda (link-string)
605 ;; get link-string boundaries
606 ;; we have to go to the beginning of the line, and then search forward
609 ;; object is the link you clicked on
610 (object (org-element-context))
612 (link-string-beginning)
616 (goto-char (org-element-property :begin object))
617 (search-forward link-string nil nil 1)
618 (setq link-string-beginning (match-beginning 0))
619 (setq link-string-end (match-end 0)))
621 ;; We set the reftex-default-bibliography
622 ;; here. it should be a local variable only in
623 ;; the current buffer. We need this for using
624 ;; reftex to do citations.
625 (set (make-local-variable 'reftex-default-bibliography)
626 (split-string (org-element-property :path object) ","))
628 ;; now if we have comma separated bibliographies
629 ;; we find the one clicked on. we want to
630 ;; search forward to next comma from point
632 (if (search-forward "," link-string-end 1 1)
633 (setq key-end (- (match-end 0) 1)) ; we found a match
634 (setq key-end (point)))) ; no comma found so take the point
635 ;; and backward to previous comma from point
637 (if (search-backward "," link-string-beginning 1 1)
638 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
639 (setq key-beginning (point)))) ; no match found
640 ;; save the key we clicked on.
641 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
642 (find-file bibfile))) ; open file on click
645 (lambda (keyword desc format)
647 ((eq format 'org) (org-ref-get-org-bibliography))
648 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
649 ((eq format 'html) (org-ref-get-html-bibliography))
651 ;; write out the latex bibliography command
653 ; (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
654 ; (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
655 ; (mapcar 'expand-file-name
656 ; (split-string keyword ","))
659 (format "\\nobibliography{%s}"
660 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
661 (mapcar 'expand-file-name
662 (split-string keyword ","))
668 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
669 (org-add-link-type "printbibliography"
670 (lambda (arg) (message "Nothing implemented for clicking here."))
671 (lambda (keyword desc format)
673 ((eq format 'org) (org-ref-get-org-bibliography))
674 ((eq format 'html) (org-ref-get-html-bibliography))
676 ;; write out the biblatex bibliography command
677 "\\printbibliography"))
681 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, ...
683 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
684 (org-add-link-type "bibliographystyle"
685 (lambda (arg) (message "Nothing implemented for clicking here."))
686 (lambda (keyword desc format)
689 ;; write out the latex bibliography command
690 (format "\\bibliographystyle{%s}" keyword)))))
693 *** Completion for bibliography link
696 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
697 (defun org-bibliography-complete-link (&optional arg)
698 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
700 (defun org-ref-insert-bibliography-link ()
701 "insert a bibliography with completion"
703 (insert (org-bibliography-complete-link)))
707 This is apparently used for biblatex.
708 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
709 (org-add-link-type "addbibresource"
710 ;; this code is run on clicking. The addbibresource
711 ;; may contain multiple files. this code finds the
712 ;; one you clicked on and opens it.
713 (lambda (link-string)
714 ;; get link-string boundaries
715 ;; we have to go to the beginning of the line, and then search forward
718 ;; object is the link you clicked on
719 (object (org-element-context))
721 (link-string-beginning)
725 (goto-char (org-element-property :begin object))
726 (search-forward link-string nil nil 1)
727 (setq link-string-beginning (match-beginning 0))
728 (setq link-string-end (match-end 0)))
730 ;; We set the reftex-default-addbibresource
731 ;; here. it should be a local variable only in
732 ;; the current buffer. We need this for using
733 ;; reftex to do citations.
734 (set (make-local-variable 'reftex-default-addbibresource)
735 (split-string (org-element-property :path object) ","))
737 ;; now if we have comma separated bibliographies
738 ;; we find the one clicked on. we want to
739 ;; search forward to next comma from point
741 (if (search-forward "," link-string-end 1 1)
742 (setq key-end (- (match-end 0) 1)) ; we found a match
743 (setq key-end (point)))) ; no comma found so take the point
744 ;; and backward to previous comma from point
746 (if (search-backward "," link-string-beginning 1 1)
747 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
748 (setq key-beginning (point)))) ; no match found
749 ;; save the key we clicked on.
750 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
751 (find-file bibfile))) ; open file on click
754 (lambda (keyword desc format)
756 ((eq format 'html) (format "")); no output for html
758 ;; write out the latex addbibresource command
759 (format "\\addbibresource{%s}" keyword)))))
764 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.
766 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
767 (defun org-ref-list-of-figures (&optional arg)
768 "Generate buffer with list of figures in them"
770 (save-excursion (widen)
771 (let* ((c-b (buffer-name))
774 (org-element-map (org-element-parse-buffer) 'link
776 "create a link for to the figure"
778 (and (string= (org-element-property :type link) "file")
780 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
781 (org-element-property :path link)))
784 (let* ((start (org-element-property :begin link))
785 (parent (car (cdr (org-element-property :parent link))))
786 (caption (caaar (plist-get parent :caption)))
787 (name (plist-get parent :name)))
790 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
791 c-b start counter (or name "") caption)
793 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
794 c-b start counter (or name "")))))))))
795 (switch-to-buffer "*List of Figures*")
796 (setq buffer-read-only nil)
799 (insert (mapconcat 'identity list-of-figures ""))
800 (setq buffer-read-only t)
801 (use-local-map (copy-keymap org-mode-map))
802 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
806 'org-ref-list-of-figures ; on click
807 (lambda (keyword desc format)
810 (format "\\listoffigures")))))
815 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
816 (defun org-ref-list-of-tables (&optional arg)
817 "Generate a buffer with a list of tables"
821 (let* ((c-b (buffer-name))
824 (org-element-map (org-element-parse-buffer 'element) 'table
826 "create a link for to the table"
828 (let ((start (org-element-property :begin table))
829 (name (org-element-property :name table))
830 (caption (caaar (org-element-property :caption table))))
833 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
834 c-b start counter (or name "") caption)
836 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
837 c-b start counter (or name ""))))))))
838 (switch-to-buffer "*List of Tables*")
839 (setq buffer-read-only nil)
842 (insert (mapconcat 'identity list-of-tables ""))
843 (setq buffer-read-only t)
844 (use-local-map (copy-keymap org-mode-map))
845 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
849 'org-ref-list-of-tables
850 (lambda (keyword desc format)
853 (format "\\listoftables")))))
857 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.
858 *************** TODO search tblnames, custom_ids and check for case sensitivity
861 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
865 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
866 (message (format "%s occurences"
867 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
868 ;; for tblname, it is not enough to get word boundary
869 ;; tab-little and tab-little-2 match then.
870 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
871 (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
872 ;; this is the org-format #+label:
873 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))))
874 (lambda (keyword desc format)
876 ((eq format 'html) (format "(<label>%s</label>)" path))
878 (format "\\label{%s}" keyword)))))
881 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.
883 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
884 (defun org-label-store-link ()
885 "store a link to a label. The output will be a ref to that label"
886 ;; First we have to make sure we are on a label link.
887 (let* ((object (org-element-context)))
888 (when (and (equal (org-element-type object) 'link)
889 (equal (org-element-property :type object) "label"))
890 (org-store-link-props
892 :link (concat "ref:" (org-element-property :path object))))
894 ;; Store link on table
895 (when (equal (org-element-type object) 'table)
896 (org-store-link-props
898 :link (concat "ref:" (org-element-property :name object))))
900 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
901 ;; store link on heading with custom_id
902 ; (when (and (equal (org-element-type object) 'headline)
903 ; (org-entry-get (point) "CUSTOM_ID"))
904 ; (org-store-link-props
906 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
908 ;; and to #+label: lines
909 (when (and (equal (org-element-type object) 'paragraph)
910 (org-element-property :name object))
911 (org-store-link-props
913 :link (concat "ref:" (org-element-property :name object))))
916 (add-hook 'org-store-link-functions 'org-label-store-link)
920 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.
922 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
924 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
928 "on clicking goto the label. Navigate back with C-c &"
930 ;; next search from beginning of the buffer
932 ;; it is possible you would not find the label if narrowing is in effect
939 (goto-char (point-min))
940 (re-search-forward (format "label:%s\\b" label) nil t))
944 (goto-char (point-min))
945 (re-search-forward (format "\\label{%s}" label) nil t))
947 ;; #+label: name org-definition
949 (goto-char (point-min))
950 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
954 (goto-char (point-min))
955 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
957 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
958 ;; you need [[#label]] links.
961 ; (goto-char (point-min))
962 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
964 ;; we did not find anything, so go back to where we came
966 (error "%s not found" label))
968 (message "go back with (org-mark-ring-goto) `C-c &`"))
970 (lambda (keyword desc format)
972 ((eq format 'html) (format "(<ref>%s</ref>)" path))
974 (format "\\ref{%s}" keyword)))))
977 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.
979 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
980 (defun org-ref-get-custom-ids ()
981 "return a list of custom_id properties in the buffer"
982 (let ((results '()) custom_id)
985 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
986 (when (not (null custom_id))
987 (setq results (append results (list custom_id)))))))
991 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
992 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
993 (defun org-ref-get-latex-labels ()
995 (goto-char (point-min))
997 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
998 (add-to-list 'matches (match-string-no-properties 1) t))
1002 Finally, we get the table names.
1004 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1005 (defun org-ref-get-tblnames ()
1006 (org-element-map (org-element-parse-buffer 'element) 'table
1008 (org-element-property :name table))))
1011 Now, we can put all the labels together which will give us a list of candidates.
1013 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1014 (defun org-ref-get-labels ()
1015 "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
1019 (goto-char (point-min))
1020 (let ((matches '()))
1021 (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1022 (add-to-list 'matches (match-string-no-properties 1) t))
1023 (append matches (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
1026 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.
1028 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1029 (defun org-ref-complete-link (&optional arg)
1030 "Completion function for ref links"
1032 (setq label (completing-read "label: " (org-ref-get-labels)))
1033 (format "ref:%s" label)))
1036 Alternatively, you may want to just call a function that inserts a link with completion:
1038 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1039 (defun org-ref-insert-ref-link ()
1041 (insert (org-ref-complete-link)))
1046 This refers to the page of a label in LaTeX.
1048 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1052 "on clicking goto the label. Navigate back with C-c &"
1053 (org-mark-ring-push)
1054 ;; next search from beginning of the buffer
1060 (goto-char (point-min))
1061 (re-search-forward (format "label:%s\\b" label) nil t))
1065 (goto-char (point-min))
1066 (re-search-forward (format "\\label{%s}" label) nil t))
1068 ;; #+label: name org-definition
1070 (goto-char (point-min))
1071 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1075 (goto-char (point-min))
1076 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1078 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1079 ;; you need [[#label]] links.
1082 ; (goto-char (point-min))
1083 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1085 ;; we did not find anything, so go back to where we came
1086 (org-mark-ring-goto)
1087 (error "%s not found" label))
1088 (message "go back with (org-mark-ring-goto) `C-c &`"))
1090 (lambda (keyword desc format)
1092 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1094 (format "\\pageref{%s}" keyword)))))
1097 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1098 (defun org-pageref-complete-link (&optional arg)
1099 "Completion function for ref links"
1101 (setq label (completing-read "label: " (org-ref-get-labels)))
1102 (format "ref:%s" label)))
1105 Alternatively, you may want to just call a function that inserts a link with completion:
1107 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1108 (defun org-pageref-insert-ref-link ()
1110 (insert (org-pageref-complete-link)))
1115 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.
1117 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1121 "on clicking goto the label. Navigate back with C-c &"
1122 (org-mark-ring-push)
1123 ;; next search from beginning of the buffer
1129 (goto-char (point-min))
1130 (re-search-forward (format "\\label{%s}" label) nil t))
1132 ;; we did not find anything, so go back to where we came
1133 (org-mark-ring-goto)
1134 (error "%s not found" label))
1135 (message "go back with (org-mark-ring-goto) `C-c &`"))
1137 (lambda (keyword desc format)
1139 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1141 (format "\\nameref{%s}" keyword)))))
1145 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1147 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1151 "on clicking goto the label. Navigate back with C-c &"
1152 (org-mark-ring-push)
1153 ;; next search from beginning of the buffer
1155 (goto-char (point-min))
1158 ;; search forward for the first match
1160 (re-search-forward (format "label:%s" label) nil t)
1162 (re-search-forward (format "\\label{%s}" label) nil t)
1163 ;; #+label: name org-definition
1164 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1165 (org-mark-ring-goto)
1166 (error "%s not found" label))
1167 (message "go back with (org-mark-ring-goto) `C-c &`"))
1169 (lambda (keyword desc format)
1171 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1173 (format "\\eqref{%s}" keyword)))))
1178 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.
1180 *** Implementing the click actions of cite
1182 **** Getting the key we clicked on
1183 The first thing we need is to get the bibtex key we clicked on.
1185 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1186 (defun org-ref-get-bibtex-key-under-cursor ()
1187 "returns key under the bibtex cursor. We search forward from
1188 point to get a comma, or the end of the link, and then backwards
1189 to get a comma, or the beginning of the link. that delimits the
1190 keyword we clicked on. We also strip the text properties."
1192 (let* ((object (org-element-context))
1193 (link-string (org-element-property :path object)))
1194 ;; you may click on the part before the citations. here we make
1195 ;; sure to move to the beginning so you get the first citation.
1197 (goto-char (org-element-property :begin object))
1198 (search-forward link-string (org-element-property :end object))
1199 (goto-char (match-beginning 0))
1200 ;; check if we clicked before the path and move as needed.
1201 (unless (< cp (point))
1204 (if (not (org-element-property :contents-begin object))
1205 ;; this means no description in the link
1207 ;; we need the link path start and end
1209 (goto-char (org-element-property :begin object))
1210 (search-forward link-string nil nil 1)
1211 (setq link-string-beginning (match-beginning 0))
1212 (setq link-string-end (match-end 0)))
1214 ;; The key is the text between commas, or the link boundaries
1216 (if (search-forward "," link-string-end t 1)
1217 (setq key-end (- (match-end 0) 1)) ; we found a match
1218 (setq key-end link-string-end))) ; no comma found so take the end
1219 ;; and backward to previous comma from point which defines the start character
1221 (if (search-backward "," link-string-beginning 1 1)
1222 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1223 (setq key-beginning link-string-beginning))) ; no match found
1224 ;; save the key we clicked on.
1225 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1226 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1228 ;; link with description. assume only one key
1232 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.
1234 **** Getting the bibliographies
1235 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1236 (defun org-ref-find-bibliography ()
1237 "find the bibliography in the buffer.
1238 This function sets and returns cite-bibliography-files, which is a list of files
1239 either from bibliography:f1.bib,f2.bib
1240 \bibliography{f1,f2}
1241 internal bibliographies
1243 falling back to what the user has set in org-ref-default-bibliography
1248 (goto-char (point-min))
1249 ;; look for a bibliography link
1250 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1251 (setq org-ref-bibliography-files
1252 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1253 (throw 'result org-ref-bibliography-files))
1256 ;; we did not find a bibliography link. now look for \bibliography
1257 (goto-char (point-min))
1258 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1259 ;; split, and add .bib to each file
1260 (setq org-ref-bibliography-files
1261 (mapcar (lambda (x) (concat x ".bib"))
1262 (mapcar 'org-ref-strip-string
1263 (split-string (match-string 1) ","))))
1264 (throw 'result org-ref-bibliography-files))
1266 ;; no bibliography found. maybe we need a biblatex addbibresource
1267 (goto-char (point-min))
1268 ;; look for a bibliography link
1269 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1270 (setq org-ref-bibliography-files
1271 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1272 (throw 'result org-ref-bibliography-files))
1274 ;; we did not find anything. use defaults
1275 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1277 ;; set reftex-default-bibliography so we can search
1278 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1279 org-ref-bibliography-files)
1282 **** Finding the bibliography file a key is in
1283 Now, we can see if an entry is in a file.
1285 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1286 (defun org-ref-key-in-file-p (key filename)
1287 "determine if the key is in the file"
1288 (interactive "skey: \nsFile: ")
1289 (save-current-buffer
1290 (let ((bibtex-files (list filename)))
1291 (bibtex-search-entry key t))))
1294 Finally, we want to know which file the key is in.
1296 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1297 (defun org-ref-get-bibtex-key-and-file (&optional key)
1298 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1300 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1303 (setq key (org-ref-get-bibtex-key-under-cursor)))
1304 (setq file (catch 'result
1305 (loop for file in org-ref-bibliography-files do
1306 (if (org-ref-key-in-file-p key (file-truename file))
1307 (throw 'result file)))))
1311 **** Creating the menu for when we click on a key
1313 :ID: d7b7530b-802f-42b1-b61e-1e77da33e278
1315 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.
1317 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1318 (defun org-ref-get-menu-options ()
1319 "returns a dynamically determined string of options for the citation under point.
1321 we check to see if there is pdf, and if the key actually exists in the bibliography"
1323 (let* ((results (org-ref-get-bibtex-key-and-file))
1325 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1326 (bibfile (cdr results))
1327 m1 m2 m3 m4 m5 menu-string)
1328 (setq m1 (if bibfile
1332 (setq m3 (if (file-exists-p pdf-file)
1338 (string= (catch 'url
1342 (insert-file-contents bibfile)
1343 (bibtex-search-entry key)
1345 (string= (setq url (bibtex-autokey-get-field "url")) ""))
1349 (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1350 (throw 'url url))))) "")))
1351 "(u)rl" "(no url found)"))
1353 (setq m2 (if bibfile
1355 (setq citation (progn
1357 (insert-file-contents bibfile)
1358 (bibtex-search-entry key)
1359 (org-ref-bib-citation))))
1363 (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") " "))
1367 **** convenience functions to act on citation at point
1369 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1371 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.
1373 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1374 (defun org-ref-open-pdf-at-point ()
1375 "open the pdf for bibtex key under point if it exists"
1377 (let* ((results (org-ref-get-bibtex-key-and-file))
1379 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1380 (if (file-exists-p pdf-file)
1381 (org-open-file pdf-file)
1382 (message "no pdf found for %s" key))))
1385 (defun org-ref-open-url-at-point ()
1386 "open the url for bibtex key under point."
1388 (let* ((results (org-ref-get-bibtex-key-and-file))
1390 (bibfile (cdr results)))
1393 (insert-file-contents bibfile)
1394 (bibtex-search-entry key)
1395 ;; I like this better than bibtex-url which does not always find
1398 (let ((url (bibtex-autokey-get-field "url")))
1403 (let ((doi (bibtex-autokey-get-field "doi")))
1405 (if (string-match "^http" doi)
1407 (browse-url (format "http://dx.doi.org/%s" doi)))
1408 (throw 'done nil))))))))
1410 (defun org-ref-open-notes-at-point ()
1411 "open the notes for bibtex key under point."
1413 (let* ((results (org-ref-get-bibtex-key-and-file))
1415 (bibfile (cdr results)))
1418 (insert-file-contents bibfile)
1419 (bibtex-search-entry key)
1420 (org-ref-open-bibtex-notes)))))
1422 (defun org-ref-citation-at-point ()
1423 "give message of current citation at point"
1425 (let* ((cb (current-buffer))
1426 (results (org-ref-get-bibtex-key-and-file))
1428 (bibfile (cdr results)))
1429 (message "%s" (progn
1431 (insert-file-contents bibfile)
1432 (bibtex-search-entry key)
1433 (org-ref-bib-citation))))))
1435 (defun org-ref-open-citation-at-point ()
1436 "open bibtex file to key at point"
1438 (let* ((cb (current-buffer))
1439 (results (org-ref-get-bibtex-key-and-file))
1441 (bibfile (cdr results)))
1443 (bibtex-search-entry key)))
1446 **** the actual minibuffer menu
1447 Now, we create the menu.
1449 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1450 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1451 "use a minibuffer to select options for the citation under point.
1453 you select your option with a single key press."
1455 (let* ((choice (read-char (org-ref-get-menu-options)))
1456 (results (org-ref-get-bibtex-key-and-file))
1458 (cb (current-buffer))
1459 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1460 (bibfile (cdr results)))
1466 (bibtex-search-entry key))
1470 (org-ref-citation-at-point))
1476 (= choice ?\ )) ; space
1477 ;; this clears the minibuffer
1482 (org-ref-open-pdf-at-point))
1486 (org-ref-open-notes-at-point))
1490 (org-ref-open-url-at-point))
1492 ;; anything else we just quit.
1497 *** A function to format a cite link
1499 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.
1501 #+BEGIN_SRC emacs-lisp :tangle no
1502 ;(defun org-ref-cite-link-format (keyword desc format)
1504 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1505 ; ((eq format 'latex)
1506 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1507 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1511 *** The actual cite link
1512 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1514 #+BEGIN_SRC emacs-lisp :tangle no
1517 ; 'org-ref-cite-onclick-minibuffer-menu
1518 ; 'org-ref-cite-link-format)
1521 *** Automatic definition of the cite links
1522 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.
1524 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1525 (defmacro org-ref-make-completion-function (type)
1526 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1532 (let ((bibtex-files (org-ref-find-bibliography)))
1533 (bibtex-global-key-alist))))))
1536 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.
1538 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1539 (defmacro org-ref-make-format-function (type)
1540 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1545 (format "[[#%s][%s]]" key key))
1546 (org-ref-split-and-strip-string keyword) ","))
1553 (org-ref-split-and-strip-string keyword) ",") "]"))
1558 (format "<a href=\"#%s\">%s</a>" key key))
1559 (org-ref-split-and-strip-string keyword) ","))
1562 (if (string= (substring type -1) "s")
1563 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1564 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1565 (org-ref-split-and-strip-string keyword) ""))
1567 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1568 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1574 We create the links by mapping the function onto the list of defined link types.
1576 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1577 (defun org-ref-format-citation-description (desc)
1578 "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 ::."
1581 ((string-match "::" desc)
1582 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1583 (t (format "[%s]" desc))))
1585 (defun org-ref-define-citation-link (type &optional key)
1586 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1587 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1588 and the completion function."
1589 (interactive "sCitation Type: \ncKey: ")
1591 ;; create the formatting function
1592 (eval `(org-ref-make-format-function ,type))
1597 'org-ref-cite-onclick-minibuffer-menu
1598 (quote ,(intern (format "org-ref-format-%s" type)))))
1600 ;; create the completion function
1601 (eval `(org-ref-make-completion-function ,type))
1603 ;; store new type so it works with adding citations, which checks
1604 ;; for existence in this list
1605 (add-to-list 'org-ref-cite-types type)
1607 ;; and finally if a key is specified, we modify the reftex menu
1609 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1610 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1611 `((,key . ,(concat type ":%l")))))))
1613 ;; create all the link types and their completion functions
1614 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1617 *** org-ref-insert-cite-link
1618 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.
1620 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1621 (defun org-ref-insert-cite-link (alternative-cite)
1622 "Insert a default citation link using reftex. If you are on a link, it
1623 appends to the end of the link, otherwise, a new link is
1624 inserted. Use a prefix arg to get a menu of citation types."
1626 (org-ref-find-bibliography)
1627 (let* ((object (org-element-context))
1628 (link-string-beginning (org-element-property :begin object))
1629 (link-string-end (org-element-property :end object))
1630 (path (org-element-property :path object)))
1632 (if (not alternative-cite)
1635 ;; case where we are in a link
1636 ((and (equal (org-element-type object) 'link)
1637 (-contains? org-ref-cite-types (org-element-property :type object)))
1638 (goto-char link-string-end)
1639 ;; sometimes there are spaces at the end of the link
1640 ;; this code moves point pack until no spaces are there
1641 (while (looking-back " ") (backward-char))
1642 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1644 ;; We are next to a link, and we want to append
1647 (and (equal (org-element-type (org-element-context)) 'link)
1648 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1649 (while (looking-back " ") (backward-char))
1650 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1652 ;; insert fresh link
1655 (concat org-ref-default-citation-link
1657 (mapconcat 'identity (reftex-citation t) ",")))))
1659 ;; you pressed a C-u so we run this code
1665 : org-ref-insert-cite-link
1667 *** Completion in cite links
1668 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.
1670 #+BEGIN_SRC emacs-lisp :tangle no
1671 (defun org-cite-complete-link (&optional arg)
1672 "Completion function for cite links"
1674 org-ref-default-citation-link
1677 (let ((bibtex-files (org-ref-find-bibliography)))
1678 (bibtex-global-key-alist)))))
1681 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1683 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1684 (defun org-ref-insert-cite-with-completion (type)
1685 "Insert a cite link with completion"
1686 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1687 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1690 ** Storing links to a bibtex entry
1691 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.
1693 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1694 (defun org-ref-store-bibtex-entry-link ()
1695 "Save a citation link to the current bibtex entry. Saves in the default link type."
1697 (let ((link (concat org-ref-default-citation-link
1700 (bibtex-beginning-of-entry)
1701 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1702 (message "saved %s" link)
1703 (push (list link) org-stored-links)
1704 (car org-stored-links)))
1709 ** create simple text citation from bibtex entry
1711 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1712 (defun org-ref-bib-citation ()
1713 "from a bibtex entry, create and return a simple citation string."
1715 (bibtex-beginning-of-entry)
1716 (let* ((cb (current-buffer))
1717 (bibtex-expand-strings t)
1718 (entry (loop for (key . value) in (bibtex-parse-entry t)
1719 collect (cons (downcase key) value)))
1720 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1721 (year (reftex-get-bib-field "year" entry))
1722 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1723 (key (reftex-get-bib-field "=key=" entry))
1724 (journal (reftex-get-bib-field "journal" entry))
1725 (volume (reftex-get-bib-field "volume" entry))
1726 (pages (reftex-get-bib-field "pages" entry))
1727 (doi (reftex-get-bib-field "doi" entry))
1728 (url (reftex-get-bib-field "url" entry))
1730 ;;authors, "title", Journal, vol(iss):pages (year).
1731 (format "%s, \"%s\", %s, %s:%s (%s)"
1732 author title journal volume pages year)))
1736 : org-ref-bib-citation
1739 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1740 (defun org-ref-bib-html-citation ()
1741 "from a bibtex entry, create and return a simple citation with html links."
1743 (bibtex-beginning-of-entry)
1744 (let* ((cb (current-buffer))
1745 (bibtex-expand-strings t)
1746 (entry (loop for (key . value) in (bibtex-parse-entry t)
1747 collect (cons (downcase key) value)))
1748 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1749 (year (reftex-get-bib-field "year" entry))
1750 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1751 (key (reftex-get-bib-field "=key=" entry))
1752 (journal (reftex-get-bib-field "journal" entry))
1753 (volume (reftex-get-bib-field "volume" entry))
1754 (pages (reftex-get-bib-field "pages" entry))
1755 (doi (reftex-get-bib-field "doi" entry))
1756 (url (reftex-get-bib-field "url" entry))
1758 ;;authors, "title", Journal, vol(iss):pages (year).
1759 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1760 author title journal volume pages year)
1761 (when url (format " <a href=\"%s\">link</a>" url))
1762 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1766 ** open pdf from bibtex
1767 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1768 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1769 (defun org-ref-open-bibtex-pdf ()
1770 "open pdf for a bibtex entry, if it exists. assumes point is in
1771 the entry of interest in the bibfile. but does not check that."
1774 (bibtex-beginning-of-entry)
1775 (let* ((bibtex-expand-strings t)
1776 (entry (bibtex-parse-entry t))
1777 (key (reftex-get-bib-field "=key=" entry))
1778 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1780 (if (file-exists-p pdf)
1781 (org-open-link-from-string (format "[[file:%s]]" pdf))
1785 ** open notes from bibtex
1786 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1788 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1789 (defun org-ref-open-bibtex-notes ()
1790 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1792 I never did figure out how to use reftex to make this happen
1793 non-interactively. the reftex-format-citation function did not
1794 work perfectly; there were carriage returns in the strings, and
1795 it did not put the key where it needed to be. so, below I replace
1796 the carriage returns and extra spaces with a single space and
1797 construct the heading by hand."
1800 (bibtex-beginning-of-entry)
1801 (let* ((cb (current-buffer))
1802 (bibtex-expand-strings t)
1803 (entry (loop for (key . value) in (bibtex-parse-entry t)
1804 collect (cons (downcase key) value)))
1805 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1806 (year (reftex-get-bib-field "year" entry))
1807 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1808 (key (reftex-get-bib-field "=key=" entry))
1809 (journal (reftex-get-bib-field "journal" entry))
1810 (volume (reftex-get-bib-field "volume" entry))
1811 (pages (reftex-get-bib-field "pages" entry))
1812 (doi (reftex-get-bib-field "doi" entry))
1813 (url (reftex-get-bib-field "url" entry))
1816 ;; save key to clipboard to make saving pdf later easier by pasting.
1819 (kill-ring-save (point-min) (point-max)))
1821 ;; now look for entry in the notes file
1822 (if org-ref-bibliography-notes
1823 (find-file-other-window org-ref-bibliography-notes)
1824 (error "org-ref-bib-bibliography-notes is not set to anything"))
1826 (goto-char (point-min))
1827 ;; put new entry in notes if we don't find it.
1828 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1829 (funcall org-ref-open-notes-function)
1830 ;; no entry found, so add one
1831 (insert (format "\n** TODO %s - %s" year title))
1843 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1844 key author journal year volume pages doi url key org-ref-pdf-directory key))
1848 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1849 (defun org-ref-open-notes-from-reftex ()
1850 "Call reftex, and open notes for selected entry."
1852 (let ((bibtex-key )))
1854 ;; now look for entry in the notes file
1855 (if org-ref-bibliography-notes
1856 (find-file-other-window org-ref-bibliography-notes)
1857 (error "org-ref-bib-bibliography-notes is not set to anything"))
1859 (goto-char (point-min))
1861 (re-search-forward (format
1863 (first (reftex-citation t)) nil 'end))
1864 (funcall org-ref-open-notes-function))
1867 ** open url in browser from bibtex
1869 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1871 + 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.
1873 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1874 (defun org-ref-open-in-browser ()
1875 "Open the bibtex entry at point in a browser using the url field or doi field"
1878 (bibtex-beginning-of-entry)
1880 (let ((url (bibtex-autokey-get-field "url")))
1885 (let ((doi (bibtex-autokey-get-field "doi")))
1887 (if (string-match "^http" doi)
1889 (browse-url (format "http://dx.doi.org/%s" doi)))
1891 (message "No url or doi found"))))
1895 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.
1897 *** function to upload bibtex to citeulike
1899 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1900 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1901 "with point in a bibtex entry get bibtex string and submit to citeulike.
1903 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1905 (message "uploading to citeulike")
1907 (bibtex-narrow-to-entry)
1908 (let ((startpos (point-min))
1909 (endpos (point-max))
1910 (bibtex-string (buffer-string))
1911 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1912 (with-temp-buffer (insert bibtex-string)
1913 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1916 *** The upload script
1917 Here is the python script for uploading.
1919 *************** TODO document how to get the cookies
1923 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1925 import pickle, requests, sys
1928 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1929 cookies = pickle.load(f)
1931 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1933 bibtex = sys.stdin.read()
1935 data = {'pasted':bibtex,
1937 'tag_parsing':'simple',
1938 'strip_brackets':'no',
1939 'update_id':'bib-key',
1940 'btn_bibtex':'Import BibTeX file ...'}
1942 headers = {'content-type': 'multipart/form-data',
1943 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1945 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1949 ** Build a pdf from a bibtex file
1950 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.
1952 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1953 (defun org-ref-build-full-bibliography ()
1954 "build pdf of all bibtex entries, and open it."
1956 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1957 (bib-base (file-name-sans-extension bibfile))
1958 (texfile (concat bib-base ".tex"))
1959 (pdffile (concat bib-base ".pdf")))
1962 (insert (format "\\documentclass[12pt]{article}
1963 \\usepackage[version=3]{mhchem}
1965 \\usepackage[numbers]{natbib}
1966 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1970 \\bibliographystyle{unsrtnat}
1972 \\end{document}" bib-base))
1974 (shell-command (concat "pdflatex " bib-base))
1975 (shell-command (concat "bibtex " bib-base))
1976 (shell-command (concat "pdflatex " bib-base))
1977 (shell-command (concat "pdflatex " bib-base))
1978 (kill-buffer texfile)
1979 (org-open-file pdffile)
1983 ** Extract bibtex entries cited in an org-file
1984 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.
1986 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1987 (defun org-ref-extract-bibtex-entries ()
1988 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1990 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1992 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1993 (tempname (make-temp-file "extract-bib"))
1994 (contents (buffer-string))
1995 (cb (current-buffer))
1996 basename texfile bibfile results)
1998 ;; open tempfile and insert org-buffer contents
1999 (find-file tempname)
2001 (setq basename (file-name-sans-extension
2002 (file-name-nondirectory buffer-file-name))
2003 texfile (concat tempname ".tex")
2004 bibfile (concat tempname ".bib"))
2006 ;; see if we have a bibliography, and insert the default one if not.
2008 (goto-char (point-min))
2009 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2010 (insert (format "\nbibliography:%s"
2011 (mapconcat 'identity reftex-default-bibliography ",")))))
2014 ;; get a latex file and extract the references
2015 (org-latex-export-to-latex)
2018 (reftex-create-bibtex-file bibfile)
2020 ;; save results of the references
2021 (setq results (buffer-string))
2023 ;; kill buffers. these are named by basename, not full path
2024 (kill-buffer (concat basename ".bib"))
2025 (kill-buffer (concat basename ".tex"))
2026 (kill-buffer basename)
2028 (delete-file bibfile)
2029 (delete-file texfile)
2030 (delete-file tempname)
2032 ;; Now back to the original org buffer and insert the results
2033 (switch-to-buffer cb)
2034 (when (not (string= "" results))
2036 (goto-char (point-max))
2038 (org-insert-heading)
2039 (insert (format " Bibtex entries
2041 ,#+BEGIN_SRC text :tangle %s
2043 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2046 ** Find bad cite links
2047 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.
2049 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2052 (defun index (substring list)
2053 "return the index of string in a list of strings"
2056 (dolist (arg list i)
2057 (if (string-match (concat "^" substring "$") arg)
2062 ;; return counter if found, otherwise return nil
2066 (defun org-ref-find-bad-citations ()
2067 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2069 Makes a new buffer with clickable links."
2071 ;; generate the list of bibtex-keys and cited keys
2072 (let* ((bibtex-files (org-ref-find-bibliography))
2073 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2074 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2075 (bad-citations '()))
2077 (org-element-map (org-element-parse-buffer) 'link
2079 (let ((plist (nth 1 link)))
2080 (when (equal (plist-get plist ':type) "cite")
2081 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
2082 (when (not (index key bibtex-keys))
2083 (setq bad-citations (append bad-citations
2084 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2085 key (buffer-name)(plist-get plist ':begin)))))
2090 (switch-to-buffer-other-window "*Missing citations*")
2093 (insert "* List of bad cite links\n")
2094 (insert (mapconcat 'identity bad-citations ""))
2095 ;(setq buffer-read-only t)
2096 (use-local-map (copy-keymap org-mode-map))
2097 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2099 (when (get-buffer "*Missing citations*")
2100 (kill-buffer "*Missing citations*"))
2101 (message "No bad cite links found"))))
2104 ** Finding non-ascii characters
2105 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
2107 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2108 (defun org-ref-find-non-ascii-characters ()
2109 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2111 (occur "[^[:ascii:]]"))
2114 ** Resort a bibtex entry
2115 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.
2117 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2118 (defun org-ref-sort-bibtex-entry ()
2119 "sort fields of entry in standard order and downcase them"
2121 (bibtex-beginning-of-entry)
2122 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2123 (entry (bibtex-parse-entry))
2126 (type (cdr (assoc "=type=" entry)))
2127 (key (cdr (assoc "=key=" entry))))
2129 ;; these are the fields we want to order that are in this entry
2130 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2131 ;; we do not want to reenter these fields
2132 (setq entry-fields (remove "=key=" entry-fields))
2133 (setq entry-fields (remove "=type=" entry-fields))
2135 ;;these are the other fields in the entry
2136 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2139 ;; right now we only resort articles
2140 ((string= (downcase type) "article")
2143 (concat "@article{" key ",\n"
2146 (when (member field entry-fields)
2147 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2150 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2152 (bibtex-find-entry key)
2154 (bibtex-clean-entry)
2158 ** Clean a bibtex entry
2159 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.
2160 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.
2161 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2162 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2163 "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"
2165 (bibtex-beginning-of-entry)
2167 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2168 (unless (string-match ",$" (thing-at-point 'line))
2172 ;; check for empty pages, and put eid or article id in its place
2173 (let ((entry (bibtex-parse-entry))
2174 (pages (bibtex-autokey-get-field "pages"))
2175 (year (bibtex-autokey-get-field "year"))
2176 (doi (bibtex-autokey-get-field "doi"))
2177 ;; The Journal of Chemical Physics uses eid
2178 (eid (bibtex-autokey-get-field "eid")))
2180 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2181 ;; but we only want the doi.
2182 (when (string-match "^http://dx.doi.org/" doi)
2183 (bibtex-beginning-of-entry)
2184 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2186 (bibtex-make-field "doi")
2188 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2190 ;; asap articles often set year to 0, which messes up key
2191 ;; generation. fix that.
2192 (when (string= "0" year)
2193 (bibtex-beginning-of-entry)
2194 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2196 (bibtex-make-field "year")
2198 (insert (read-string "Enter year: ")))
2200 ;; fix pages if they are empty if there is an eid to put there.
2201 (when (string= "-" pages)
2203 (bibtex-beginning-of-entry)
2204 ;; this seems like a clunky way to set the pages field.But I
2205 ;; cannot find a better way.
2206 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2208 (bibtex-make-field "pages")
2212 ;; replace naked & with \&
2214 (bibtex-narrow-to-entry)
2215 (bibtex-beginning-of-entry)
2216 (message "checking &")
2217 (replace-regexp " & " " \\\\& ")
2220 ;; generate a key, and if it duplicates an existing key, edit it.
2222 (let ((key (bibtex-generate-autokey)))
2224 ;; first we delete the existing key
2225 (bibtex-beginning-of-entry)
2226 (re-search-forward bibtex-entry-maybe-empty-head)
2227 (if (match-beginning bibtex-key-in-head)
2228 (delete-region (match-beginning bibtex-key-in-head)
2229 (match-end bibtex-key-in-head)))
2230 ;; check if the key is in the buffer
2231 (when (save-excursion
2232 (bibtex-search-entry key))
2234 (bibtex-search-entry key)
2235 (bibtex-copy-entry-as-kill)
2236 (switch-to-buffer-other-window "*duplicate entry*")
2238 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2241 (kill-new key))) ;; save key for pasting
2243 ;; run hooks. each of these operates on the entry with no arguments.
2244 ;; this did not work like i thought, it gives a symbolp error.
2245 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2250 org-ref-clean-bibtex-entry-hook)
2252 ;; sort fields within entry
2253 (org-ref-sort-bibtex-entry)
2254 ;; check for non-ascii characters
2255 (occur "[^[:ascii:]]")
2260 : org-ref-clean-bibtex-entry
2262 ** Sort the entries in a citation link by year
2263 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2265 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2266 (defun org-ref-get-citation-year (key)
2267 "get the year of an entry with key. Returns year as a string."
2269 (let* ((results (org-ref-get-bibtex-key-and-file key))
2270 (bibfile (cdr results)))
2272 (insert-file-contents bibfile)
2273 (bibtex-search-entry key nil 0)
2274 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2277 (defun org-ref-sort-citation-link ()
2278 "replace link at point with sorted link by year"
2280 (let* ((object (org-element-context))
2281 (type (org-element-property :type object))
2282 (begin (org-element-property :begin object))
2283 (end (org-element-property :end object))
2284 (link-string (org-element-property :path object))
2286 (setq keys (org-ref-split-and-strip-string link-string))
2287 (setq years (mapcar 'org-ref-get-citation-year keys))
2288 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2289 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2290 ;; now get the keys separated by commas
2291 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2292 ;; and replace the link with the sorted keys
2293 (cl--set-buffer-substring begin end (concat type ":" keys))))
2296 ** Sort entries in citation links with shift-arrow keys
2297 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2298 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2299 (defun org-ref-swap-keys (i j keys)
2300 "swap the keys in a list with index i and j"
2301 (let ((tempi (nth i keys)))
2302 (setf (nth i keys) (nth j keys))
2303 (setf (nth j keys) tempi))
2306 (defun org-ref-swap-citation-link (direction)
2307 "move citation at point in direction +1 is to the right, -1 to the left"
2309 (let* ((object (org-element-context))
2310 (type (org-element-property :type object))
2311 (begin (org-element-property :begin object))
2312 (end (org-element-property :end object))
2313 (link-string (org-element-property :path object))
2315 ;; We only want this to work on citation links
2316 (when (-contains? org-ref-cite-types type)
2317 (setq key (org-ref-get-bibtex-key-under-cursor))
2318 (setq keys (org-ref-split-and-strip-string link-string))
2319 (setq i (index key keys)) ;; defined in org-ref
2320 (if (> direction 0) ;; shift right
2321 (org-ref-swap-keys i (+ i 1) keys)
2322 (org-ref-swap-keys i (- i 1) keys))
2323 (setq keys (mapconcat 'identity keys ","))
2324 ;; and replace the link with the sorted keys
2325 (cl--set-buffer-substring begin end (concat type ":" keys))
2326 ;; now go forward to key so we can move with the key
2327 (re-search-forward key)
2328 (goto-char (match-beginning 0)))))
2330 ;; add hooks to make it work
2331 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2332 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2335 I like convenience. Here are some aliases for faster typing.
2337 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2338 (defalias 'oro 'org-ref-open-citation-at-point)
2339 (defalias 'orc 'org-ref-citation-at-point)
2340 (defalias 'orp 'org-ref-open-pdf-at-point)
2341 (defalias 'oru 'org-ref-open-url-at-point)
2342 (defalias 'orn 'org-ref-open-notes-at-point)
2343 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2345 (defalias 'orib 'org-ref-insert-bibliography-link)
2346 (defalias 'oric 'org-ref-insert-cite-link)
2347 (defalias 'orir 'org-ref-insert-ref-link)
2348 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2350 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2353 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2360 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2362 [[elisp:(org-babel-load-file "org-ref.org")]]