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."
108 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.
110 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
111 (defcustom org-ref-cite-types
112 '("cite" "nocite" ;; the default latex cite commands
113 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
114 "citet" "citet*" "citep" "citep*"
115 "citealt" "citealt*" "citealp" "citealp*"
117 "citeauthor" "citeauthor*"
118 "citeyear" "citeyear*"
119 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
121 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
123 "parencite" "Parencite"
124 "footcite" "footcitetext"
125 "textcite" "Textcite"
126 "smartcite" "Smartcite"
127 "cite*" "parencite*" "supercite"
128 "autocite" "Autocite" "autocite*" "Autocite*"
130 "citetitle" "citetitle*"
131 "citedate" "citedate*"
133 "fullcite" "footfullcite"
134 ;; "volcite" "Volcite" cannot support the syntax
135 "notecite" "Notecite"
136 "pnotecite" "Pnotecite"
138 ;; multicites. Very limited support for these.
139 "cites" "Cites" "parencites" "Parencites"
140 "footcites" "footcitetexts"
141 "smartcites" "Smartcites" "textcites" "Textcites"
142 "supercites" "autocites" "Autocites"
144 "List of citation types known in org-ref"
145 :type '(repeat :tag "List of citation types" string)
149 We need a hook variable to store user-defined bibtex entry cleaning functions
150 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
151 (defcustom org-ref-clean-bibtex-entry-hook nil
152 "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
158 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
159 (defvar org-ref-bibliography-files
161 "variable to hold bibliography files to be searched")
164 ** org-mode / reftex setup
166 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.
168 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
169 (defun org-mode-reftex-setup ()
170 (load-library "reftex")
171 (and (buffer-file-name)
172 (file-exists-p (buffer-file-name))
173 (global-auto-revert-mode t)
175 (make-local-variable 'reftex-cite-format)
176 (setq reftex-cite-format 'org)
177 (define-key org-mode-map (kbd org-ref-insert-cite-key) 'org-ref-insert-cite-link))
179 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
181 (eval-after-load 'reftex-vars
183 (add-to-list 'reftex-cite-format-builtin
184 '(org "Org-mode citation"
185 ((?\C-m . "cite:%l") ; default
186 (?d . ",%l") ; for appending
192 (?h . "citeauthor:%l")
193 (?H . "citeauthor*:%l")
200 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.
202 #+BEGIN_SRC emacs-lisp :tangle no
204 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
205 (append (nth 2 (assoc 'org reftex-cite-format-builtin)) '((?W . "textcite:%l")
206 (?z . "newcite:%l"))))
209 You can define a new citation link like this:
210 #+BEGIN_SRC emacs-lisp :tangle no
211 (org-ref-define-citation-link "citez" ?z)
215 Most of this library is the creation of functional links to help with references and citations.
217 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.
219 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
220 (defun org-ref-strip-string (string)
221 "strip leading and trailing whitespace from the string"
222 (replace-regexp-in-string
223 (concat search-whitespace-regexp "$" ) ""
224 (replace-regexp-in-string
225 (concat "^" search-whitespace-regexp ) "" string)))
228 It is helpful to make the previous function operate on a list of strings here.
230 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
231 (defun org-ref-split-and-strip-string (string)
232 "split key-string and strip keys. Assumes the key-string is comma delimited"
233 (mapcar 'org-ref-strip-string (split-string string ",")))
236 ** bibliography and bibliographystyle
237 *** An html bibliography
239 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.
241 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
242 (defun org-ref-reftex-get-bib-field (field entry &optional format)
243 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
245 (setq result (reftex-get-bib-field field entry format))
246 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
247 (setq result (substring result 1 -1)))
248 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
249 (setq result (substring result 1 -1)))
252 (defun org-ref-reftex-format-citation (entry format)
253 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
254 to the format argument. The format is a string with these percent escapes.
256 In the format, the following percent escapes will be expanded.
258 %l The BibTeX label of the citation.
259 %a List of author names, see also `reftex-cite-punctuation'.
260 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
261 %A First author name only.
262 %e Works like %a, but on list of editor names. (%2e and %E work a well)
264 It is also possible to access all other BibTeX database fields:
265 %b booktitle %c chapter %d edition %h howpublished
266 %i institution %j journal %k key %m month
267 %n number %o organization %p pages %P first page
268 %r address %s school %u publisher %t title
270 %B booktitle, abbreviated %T title, abbreviated
275 Usually, only %l is needed. The other stuff is mainly for the echo area
276 display, and for (setq reftex-comment-citations t).
278 %< as a special operator kills punctuation and space around it after the
279 string has been formatted.
281 A pair of square brackets indicates an optional argument, and RefTeX
282 will prompt for the values of these arguments.
284 Beware that all this only works with BibTeX database files. When
285 citations are made from the \bibitems in an explicit thebibliography
286 environment, only %l is available."
287 ;; Format a citation from the info in the BibTeX ENTRY
289 (unless (stringp format) (setq format "\\cite{%l}"))
291 (if (and reftex-comment-citations
292 (string-match "%l" reftex-cite-comment-format))
293 (error "reftex-cite-comment-format contains invalid %%l"))
296 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
298 (let ((n (string-to-number (match-string 4 format)))
299 (l (string-to-char (match-string 5 format)))
305 (org-ref-reftex-get-bib-field "&key" entry)
306 (if reftex-comment-citations
307 reftex-cite-comment-format
309 ((= l ?a) (reftex-format-names
310 (reftex-get-bib-names "author" entry)
312 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
313 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
314 ((= l ?B) (reftex-abbreviate-title
315 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
316 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
317 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
318 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
319 ((= l ?e) (reftex-format-names
320 (reftex-get-bib-names "editor" entry)
322 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
323 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
324 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
325 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
326 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
327 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
328 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
329 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
330 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
331 ((= l ?P) (car (split-string
332 (org-ref-reftex-get-bib-field "pages" entry)
334 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
335 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
336 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
337 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
338 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
339 ;; strip enclosing brackets from title if they are there
340 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
341 ((= l ?T) (reftex-abbreviate-title
342 (org-ref-reftex-get-bib-field "title" entry)))
343 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
344 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
347 (setq b (match-beginning 2) e (match-end 2))
348 (setq b (match-beginning 3) e (match-end 3)))
349 (setq format (concat (substring format 0 b) rpl (substring format e)))))
350 (while (string-match "%%" format)
351 (setq format (replace-match "%" t t format)))
352 (while (string-match "[ ,.;:]*%<" format)
353 (setq format (replace-match "" t t format)))
354 ;; also replace carriage returns, tabs, and multiple whitespaces
355 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
358 (defun org-ref-get-bibtex-entry-citation (key)
359 "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
361 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
362 (file) (entry) (bibtex-entry) (entry-type) (format))
364 (setq file (catch 'result
365 (loop for file in org-ref-bibliography-files do
366 (if (org-ref-key-in-file-p key (file-truename file))
368 (message "%s not found in %s" key (file-truename file))))))
371 (insert-file-contents file)
372 (bibtex-search-entry key nil 0)
373 (setq bibtex-entry (bibtex-parse-entry))
374 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
375 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
377 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
379 (bibtex-narrow-to-entry)
380 (setq entry (buffer-string)))))
385 : org-ref-reftex-format-citation
387 Here is how to use the function. You call it with point in an entry in a bibtex file.
389 #+BEGIN_SRC emacs-lisp :tangle no
390 (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>."))
391 (org-ref-get-bibtex-entry-citation "armiento-2014-high"))
394 : 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>.
396 I am not sure why full author names are not used.
398 This code provides some functions to generate a simple sorted bibliography in html. First we get all the keys in the buffer.
400 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
401 (defun org-ref-get-bibtex-keys ()
402 "return a list of unique keys in the buffer."
404 (org-element-map (org-element-parse-buffer) 'link
406 (let ((plist (nth 1 link)))
407 (when (-contains? org-ref-cite-types (plist-get plist ':type))
410 (org-ref-split-and-strip-string (plist-get plist ':path)))
411 (when (not (-contains? keys key))
412 (setq keys (append keys (list key)))))))))
413 ;; Sort keys alphabetically
414 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
418 This function gets the html for one entry.
420 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
421 (defun org-ref-get-bibtex-entry-html (key)
422 "returns an html string for the bibliography entry corresponding to key"
424 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
427 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
429 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
430 (defun org-ref-get-html-bibliography ()
431 "Create an html bibliography when there are keys"
432 (let ((keys (org-ref-get-bibtex-keys)))
434 (concat "<h1>Bibliography</h1>
436 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
440 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.
442 *** An org bibliography
443 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.
445 First, we get the string for a single entry.
446 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
447 (defun org-ref-get-bibtex-entry-org (key)
448 "returns an org string for the bibliography entry corresponding to key"
449 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
450 (file) (entry) (bibtex-entry) (entry-type) (format))
452 (setq file (catch 'result
453 (loop for file in org-ref-bibliography-files do
454 (if (org-ref-key-in-file-p key (file-truename file))
456 (message "%s not found in %s" key (file-truename file))))))
459 (insert-file-contents file)
460 (bibtex-search-entry key nil 0)
461 (setq entry (bibtex-parse-entry))
466 " (org-ref-reftex-get-bib-field "author" entry)
467 (org-ref-reftex-get-bib-field "title" entry)
468 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
469 (mapconcat (lambda (element) (format " :%s: %s"
470 (upcase (car element))
476 Now, we loop over the keys, and combine all the entries into a bibliography.
477 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
478 (defun org-ref-get-org-bibliography ()
479 "Create an org bibliography when there are keys"
480 (let ((keys (org-ref-get-bibtex-keys)))
482 (concat "* Bibliography
484 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
488 *** An ascii bibliography
490 This function gets the html for one entry.
492 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
493 (defun org-ref-get-bibtex-entry-ascii (key)
494 "returns an ascii string for the bibliography entry corresponding to key"
496 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
499 Now, we map over the whole list of keys, and the whole bibliography, formatted as an unordered list.
501 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
502 (defun org-ref-get-ascii-bibliography ()
503 "Create an html bibliography when there are keys"
504 (let ((keys (org-ref-get-bibtex-keys)))
510 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
516 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.
518 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
519 (org-add-link-type "bibliography"
520 ;; this code is run on clicking. The bibliography
521 ;; may contain multiple files. this code finds the
522 ;; one you clicked on and opens it.
523 (lambda (link-string)
524 ;; get link-string boundaries
525 ;; we have to go to the beginning of the line, and then search forward
528 ;; object is the link you clicked on
529 (object (org-element-context))
531 (link-string-beginning)
535 (goto-char (org-element-property :begin object))
536 (search-forward link-string nil nil 1)
537 (setq link-string-beginning (match-beginning 0))
538 (setq link-string-end (match-end 0)))
540 ;; We set the reftex-default-bibliography
541 ;; here. it should be a local variable only in
542 ;; the current buffer. We need this for using
543 ;; reftex to do citations.
544 (set (make-local-variable 'reftex-default-bibliography)
545 (split-string (org-element-property :path object) ","))
547 ;; now if we have comma separated bibliographies
548 ;; we find the one clicked on. we want to
549 ;; search forward to next comma from point
551 (if (search-forward "," link-string-end 1 1)
552 (setq key-end (- (match-end 0) 1)) ; we found a match
553 (setq key-end (point)))) ; no comma found so take the point
554 ;; and backward to previous comma from point
556 (if (search-backward "," link-string-beginning 1 1)
557 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
558 (setq key-beginning (point)))) ; no match found
559 ;; save the key we clicked on.
560 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
561 (find-file bibfile))) ; open file on click
564 (lambda (keyword desc format)
566 ((eq format 'org) (org-ref-get-org-bibliography))
567 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
568 ((eq format 'html) (org-ref-get-html-bibliography))
570 ;; write out the latex bibliography command
571 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" keyword))))))
574 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
575 (org-add-link-type "printbibliography"
576 (lambda (arg) (message "Nothing implemented for clicking here."))
577 (lambda (keyword desc format)
579 ((eq format 'org) (org-ref-get-org-bibliography))
580 ((eq format 'html) (org-ref-get-html-bibliography))
582 ;; write out the latex bibliography command
583 (format "\\printbibliography" keyword))
587 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, ...
589 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
590 (org-add-link-type "bibliographystyle"
591 (lambda (arg) (message "Nothing implemented for clicking here."))
592 (lambda (keyword desc format)
595 ;; write out the latex bibliography command
596 (format "\\bibliographystyle{%s}" keyword)))))
599 *** Completion for bibliography link
602 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
603 (defun org-bibliography-complete-link (&optional arg)
604 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
606 (defun org-ref-insert-bibliography-link ()
607 "insert a bibliography with completion"
609 (insert (org-bibliography-complete-link)))
613 This is apparently used for biblatex.
614 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
615 (org-add-link-type "addbibresource"
616 ;; this code is run on clicking. The addbibresource
617 ;; may contain multiple files. this code finds the
618 ;; one you clicked on and opens it.
619 (lambda (link-string)
620 ;; get link-string boundaries
621 ;; we have to go to the beginning of the line, and then search forward
624 ;; object is the link you clicked on
625 (object (org-element-context))
627 (link-string-beginning)
631 (goto-char (org-element-property :begin object))
632 (search-forward link-string nil nil 1)
633 (setq link-string-beginning (match-beginning 0))
634 (setq link-string-end (match-end 0)))
636 ;; We set the reftex-default-addbibresource
637 ;; here. it should be a local variable only in
638 ;; the current buffer. We need this for using
639 ;; reftex to do citations.
640 (set (make-local-variable 'reftex-default-addbibresource)
641 (split-string (org-element-property :path object) ","))
643 ;; now if we have comma separated bibliographies
644 ;; we find the one clicked on. we want to
645 ;; search forward to next comma from point
647 (if (search-forward "," link-string-end 1 1)
648 (setq key-end (- (match-end 0) 1)) ; we found a match
649 (setq key-end (point)))) ; no comma found so take the point
650 ;; and backward to previous comma from point
652 (if (search-backward "," link-string-beginning 1 1)
653 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
654 (setq key-beginning (point)))) ; no match found
655 ;; save the key we clicked on.
656 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
657 (find-file bibfile))) ; open file on click
660 (lambda (keyword desc format)
662 ((eq format 'html) (format "")); no output for html
664 ;; write out the latex addbibresource command
665 (format "\\addbibresource{%s}" keyword)))))
670 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.
672 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
673 (defun org-ref-list-of-figures (&optional arg)
674 "Generate buffer with list of figures in them"
676 (save-excursion (widen)
677 (let* ((c-b (buffer-name))
680 (org-element-map (org-element-parse-buffer) 'link
682 "create a link for to the figure"
684 (and (string= (org-element-property :type link) "file")
686 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
687 (org-element-property :path link)))
690 (let* ((start (org-element-property :begin link))
691 (parent (car (cdr (org-element-property :parent link))))
692 (caption (caaar (plist-get parent :caption)))
693 (name (plist-get parent :name)))
696 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
697 c-b start counter (or name "") caption)
699 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
700 c-b start counter (or name "")))))))))
701 (switch-to-buffer "*List of Figures*")
702 (setq buffer-read-only nil)
705 (insert (mapconcat 'identity list-of-figures ""))
706 (setq buffer-read-only t)
707 (use-local-map (copy-keymap org-mode-map))
708 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
712 'org-ref-list-of-figures ; on click
713 (lambda (keyword desc format)
716 (format "\\listoffigures")))))
721 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
722 (defun org-ref-list-of-tables (&optional arg)
723 "Generate a buffer with a list of tables"
727 (let* ((c-b (buffer-name))
730 (org-element-map (org-element-parse-buffer 'element) 'table
732 "create a link for to the table"
734 (let ((start (org-element-property :begin table))
735 (name (org-element-property :name table))
736 (caption (caaar (org-element-property :caption table))))
739 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
740 c-b start counter (or name "") caption)
742 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
743 c-b start counter (or name ""))))))))
744 (switch-to-buffer "*List of Tables*")
745 (setq buffer-read-only nil)
748 (insert (mapconcat 'identity list-of-tables ""))
749 (setq buffer-read-only t)
750 (use-local-map (copy-keymap org-mode-map))
751 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
755 'org-ref-list-of-tables
756 (lambda (keyword desc format)
759 (format "\\listoftables")))))
763 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.
764 *************** TODO search tblnames, custom_ids and check for case sensitivity
767 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
771 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
772 (message (format "%s occurences"
773 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max) t)
774 ;; for tblname, it is not enough to get word boundary
775 ;; tab-little and tab-little-2 match then.
776 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)
777 (count-matches (format "\\label{%s}\\b" label) (point-min) (point-max) t)
778 ;; this is the org-format #+label:
779 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max) t)))))
780 (lambda (keyword desc format)
782 ((eq format 'html) (format "(<label>%s</label>)" path))
784 (format "\\label{%s}" keyword)))))
787 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.
789 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
790 (defun org-label-store-link ()
791 "store a link to a label. The output will be a ref to that label"
792 ;; First we have to make sure we are on a label link.
793 (let* ((object (org-element-context)))
794 (when (and (equal (org-element-type object) 'link)
795 (equal (org-element-property :type object) "label"))
796 (org-store-link-props
798 :link (concat "ref:" (org-element-property :path object))))
800 ;; Store link on table
801 (when (equal (org-element-type object) 'table)
802 (org-store-link-props
804 :link (concat "ref:" (org-element-property :name object))))
806 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
807 ;; store link on heading with custom_id
808 ; (when (and (equal (org-element-type object) 'headline)
809 ; (org-entry-get (point) "CUSTOM_ID"))
810 ; (org-store-link-props
812 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
814 ;; and to #+label: lines
815 (when (and (equal (org-element-type object) 'paragraph)
816 (org-element-property :name object))
817 (org-store-link-props
819 :link (concat "ref:" (org-element-property :name object))))
822 (add-hook 'org-store-link-functions 'org-label-store-link)
826 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.
828 At the moment, ref links are not usable for section links. You need [[#CUSTOM_ID]] type links.
830 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
834 "on clicking goto the label. Navigate back with C-c &"
836 ;; next search from beginning of the buffer
838 ;; it is possible you would not find the label if narrowing is in effect
845 (goto-char (point-min))
846 (re-search-forward (format "label:%s\\b" label) nil t))
850 (goto-char (point-min))
851 (re-search-forward (format "\\label{%s}" label) nil t))
853 ;; #+label: name org-definition
855 (goto-char (point-min))
856 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
860 (goto-char (point-min))
861 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
863 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
864 ;; you need [[#label]] links.
867 ; (goto-char (point-min))
868 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
870 ;; we did not find anything, so go back to where we came
872 (error "%s not found" label))
873 (message "go back with (org-mark-ring-goto) `C-c &`"))
875 (lambda (keyword desc format)
877 ((eq format 'html) (format "(<ref>%s</ref>)" path))
879 (format "\\ref{%s}" keyword)))))
882 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.
884 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
885 (defun org-ref-get-custom-ids ()
886 "return a list of custom_id properties in the buffer"
887 (let ((results '()) custom_id)
890 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
891 (when (not (null custom_id))
892 (setq results (append results (list custom_id)))))))
896 Here we get a list of the labels defined as raw latex labels, e.g. \label{eqtre}.
897 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
898 (defun org-ref-get-latex-labels ()
900 (goto-char (point-min))
902 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
903 (add-to-list 'matches (match-string-no-properties 1) t))
907 Finally, we get the table names.
909 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
910 (defun org-ref-get-tblnames ()
911 (org-element-map (org-element-parse-buffer 'element) 'table
913 (org-element-property :name table))))
916 Now, we can put all the labels together which will give us a list of candidates.
918 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
919 (defun org-ref-get-labels ()
920 "returns a list of labels in the buffer that you can make a ref link to. this is used to auto-complete ref links."
924 (goto-char (point-min))
926 (while (re-search-forward "label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
927 (add-to-list 'matches (match-string-no-properties 1) t))
928 (append matches (org-ref-get-latex-labels) (org-ref-get-tblnames) (org-ref-get-custom-ids))))))
931 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.
933 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
934 (defun org-ref-complete-link (&optional arg)
935 "Completion function for ref links"
937 (setq label (completing-read "label: " (org-ref-get-labels)))
938 (format "ref:%s" label)))
941 Alternatively, you may want to just call a function that inserts a link with completion:
943 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
944 (defun org-ref-insert-ref-link ()
946 (insert (org-ref-complete-link)))
951 This refers to the page of a label in LaTeX.
953 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
957 "on clicking goto the label. Navigate back with C-c &"
959 ;; next search from beginning of the buffer
965 (goto-char (point-min))
966 (re-search-forward (format "label:%s\\b" label) nil t))
970 (goto-char (point-min))
971 (re-search-forward (format "\\label{%s}" label) nil t))
973 ;; #+label: name org-definition
975 (goto-char (point-min))
976 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
980 (goto-char (point-min))
981 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
983 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
984 ;; you need [[#label]] links.
987 ; (goto-char (point-min))
988 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
990 ;; we did not find anything, so go back to where we came
992 (error "%s not found" label))
993 (message "go back with (org-mark-ring-goto) `C-c &`"))
995 (lambda (keyword desc format)
997 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
999 (format "\\pageref{%s}" keyword)))))
1002 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1003 (defun org-pageref-complete-link (&optional arg)
1004 "Completion function for ref links"
1006 (setq label (completing-read "label: " (org-ref-get-labels)))
1007 (format "ref:%s" label)))
1010 Alternatively, you may want to just call a function that inserts a link with completion:
1012 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1013 (defun org-pageref-insert-ref-link ()
1015 (insert (org-pageref-complete-link)))
1020 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.
1022 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1026 "on clicking goto the label. Navigate back with C-c &"
1027 (org-mark-ring-push)
1028 ;; next search from beginning of the buffer
1034 (goto-char (point-min))
1035 (re-search-forward (format "\\label{%s}" label) nil t))
1037 ;; we did not find anything, so go back to where we came
1038 (org-mark-ring-goto)
1039 (error "%s not found" label))
1040 (message "go back with (org-mark-ring-goto) `C-c &`"))
1042 (lambda (keyword desc format)
1044 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1046 (format "\\nameref{%s}" keyword)))))
1050 This is just the LaTeX ref for equations. On export, the reference is enclosed in parentheses.
1052 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1056 "on clicking goto the label. Navigate back with C-c &"
1057 (org-mark-ring-push)
1058 ;; next search from beginning of the buffer
1060 (goto-char (point-min))
1063 ;; search forward for the first match
1065 (re-search-forward (format "label:%s" label) nil t)
1067 (re-search-forward (format "\\label{%s}" label) nil t)
1068 ;; #+label: name org-definition
1069 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1070 (org-mark-ring-goto)
1071 (error "%s not found" label))
1072 (message "go back with (org-mark-ring-goto) `C-c &`"))
1074 (lambda (keyword desc format)
1076 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1078 (format "\\eqref{%s}" keyword)))))
1083 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.
1085 *** Implementing the click actions of cite
1087 **** Getting the key we clicked on
1088 The first thing we need is to get the bibtex key we clicked on.
1090 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1091 (defun org-ref-get-bibtex-key-under-cursor ()
1092 "returns key under the bibtex cursor. We search forward from
1093 point to get a comma, or the end of the link, and then backwards
1094 to get a comma, or the beginning of the link. that delimits the
1095 keyword we clicked on. We also strip the text properties."
1097 (let* ((object (org-element-context))
1098 (link-string (org-element-property :path object)))
1100 (if (not (org-element-property :contents-begin object))
1101 ;; this means no description in the link
1103 ;; we need the link path start and end
1105 (goto-char (org-element-property :begin object))
1106 (search-forward link-string nil nil 1)
1107 (setq link-string-beginning (match-beginning 0))
1108 (setq link-string-end (match-end 0)))
1110 ;; The key is the text between commas, or the link boundaries
1112 (if (search-forward "," link-string-end t 1)
1113 (setq key-end (- (match-end 0) 1)) ; we found a match
1114 (setq key-end link-string-end))) ; no comma found so take the end
1115 ;; and backward to previous comma from point which defines the start character
1117 (if (search-backward "," link-string-beginning 1 1)
1118 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1119 (setq key-beginning link-string-beginning))) ; no match found
1120 ;; save the key we clicked on.
1121 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1122 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1124 ;; link with description. assume only one key
1128 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.
1130 **** Getting the bibliographies
1131 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1132 (defun org-ref-find-bibliography ()
1133 "find the bibliography in the buffer.
1134 This function sets and returns cite-bibliography-files, which is a list of files
1135 either from bibliography:f1.bib,f2.bib
1136 \bibliography{f1,f2}
1137 internal bibliographies
1139 falling back to what the user has set in org-ref-default-bibliography
1144 (goto-char (point-min))
1145 ;; look for a bibliography link
1146 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1147 (setq org-ref-bibliography-files
1148 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1149 (throw 'result org-ref-bibliography-files))
1152 ;; we did not find a bibliography link. now look for \bibliography
1153 (goto-char (point-min))
1154 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1155 ;; split, and add .bib to each file
1156 (setq org-ref-bibliography-files
1157 (mapcar (lambda (x) (concat x ".bib"))
1158 (mapcar 'org-ref-strip-string
1159 (split-string (match-string 1) ","))))
1160 (throw 'result org-ref-bibliography-files))
1162 ;; no bibliography found. maybe we need a biblatex addbibresource
1163 (goto-char (point-min))
1164 ;; look for a bibliography link
1165 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1166 (setq org-ref-bibliography-files
1167 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1168 (throw 'result org-ref-bibliography-files))
1170 ;; we did not find anything. use defaults
1171 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1173 ;; set reftex-default-bibliography so we can search
1174 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1175 org-ref-bibliography-files)
1178 **** Finding the bibliography file a key is in
1179 Now, we can see if an entry is in a file.
1181 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1182 (defun org-ref-key-in-file-p (key filename)
1183 "determine if the key is in the file"
1184 (interactive "skey: \nsFile: ")
1185 (save-current-buffer
1186 (let ((bibtex-files (list filename)))
1187 (bibtex-search-entry key t))))
1190 Finally, we want to know which file the key is in.
1192 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1193 (defun org-ref-get-bibtex-key-and-file (&optional key)
1194 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1196 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1199 (setq key (org-ref-get-bibtex-key-under-cursor)))
1200 (setq file (catch 'result
1201 (loop for file in org-ref-bibliography-files do
1202 (if (org-ref-key-in-file-p key (file-truename file))
1203 (throw 'result file)))))
1207 **** Creating the menu for when we click on a key
1209 :ID: d7b7530b-802f-42b1-b61e-1e77da33e278
1211 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.
1213 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1214 (defun org-ref-get-menu-options ()
1215 "returns a dynamically determined string of options for the citation under point.
1217 we check to see if there is pdf, and if the key actually exists in the bibliography"
1219 (let* ((results (org-ref-get-bibtex-key-and-file))
1221 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1222 (bibfile (cdr results))
1223 m1 m2 m3 m4 m5 menu-string)
1224 (setq m1 (if bibfile
1228 (setq m3 (if (file-exists-p pdf-file)
1234 (string= (catch 'url
1238 (insert-file-contents bibfile)
1239 (bibtex-search-entry key)
1241 (string= (setq url (bibtex-autokey-get-field "url")) ""))
1245 (string= (setq url (bibtex-autokey-get-field "doi")) ""))
1246 (throw 'url url))))) "")))
1247 "(u)rl" "(no url found)"))
1249 (setq m2 (if bibfile
1251 (setq citation (progn
1253 (insert-file-contents bibfile)
1254 (bibtex-search-entry key)
1255 (org-ref-bib-citation))))
1259 (setq menu-string (mapconcat 'identity (list m2 "\n" m1 m3 m4 m5 "(q)uit") " "))
1263 **** convenience functions to act on citation at point
1265 :ID: af0b2a82-a7c9-4c08-9dac-09f93abc4a92
1267 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.
1269 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1270 (defun org-ref-open-pdf-at-point ()
1271 "open the pdf for bibtex key under point if it exists"
1273 (let* ((results (org-ref-get-bibtex-key-and-file))
1275 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1276 (if (file-exists-p pdf-file)
1277 (org-open-file pdf-file)
1278 (message "no pdf found for %s" key))))
1281 (defun org-ref-open-url-at-point ()
1282 "open the url for bibtex key under point."
1284 (let* ((results (org-ref-get-bibtex-key-and-file))
1286 (bibfile (cdr results)))
1289 (insert-file-contents bibfile)
1290 (bibtex-search-entry key)
1291 ;; I like this better than bibtex-url which does not always find
1294 (let ((url (bibtex-autokey-get-field "url")))
1299 (let ((doi (bibtex-autokey-get-field "doi")))
1301 (if (string-match "^http" doi)
1303 (browse-url (format "http://dx.doi.org/%s" doi)))
1304 (throw 'done nil))))))))
1306 (defun org-ref-open-notes-at-point ()
1307 "open the notes for bibtex key under point."
1309 (let* ((results (org-ref-get-bibtex-key-and-file))
1311 (bibfile (cdr results)))
1314 (insert-file-contents bibfile)
1315 (bibtex-search-entry key)
1316 (org-ref-open-bibtex-notes)))))
1318 (defun org-ref-citation-at-point ()
1319 "give message of current citation at point"
1321 (let* ((cb (current-buffer))
1322 (results (org-ref-get-bibtex-key-and-file))
1324 (bibfile (cdr results)))
1325 (message "%s" (progn
1327 (insert-file-contents bibfile)
1328 (bibtex-search-entry key)
1329 (org-ref-bib-citation))))))
1331 (defun org-ref-open-citation-at-point ()
1332 "open bibtex file to key at point"
1334 (let* ((cb (current-buffer))
1335 (results (org-ref-get-bibtex-key-and-file))
1337 (bibfile (cdr results)))
1339 (bibtex-search-entry key)))
1342 **** the actual minibuffer menu
1343 Now, we create the menu.
1345 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1346 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1347 "use a minibuffer to select options for the citation under point.
1349 you select your option with a single key press."
1351 (let* ((choice (read-char (org-ref-get-menu-options)))
1352 (results (org-ref-get-bibtex-key-and-file))
1354 (cb (current-buffer))
1355 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1356 (bibfile (cdr results)))
1362 (bibtex-search-entry key))
1366 (org-ref-citation-at-point))
1372 (= choice ?\ )) ; space
1373 ;; this clears the minibuffer
1378 (org-ref-open-pdf-at-point))
1382 (org-ref-open-notes-at-point))
1386 (org-ref-open-url-at-point))
1388 ;; anything else we just quit.
1393 *** A function to format a cite link
1395 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.
1397 #+BEGIN_SRC emacs-lisp :tangle no
1398 ;(defun org-ref-cite-link-format (keyword desc format)
1400 ; ((eq format 'html) (mapconcat (lambda (key) (format "<a name=\"#%s\">%s</a>" key key) (org-ref-split-and-strip-string keyword) ",")))
1401 ; ((eq format 'latex)
1402 ; (concat "\\cite" (when desc (format "[%s]" desc)) "{"
1403 ; (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1407 *** The actual cite link
1408 Finally, we define the cite link. This is deprecated; the links are autogenerated later. This is here for memory.
1410 #+BEGIN_SRC emacs-lisp :tangle no
1413 ; 'org-ref-cite-onclick-minibuffer-menu
1414 ; 'org-ref-cite-link-format)
1417 *** Automatic definition of the cite links
1418 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.
1420 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1421 (defmacro org-ref-make-completion-function (type)
1422 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1428 (let ((bibtex-files (org-ref-find-bibliography)))
1429 (bibtex-global-key-alist))))))
1432 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.
1434 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1435 (defmacro org-ref-make-format-function (type)
1436 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1441 (format "[[#%s][%s]]" key key))
1442 (org-ref-split-and-strip-string keyword) ","))
1449 (org-ref-split-and-strip-string keyword) ",") "]"))
1454 (format "<a href=\"#%s\">%s</a>" key key))
1455 (org-ref-split-and-strip-string keyword) ","))
1458 (if (string= (substring type -1) "s")
1459 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1460 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1461 (org-ref-split-and-strip-string keyword) ""))
1463 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1464 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1470 We create the links by mapping the function onto the list of defined link types.
1472 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1473 (defun org-ref-format-citation-description (desc)
1474 "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 ::."
1477 ((string-match "::" desc)
1478 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1479 (t (format "[%s]" desc))))
1481 (defun org-ref-define-citation-link (type &optional key)
1482 "add a citation link for org-ref. With optional key, set the reftex binding. For example:
1483 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1484 and the completion function."
1485 (interactive "sCitation Type: \ncKey: ")
1487 ;; create the formatting function
1488 (eval `(org-ref-make-format-function ,type))
1493 'org-ref-cite-onclick-minibuffer-menu
1494 (quote ,(intern (format "org-ref-format-%s" type)))))
1496 ;; create the completion function
1497 (eval `(org-ref-make-completion-function ,type))
1499 ;; store new type so it works with adding citations, which checks
1500 ;; for existence in this list
1501 (add-to-list 'org-ref-cite-types type)
1503 ;; and finally if a key is specified, we modify the reftex menu
1505 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1506 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1507 `((,key . ,(concat type ":%l")))))))
1509 ;; create all the link types and their completion functions
1510 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1513 *** org-ref-insert-cite-link
1514 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.
1516 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1517 (defun org-ref-insert-cite-link (alternative-cite)
1518 "Insert a default citation link using reftex. If you are on a link, it
1519 appends to the end of the link, otherwise, a new link is
1520 inserted. Use a prefix arg to get a menu of citation types."
1522 (org-ref-find-bibliography)
1523 (let* ((object (org-element-context))
1524 (link-string-beginning (org-element-property :begin object))
1525 (link-string-end (org-element-property :end object))
1526 (path (org-element-property :path object)))
1528 (if (not alternative-cite)
1531 ;; case where we are in a link
1532 ((and (equal (org-element-type object) 'link)
1533 (-contains? org-ref-cite-types (org-element-property :type object)))
1534 (goto-char link-string-end)
1535 ;; sometimes there are spaces at the end of the link
1536 ;; this code moves point pack until no spaces are there
1537 (while (looking-back " ") (backward-char))
1538 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1540 ;; We are next to a link, and we want to append
1543 (and (equal (org-element-type (org-element-context)) 'link)
1544 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1545 (while (looking-back " ") (backward-char))
1546 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1548 ;; insert fresh link
1551 (concat org-ref-default-citation-link
1553 (mapconcat 'identity (reftex-citation t) ",")))))
1555 ;; you pressed a C-u so we run this code
1561 : org-ref-insert-cite-link
1563 *** Completion in cite links
1564 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.
1566 #+BEGIN_SRC emacs-lisp :tangle no
1567 (defun org-cite-complete-link (&optional arg)
1568 "Completion function for cite links"
1570 org-ref-default-citation-link
1573 (let ((bibtex-files (org-ref-find-bibliography)))
1574 (bibtex-global-key-alist)))))
1577 Alternatively, you may shortcut the org-machinery with this command. You will be prompted for a citation type, and then offered key completion.
1579 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1580 (defun org-ref-insert-cite-with-completion (type)
1581 "Insert a cite link with completion"
1582 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1583 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1586 ** Storing links to a bibtex entry
1587 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.
1589 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1590 (defun org-ref-store-bibtex-entry-link ()
1591 "Save a citation link to the current bibtex entry. Saves in the default link type."
1593 (let ((link (concat org-ref-default-citation-link
1596 (bibtex-beginning-of-entry)
1597 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1598 (message "saved %s" link)
1599 (push (list link) org-stored-links)
1600 (car org-stored-links)))
1605 ** create simple text citation from bibtex entry
1607 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1608 (defun org-ref-bib-citation ()
1609 "from a bibtex entry, create and return a simple citation string."
1611 (bibtex-beginning-of-entry)
1612 (let* ((cb (current-buffer))
1613 (bibtex-expand-strings t)
1614 (entry (loop for (key . value) in (bibtex-parse-entry t)
1615 collect (cons (downcase key) value)))
1616 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1617 (year (reftex-get-bib-field "year" entry))
1618 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1619 (key (reftex-get-bib-field "=key=" entry))
1620 (journal (reftex-get-bib-field "journal" entry))
1621 (volume (reftex-get-bib-field "volume" entry))
1622 (pages (reftex-get-bib-field "pages" entry))
1623 (doi (reftex-get-bib-field "doi" entry))
1624 (url (reftex-get-bib-field "url" entry))
1626 ;;authors, "title", Journal, vol(iss):pages (year).
1627 (format "%s, \"%s\", %s, %s:%s (%s)"
1628 author title journal volume pages year)))
1632 : org-ref-bib-citation
1635 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1636 (defun org-ref-bib-html-citation ()
1637 "from a bibtex entry, create and return a simple citation with html links."
1639 (bibtex-beginning-of-entry)
1640 (let* ((cb (current-buffer))
1641 (bibtex-expand-strings t)
1642 (entry (loop for (key . value) in (bibtex-parse-entry t)
1643 collect (cons (downcase key) value)))
1644 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1645 (year (reftex-get-bib-field "year" entry))
1646 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1647 (key (reftex-get-bib-field "=key=" entry))
1648 (journal (reftex-get-bib-field "journal" entry))
1649 (volume (reftex-get-bib-field "volume" entry))
1650 (pages (reftex-get-bib-field "pages" entry))
1651 (doi (reftex-get-bib-field "doi" entry))
1652 (url (reftex-get-bib-field "url" entry))
1654 ;;authors, "title", Journal, vol(iss):pages (year).
1655 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
1656 author title journal volume pages year)
1657 (when url (format " <a href=\"%s\">link</a>" url))
1658 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
1662 ** open pdf from bibtex
1663 We bind this to a key here: [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1664 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1665 (defun org-ref-open-bibtex-pdf ()
1666 "open pdf for a bibtex entry, if it exists. assumes point is in
1667 the entry of interest in the bibfile. but does not check that."
1670 (bibtex-beginning-of-entry)
1671 (let* ((bibtex-expand-strings t)
1672 (entry (bibtex-parse-entry t))
1673 (key (reftex-get-bib-field "=key=" entry))
1674 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
1676 (if (file-exists-p pdf)
1677 (org-open-link-from-string (format "[[file:%s]]" pdf))
1681 ** open notes from bibtex
1682 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-notes ()
1686 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
1688 I never did figure out how to use reftex to make this happen
1689 non-interactively. the reftex-format-citation function did not
1690 work perfectly; there were carriage returns in the strings, and
1691 it did not put the key where it needed to be. so, below I replace
1692 the carriage returns and extra spaces with a single space and
1693 construct the heading by hand."
1696 (bibtex-beginning-of-entry)
1697 (let* ((cb (current-buffer))
1698 (bibtex-expand-strings t)
1699 (entry (loop for (key . value) in (bibtex-parse-entry t)
1700 collect (cons (downcase key) value)))
1701 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
1702 (year (reftex-get-bib-field "year" entry))
1703 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
1704 (key (reftex-get-bib-field "=key=" entry))
1705 (journal (reftex-get-bib-field "journal" entry))
1706 (volume (reftex-get-bib-field "volume" entry))
1707 (pages (reftex-get-bib-field "pages" entry))
1708 (doi (reftex-get-bib-field "doi" entry))
1709 (url (reftex-get-bib-field "url" entry))
1712 ;; save key to clipboard to make saving pdf later easier by pasting.
1715 (kill-ring-save (point-min) (point-max)))
1717 ;; now look for entry in the notes file
1718 (if org-ref-bibliography-notes
1719 (find-file org-ref-bibliography-notes)
1720 (error "org-ref-bib-bibliography-notes is not set to anything"))
1722 (goto-char (point-min))
1723 ;; put new entry in notes if we don't find it.
1724 (unless (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
1725 (insert (format "\n** TODO %s - %s" year title))
1737 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
1738 key author journal year volume pages doi url key org-ref-pdf-directory key))
1742 ** open url in browser from bibtex
1744 We bind this to a key here [[*key%20bindings%20for%20utilities][key bindings for utilities]].
1746 + 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.
1748 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1749 (defun org-ref-open-in-browser ()
1750 "Open the bibtex entry at point in a browser using the url field or doi field"
1753 (bibtex-beginning-of-entry)
1755 (let ((url (bibtex-autokey-get-field "url")))
1760 (let ((doi (bibtex-autokey-get-field "doi")))
1762 (if (string-match "^http" doi)
1764 (browse-url (format "http://dx.doi.org/%s" doi)))
1766 (message "No url or doi found"))))
1770 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.
1772 *** function to upload bibtex to citeulike
1774 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1775 (defun org-ref-upload-bibtex-entry-to-citeulike ()
1776 "with point in a bibtex entry get bibtex string and submit to citeulike.
1778 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
1780 (message "uploading to citeulike")
1782 (bibtex-narrow-to-entry)
1783 (let ((startpos (point-min))
1784 (endpos (point-max))
1785 (bibtex-string (buffer-string))
1786 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
1787 (with-temp-buffer (insert bibtex-string)
1788 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
1791 *** The upload script
1792 Here is the python script for uploading.
1794 *************** TODO document how to get the cookies
1798 #+BEGIN_SRC python :tangle upload_bibtex_citeulike.py
1800 import pickle, requests, sys
1803 with open('c:/Users/jkitchin/Dropbox/blogofile-jkitchin.github.com/_blog/cookies.pckl', 'rb') as f:
1804 cookies = pickle.load(f)
1806 url = 'http://www.citeulike.org/profile/jkitchin/import_do'
1808 bibtex = sys.stdin.read()
1810 data = {'pasted':bibtex,
1812 'tag_parsing':'simple',
1813 'strip_brackets':'no',
1814 'update_id':'bib-key',
1815 'btn_bibtex':'Import BibTeX file ...'}
1817 headers = {'content-type': 'multipart/form-data',
1818 'User-Agent':'jkitchin/johnrkitchin@gmail.com bibtexupload'}
1820 r = requests.post(url, headers=headers, data=data, cookies=cookies, files={})
1824 ** Build a pdf from a bibtex file
1825 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.
1827 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1828 (defun org-ref-build-full-bibliography ()
1829 "build pdf of all bibtex entries, and open it."
1831 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
1832 (bib-base (file-name-sans-extension bibfile))
1833 (texfile (concat bib-base ".tex"))
1834 (pdffile (concat bib-base ".pdf")))
1837 (insert (format "\\documentclass[12pt]{article}
1838 \\usepackage[version=3]{mhchem}
1840 \\usepackage[numbers]{natbib}
1841 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
1845 \\bibliographystyle{unsrtnat}
1847 \\end{document}" bib-base))
1849 (shell-command (concat "pdflatex " bib-base))
1850 (shell-command (concat "bibtex " bib-base))
1851 (shell-command (concat "pdflatex " bib-base))
1852 (shell-command (concat "pdflatex " bib-base))
1853 (kill-buffer texfile)
1854 (org-open-file pdffile)
1858 ** Extract bibtex entries cited in an org-file
1859 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.
1861 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1862 (defun org-ref-extract-bibtex-entries ()
1863 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
1865 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
1867 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
1868 (tempname (make-temp-file "extract-bib"))
1869 (contents (buffer-string))
1870 (cb (current-buffer))
1871 basename texfile bibfile results)
1873 ;; open tempfile and insert org-buffer contents
1874 (find-file tempname)
1876 (setq basename (file-name-sans-extension
1877 (file-name-nondirectory buffer-file-name))
1878 texfile (concat tempname ".tex")
1879 bibfile (concat tempname ".bib"))
1881 ;; see if we have a bibliography, and insert the default one if not.
1883 (goto-char (point-min))
1884 (unless (re-search-forward "^bibliography:" (point-max) 'end)
1885 (insert (format "\nbibliography:%s"
1886 (mapconcat 'identity reftex-default-bibliography ",")))))
1889 ;; get a latex file and extract the references
1890 (org-latex-export-to-latex)
1893 (reftex-create-bibtex-file bibfile)
1895 ;; save results of the references
1896 (setq results (buffer-string))
1898 ;; kill buffers. these are named by basename, not full path
1899 (kill-buffer (concat basename ".bib"))
1900 (kill-buffer (concat basename ".tex"))
1901 (kill-buffer basename)
1903 (delete-file bibfile)
1904 (delete-file texfile)
1905 (delete-file tempname)
1907 ;; Now back to the original org buffer and insert the results
1908 (switch-to-buffer cb)
1909 (when (not (string= "" results))
1911 (goto-char (point-max))
1913 (org-insert-heading)
1914 (insert (format " Bibtex entries
1916 ,#+BEGIN_SRC text :tangle %s
1918 ,#+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
1921 ** Find bad cite links
1922 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.
1924 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1927 (defun index (substring list)
1928 "return the index of string in a list of strings"
1931 (dolist (arg list i)
1932 (if (string-match (concat "^" substring "$") arg)
1937 ;; return counter if found, otherwise return nil
1941 (defun org-ref-find-bad-citations ()
1942 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
1944 Makes a new buffer with clickable links."
1946 ;; generate the list of bibtex-keys and cited keys
1947 (let* ((bibtex-files (org-ref-find-bibliography))
1948 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
1949 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
1950 (bad-citations '()))
1952 (org-element-map (org-element-parse-buffer) 'link
1954 (let ((plist (nth 1 link)))
1955 (when (equal (plist-get plist ':type) "cite")
1956 (dolist (key (org-ref-split-and-strip-string (plist-get plist ':path)) )
1957 (when (not (index key bibtex-keys))
1958 (setq bad-citations (append bad-citations
1959 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
1960 key (buffer-name)(plist-get plist ':begin)))))
1965 (switch-to-buffer-other-window "*Missing citations*")
1968 (insert "* List of bad cite links\n")
1969 (insert (mapconcat 'identity bad-citations ""))
1970 ;(setq buffer-read-only t)
1971 (use-local-map (copy-keymap org-mode-map))
1972 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
1974 (when (get-buffer "*Missing citations*")
1975 (kill-buffer "*Missing citations*"))
1976 (message "No bad cite links found"))))
1979 ** Finding non-ascii characters
1980 I like my bibtex files to be 100% ascii. This function finds the non-ascii characters so you can replace them.
1982 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1983 (defun org-ref-find-non-ascii-characters ()
1984 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
1986 (occur "[^[:ascii:]]"))
1989 ** Resort a bibtex entry
1990 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.
1992 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
1993 (defun org-ref-sort-bibtex-entry ()
1994 "sort fields of entry in standard order and downcase them"
1996 (bibtex-beginning-of-entry)
1997 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
1998 (entry (bibtex-parse-entry))
2001 (type (cdr (assoc "=type=" entry)))
2002 (key (cdr (assoc "=key=" entry))))
2004 ;; these are the fields we want to order that are in this entry
2005 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2006 ;; we do not want to reenter these fields
2007 (setq entry-fields (remove "=key=" entry-fields))
2008 (setq entry-fields (remove "=type=" entry-fields))
2010 ;;these are the other fields in the entry
2011 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2014 ;; right now we only resort articles
2015 ((string= (downcase type) "article")
2018 (concat "@article{" key ",\n"
2021 (when (member field entry-fields)
2022 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2025 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2027 (bibtex-find-entry key)
2029 (bibtex-clean-entry)
2033 ** Clean a bibtex entry
2034 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.
2035 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.
2036 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2037 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2038 "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"
2040 (bibtex-beginning-of-entry)
2042 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2043 (unless (string-match ",$" (thing-at-point 'line))
2047 ;; check for empty pages, and put eid or article id in its place
2048 (let ((entry (bibtex-parse-entry))
2049 (pages (bibtex-autokey-get-field "pages"))
2050 (year (bibtex-autokey-get-field "year"))
2051 (doi (bibtex-autokey-get-field "doi"))
2052 ;; The Journal of Chemical Physics uses eid
2053 (eid (bibtex-autokey-get-field "eid")))
2055 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2056 ;; but we only want the doi.
2057 (when (string-match "^http://dx.doi.org/" doi)
2058 (bibtex-beginning-of-entry)
2059 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2061 (bibtex-make-field "doi")
2063 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2065 ;; asap articles often set year to 0, which messes up key
2066 ;; generation. fix that.
2067 (when (string= "0" year)
2068 (bibtex-beginning-of-entry)
2069 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2071 (bibtex-make-field "year")
2073 (insert (read-string "Enter year: ")))
2075 ;; fix pages if they are empty if there is an eid to put there.
2076 (when (string= "-" pages)
2078 (bibtex-beginning-of-entry)
2079 ;; this seems like a clunky way to set the pages field.But I
2080 ;; cannot find a better way.
2081 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2083 (bibtex-make-field "pages")
2087 ;; replace naked & with \&
2089 (bibtex-narrow-to-entry)
2090 (bibtex-beginning-of-entry)
2091 (message "checking &")
2092 (replace-regexp " & " " \\\\& ")
2095 ;; generate a key, and if it duplicates an existing key, edit it.
2097 (let ((key (bibtex-generate-autokey)))
2099 ;; first we delete the existing key
2100 (bibtex-beginning-of-entry)
2101 (re-search-forward bibtex-entry-maybe-empty-head)
2102 (if (match-beginning bibtex-key-in-head)
2103 (delete-region (match-beginning bibtex-key-in-head)
2104 (match-end bibtex-key-in-head)))
2105 ;; check if the key is in the buffer
2106 (when (save-excursion
2107 (bibtex-search-entry key))
2109 (bibtex-search-entry key)
2110 (bibtex-copy-entry-as-kill)
2111 (switch-to-buffer-other-window "*duplicate entry*")
2113 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2116 (kill-new key))) ;; save key for pasting
2118 ;; run hooks. each of these operates on the entry with no arguments.
2119 ;; this did not work like i thought, it gives a symbolp error.
2120 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2125 org-ref-clean-bibtex-entry-hook)
2127 ;; sort fields within entry
2128 (org-ref-sort-bibtex-entry)
2129 ;; check for non-ascii characters
2130 (occur "[^[:ascii:]]")
2135 : org-ref-clean-bibtex-entry
2137 ** Sort the entries in a citation link by year
2138 I prefer citations in chronological order within a grouping. These functions sort the link under the cursor by year.
2140 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2141 (defun org-ref-get-citation-year (key)
2142 "get the year of an entry with key. Returns year as a string."
2144 (let* ((results (org-ref-get-bibtex-key-and-file key))
2145 (bibfile (cdr results)))
2147 (insert-file-contents bibfile)
2148 (bibtex-search-entry key nil 0)
2149 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2152 (defun org-ref-sort-citation-link ()
2153 "replace link at point with sorted link by year"
2155 (let* ((object (org-element-context))
2156 (type (org-element-property :type object))
2157 (begin (org-element-property :begin object))
2158 (end (org-element-property :end object))
2159 (link-string (org-element-property :path object))
2161 (setq keys (org-ref-split-and-strip-string link-string))
2162 (setq years (mapcar 'org-ref-get-citation-year keys))
2163 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2164 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2165 ;; now get the keys separated by commas
2166 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2167 ;; and replace the link with the sorted keys
2168 (cl--set-buffer-substring begin end (concat type ":" keys))))
2171 ** Sort entries in citation links with shift-arrow keys
2172 Sometimes it may be helpful to manually change the order of citations. These functions define shift-arrow functions.
2173 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2174 (defun org-ref-swap-keys (i j keys)
2175 "swap the keys in a list with index i and j"
2176 (let ((tempi (nth i keys)))
2177 (setf (nth i keys) (nth j keys))
2178 (setf (nth j keys) tempi))
2181 (defun org-ref-swap-citation-link (direction)
2182 "move citation at point in direction +1 is to the right, -1 to the left"
2184 (let* ((object (org-element-context))
2185 (type (org-element-property :type object))
2186 (begin (org-element-property :begin object))
2187 (end (org-element-property :end object))
2188 (link-string (org-element-property :path object))
2190 ;; We only want this to work on citation links
2191 (when (-contains? org-ref-cite-types type)
2192 (setq key (org-ref-get-bibtex-key-under-cursor))
2193 (setq keys (org-ref-split-and-strip-string link-string))
2194 (setq i (index key keys)) ;; defined in org-ref
2195 (if (> direction 0) ;; shift right
2196 (org-ref-swap-keys i (+ i 1) keys)
2197 (org-ref-swap-keys i (- i 1) keys))
2198 (setq keys (mapconcat 'identity keys ","))
2199 ;; and replace the link with the sorted keys
2200 (cl--set-buffer-substring begin end (concat type ":" keys))
2201 ;; now go forward to key so we can move with the key
2202 (re-search-forward key)
2203 (goto-char (match-beginning 0)))))
2205 ;; add hooks to make it work
2206 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2207 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2210 I like convenience. Here are some aliases for faster typing.
2212 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2213 (defalias 'oro 'org-ref-open-citation-at-point)
2214 (defalias 'orc 'org-ref-citation-at-point)
2215 (defalias 'orp 'org-ref-open-pdf-at-point)
2216 (defalias 'oru 'org-ref-open-url-at-point)
2217 (defalias 'orn 'org-ref-open-notes-at-point)
2219 (defalias 'orib 'org-ref-insert-bibliography-link)
2220 (defalias 'oric 'org-ref-insert-cite-link)
2221 (defalias 'orir 'org-ref-insert-ref-link)
2222 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2224 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2227 #+BEGIN_SRC emacs-lisp :tangle org-ref.el
2234 [[elisp:(progn (org-babel-tangle) (load-file "org-ref.el"))]]
2236 [[elisp:(org-babel-load-file "org-ref.org")]]