1 ;;; org-ref.el --- cite and cross-reference in org-mode
3 ;; Copyright(C) 2014 John Kitchin
5 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
6 ;; URL: https://github.com/jkitchin/org-ref
8 ;; Keywords: org-mode, cite, ref, label
9 ;; Package-Requires: ((org) (dash) (helm) (helm-bibtex) (hydra))
11 ;; This file is not currently part of GNU Emacs.
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License as
15 ;; published by the Free Software Foundation; either version 2, or (at
16 ;; your option) any later version.
18 ;; This program is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 ;; General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program ; see the file COPYING. If not, write to
25 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
30 ;; Lisp code to setup bibliography cite, ref and label org-mode links.
31 ;; also sets up reftex and helm for org-mode citations. The links are
32 ;; clickable and do things that are useful. You should really read
33 ;; org-ref.org for details.
38 (require 'reftex-cite)
41 (require 'helm-config)
42 (require 'helm-bibtex)
47 "Customization group for org-ref.")
49 (defcustom org-ref-bibliography-notes
51 "Filename where you will put all your notes about an entry in the default bibliography."
55 (defcustom org-ref-default-bibliography
57 "List of bibtex files to search for.
58 You should use full-paths for each file."
59 :type '(repeat :tag "List of bibtex files" file)
62 (defcustom org-ref-pdf-directory
64 "Directory where pdfs are stored by key. put a trailing / in."
68 (defcustom org-ref-default-citation-link
70 "The default type of citation link to use."
74 (defcustom org-ref-insert-cite-key
76 "Keyboard shortcut to insert a citation."
80 (defcustom org-ref-bibliography-entry-format
81 '(("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>.")
83 ("book" . "%a, %t, %u (%y).")
85 ("proceedings" . "%e, %t in %S, %u (%y).")
87 ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
89 "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."
93 (defcustom org-ref-open-notes-function
99 ;;(org-tree-to-indirect-buffer)
100 (outline-previous-visible-heading 1)
101 (recenter-top-bottom 0))
102 "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."
107 (defcustom org-ref-open-pdf-function
108 'org-ref-open-pdf-at-point
109 "User-defined function to open a pdf from a link. The function must get the key at point, and derive a path to the pdf file, then open it. The default function is `org-ref-open-pdf-at-point'."
114 (defcustom org-ref-insert-cite-function
115 'org-ref-helm-insert-cite-link
116 "Function to call to insert citation links. The default is `org-ref-helm-insert-cite-link' which uses `helm-bibtex'. `org-ref' modifies `helm-bibtex' a little bit to give `org-mode' citations, and to reorder default actions. You may use `org-ref-insert-cite-link' if you like the reftex interface."
121 (defcustom org-ref-cite-onclick-function
122 'org-ref-cite-click-helm
123 "Function that runs when you click on a cite link. The function must take no arguments. You may also use `org-ref-cite-onclick-minibuffer-menu' if you do not like helm. If you like `hydra', consider using `org-ref-cite-hydra'."
128 (defcustom org-ref-show-citation-on-enter t
129 "If non-nil add a hook function to show the citation summary in the minibuffer."
132 (defcustom org-ref-cite-types
133 '("cite" "nocite" ;; the default latex cite commands
134 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
135 "citet" "citet*" "citep" "citep*"
136 "citealt" "citealt*" "citealp" "citealp*"
138 "citeauthor" "citeauthor*"
139 "citeyear" "citeyear*"
140 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
142 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
144 "parencite" "Parencite"
145 "footcite" "footcitetext"
146 "textcite" "Textcite"
147 "smartcite" "Smartcite"
148 "cite*" "parencite*" "supercite"
149 "autocite" "Autocite" "autocite*" "Autocite*"
151 "citetitle" "citetitle*"
152 "citedate" "citedate*"
154 "fullcite" "footfullcite"
155 ;; "volcite" "Volcite" cannot support the syntax
156 "notecite" "Notecite"
157 "pnotecite" "Pnotecite"
159 ;; multicites. Very limited support for these.
160 "cites" "Cites" "parencites" "Parencites"
161 "footcites" "footcitetexts"
162 "smartcites" "Smartcites" "textcites" "Textcites"
163 "supercites" "autocites" "Autocites"
164 ;; for the bibentry package
167 "List of citation types known in `org-ref'."
168 :type '(repeat :tag "List of citation types" string)
171 (defcustom org-ref-clean-bibtex-entry-hook nil
172 "Hook that is run in `org-ref-clean-bibtex-entry'. The functions should take no arguments, and operate on the bibtex entry at point."
176 (defvar org-ref-bibliography-files
178 "Variable to hold bibliography files to be searched.")
180 ;; * org-mode / reftex setup
182 (defun org-mode-reftex-setup ()
183 "Setup `org-mode' and reftex for org-ref."
184 (and (buffer-file-name)
185 (file-exists-p (buffer-file-name))
186 (global-auto-revert-mode t))
187 (make-local-variable 'reftex-cite-format)
188 (setq reftex-cite-format 'org))
190 ;; define key for inserting citations
191 (define-key org-mode-map
192 (kbd org-ref-insert-cite-key)
193 org-ref-insert-cite-function)
195 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
197 (eval-after-load 'reftex-vars
199 (add-to-list 'reftex-cite-format-builtin
200 '(org "Org-mode citation"
201 ((?\C-m . "cite:%l") ; default
202 (?d . ",%l") ; for appending
208 (?h . "citeauthor:%l")
209 (?H . "citeauthor*:%l")
215 ;; * Messages for link at cursor
216 (defvar org-ref-message-timer nil
217 "Variable to store the link message timer in.")
220 (defun org-ref-show-link-messages ()
221 "Turn on link messages.
222 You will see a message in the minibuffer when on a cite, ref or label link."
224 (or org-ref-message-timer
225 (setq org-ref-message-timer
226 (run-with-idle-timer 0.5 t 'org-ref-link-message))))
229 (defun org-ref-cancel-link-messages ()
230 "Stop showing messages in minibuffer when on a link."
232 (cancel-timer org-ref-message-timer)
233 (setq org-ref-message-timer nil))
236 (when org-ref-show-citation-on-enter
237 (org-ref-show-link-messages))
239 ;; ** Messages for context under mouse pointer
241 (defvar org-ref-last-mouse-pos nil
242 "Stores last mouse position for use in `org-ref-mouse-message'.")
244 (defun org-ref-can-move-p ()
245 "See if a character is under the mouse. If so return the position for `goto-char'."
246 (let* ((line (cddr org-ref-last-mouse-pos))
247 (col (cadr org-ref-last-mouse-pos)))
249 (goto-char (window-start))
252 (> (- (line-end-position) (line-beginning-position)) col)
253 (progn (forward-char col) (point))
257 (defun org-ref-mouse-message ()
258 "Display message for link under mouse cursor."
260 (when (not (equal (mouse-position) org-ref-last-mouse-pos))
261 (setq org-ref-last-mouse-pos (mouse-position))
262 (let ((p (org-ref-can-move-p)))
266 (org-ref-link-message))))))
269 (defvar org-ref-message-timer-mouse nil
270 "Store mouse timer.")
273 (defvar org-ref-mouse-message-interval 0.5
274 "How often to run the mouse message timer in seconds.")
277 (defun org-ref-mouse-messages-on ()
278 "Turn on mouse messages."
280 (or org-ref-message-timer-mouse
281 (setq org-ref-message-timer-mouse
282 (run-at-time "0.5 sec"
283 org-ref-mouse-message-interval
284 'org-ref-mouse-message))))
287 (defun org-ref-mouse-messages-off ()
288 "Turn off mouse messages."
290 (cancel-timer org-ref-message-timer-mouse)
291 (setq org-ref-message-timer-mouse nil)
292 (message "Mouse messages are off"))
294 ;; Colorizing org-ref links
295 (defcustom org-ref-colorize-links
297 "When non-nil, change colors of links."
301 (defcustom org-ref-cite-color
303 "Color of cite like links."
307 (defcustom org-ref-ref-color
309 "Color of ref like links."
313 (defcustom org-ref-label-color
315 "Color of label links."
319 (defvar org-ref-cite-re nil
320 "Regexp for cite links.")
323 (setq org-ref-cite-re
324 (concat "\\(" (mapconcat
326 (replace-regexp-in-string "\*" "\\\\*" x)
328 org-ref-cite-types "\\|") "\\)"
329 ":\\([a-zA-Z0-9-_:\\./]*,?\\)*"))
332 (setq org-ref-label-re
333 "label:\\([a-zA-Z0-9-_:]*,?\\)*")
337 "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
340 (defface org-ref-cite-face
341 `((t (:inherit org-link :foreground ,org-ref-cite-color)))
342 "Color for cite-like links in org-ref.")
345 (defface org-ref-label-face
346 `((t (:inherit org-link :foreground ,org-ref-label-color)))
347 "Color for ref links in org-ref.")
350 (defface org-ref-ref-face
351 `((t (:inherit org-link :foreground ,org-ref-ref-color)))
352 "Face for ref links in org-ref.")
355 (defun org-ref-colorize-links ()
356 "Colorize org-ref links."
358 (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
359 (highlight-regexp org-ref-label-re 'org-ref-label-face)
360 (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
363 (when org-ref-colorize-links
364 (add-hook 'org-mode-hook 'org-ref-colorize-links))
366 ;; * General org-ref utilities
367 (defun org-ref-strip-string (string)
368 "Strip leading and trailing whitespace from the STRING."
369 (replace-regexp-in-string
370 (concat search-whitespace-regexp "$" ) ""
371 (replace-regexp-in-string
372 (concat "^" search-whitespace-regexp ) "" string)))
374 (defun org-ref-split-and-strip-string (string)
375 "Split key-string and strip keys in STRING.
376 Assumes the key-string is comma delimited."
377 (mapcar 'org-ref-strip-string (split-string string ",")))
379 (defun org-ref-reftex-get-bib-field (field entry &optional format)
380 "Similar to reftex-get-bib-field, but removes enclosing braces and quotes in FIELD in the bibtex ENTRY.
381 Optional argument FORMAT bibtex format."
383 (setq result (reftex-get-bib-field field entry format))
384 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
385 (setq result (substring result 1 -1)))
386 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
387 (setq result (substring result 1 -1)))
390 (defun org-ref-reftex-format-citation (entry format)
391 "Return a formatted string for the bibtex ENTRY (from bibtex-parse-entry) according to the FORMAT argument.
392 The format is a string with these percent escapes.
394 In the format, the following percent escapes will be expanded.
396 %l The BibTeX label of the citation.
397 %a List of author names, see also `reftex-cite-punctuation'.
398 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
399 %A First author name only.
400 %e Works like %a, but on list of editor names. (%2e and %E work a well)
402 It is also possible to access all other BibTeX database fields:
403 %b booktitle %c chapter %d edition %h howpublished
404 %i institution %j journal %k key %m month
405 %n number %o organization %p pages %P first page
406 %r address %s school %u publisher %t title
408 %B booktitle, abbreviated %T title, abbreviated
413 Usually, only %l is needed. The other stuff is mainly for the echo area
414 display, and for (setq reftex-comment-citations t).
416 %< as a special operator kills punctuation and space around it after the
417 string has been formatted.
419 A pair of square brackets indicates an optional argument, and RefTeX
420 will prompt for the values of these arguments.
422 Beware that all this only works with BibTeX database files. When
423 citations are made from the \bibitems in an explicit thebibliography
424 environment, only %l is available."
425 ;; Format a citation from the info in the BibTeX ENTRY
427 (unless (stringp format) (setq format "\\cite{%l}"))
429 (if (and reftex-comment-citations
430 (string-match "%l" reftex-cite-comment-format))
431 (error "Reftex-cite-comment-format contains invalid %%l"))
434 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
436 (let ((n (string-to-number (match-string 4 format)))
437 (l (string-to-char (match-string 5 format)))
443 (org-ref-reftex-get-bib-field "&key" entry)
444 (if reftex-comment-citations
445 reftex-cite-comment-format
447 ((= l ?a) (reftex-format-names
448 (reftex-get-bib-names "author" entry)
450 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
451 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
452 ((= l ?B) (reftex-abbreviate-title
453 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
454 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
455 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
456 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
457 ((= l ?e) (reftex-format-names
458 (reftex-get-bib-names "editor" entry)
460 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
461 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
462 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
463 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
464 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
465 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
466 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
467 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
468 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
469 ((= l ?P) (car (split-string
470 (org-ref-reftex-get-bib-field "pages" entry)
472 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
473 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
474 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
475 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
476 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
477 ;; strip enclosing brackets from title if they are there
478 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
479 ((= l ?T) (reftex-abbreviate-title
480 (org-ref-reftex-get-bib-field "title" entry)))
481 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
482 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
485 (setq b (match-beginning 2) e (match-end 2))
486 (setq b (match-beginning 3) e (match-end 3)))
487 (setq format (concat (substring format 0 b) rpl (substring format e)))))
488 (while (string-match "%%" format)
489 (setq format (replace-match "%" t t format)))
490 (while (string-match "[ ,.;:]*%<" format)
491 (setq format (replace-match "" t t format)))
492 ;; also replace carriage returns, tabs, and multiple whitespaces
493 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
496 (defun org-ref-get-bibtex-entry-citation (key)
497 "Return a string for the bibliography entry corresponding to KEY.
498 Format according to the type in `org-ref-bibliography-entry-format'."
500 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
501 (file) (entry) (bibtex-entry) (entry-type) (format))
503 (setq file (catch 'result
504 (loop for file in org-ref-bibliography-files do
505 (if (org-ref-key-in-file-p key (file-truename file))
507 (message "%s not found in %s"
508 key (file-truename file))))))
511 (insert-file-contents file)
512 (bibtex-search-entry key nil 0)
513 (setq bibtex-entry (bibtex-parse-entry))
514 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
515 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
517 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
519 (bibtex-narrow-to-entry)
520 (setq entry (buffer-string)))))
523 (defun org-ref-get-bibtex-keys ()
524 "Return a list of unique keys in the buffer."
526 (org-element-map (org-element-parse-buffer) 'link
528 (let ((plist (nth 1 link)))
529 (when (-contains? org-ref-cite-types (plist-get plist ':type))
532 (org-ref-split-and-strip-string (plist-get plist ':path)))
533 (when (not (-contains? keys key))
534 (setq keys (append keys (list key))))))))
535 ;; set with-affiliated to get keys in captions
537 ;; Sort keys alphabetically
538 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
541 (defun org-ref-get-bibtex-entry-html (key)
542 "Return an html string for the bibliography entry corresponding to KEY."
544 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
546 (defun org-ref-get-html-bibliography ()
547 "Create an html bibliography when there are keys."
548 (let ((keys (org-ref-get-bibtex-keys)))
550 (concat "<h1>Bibliography</h1>
552 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
555 (defun org-ref-get-bibtex-entry-org (key)
556 "Return an org string for the bibliography entry corresponding to KEY."
557 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
558 (file) (entry) (bibtex-entry) (entry-type) (format))
560 (setq file (catch 'result
561 (loop for file in org-ref-bibliography-files do
562 (if (org-ref-key-in-file-p key (file-truename file))
564 (message "%s not found in %s" key (file-truename file))))))
567 (insert-file-contents file)
568 (bibtex-search-entry key nil 0)
569 (setq entry (bibtex-parse-entry))
574 " (org-ref-reftex-get-bib-field "author" entry)
575 (org-ref-reftex-get-bib-field "title" entry)
576 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
577 (mapconcat (lambda (element) (format " :%s: %s"
578 (upcase (car element))
583 (defun org-ref-get-org-bibliography ()
584 "Create an org bibliography when there are keys."
585 (let ((keys (org-ref-get-bibtex-keys)))
587 (concat "* Bibliography
589 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
592 (defun org-ref-get-bibtex-entry-ascii (key)
593 "Return an ascii string for the bibliography entry corresponding to KEY."
595 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
597 (defun org-ref-get-ascii-bibliography ()
598 "Create an html bibliography when there are keys."
599 (let ((keys (org-ref-get-bibtex-keys)))
605 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
609 ;; ** bibliography and bibliographystyle
610 (org-add-link-type "bibliography"
611 ;; this code is run on clicking. The bibliography
612 ;; may contain multiple files. this code finds the
613 ;; one you clicked on and opens it.
614 (lambda (link-string)
615 ;; get link-string boundaries we have to go to the
616 ;; beginning of the line, and then search forward
618 ;; object is the link you clicked on
619 (object (org-element-context))
620 (link-string-beginning)
624 (goto-char (org-element-property :begin object))
625 (search-forward link-string nil nil 1)
626 (setq link-string-beginning (match-beginning 0))
627 (setq link-string-end (match-end 0)))
629 (if (< cp link-string-beginning)
630 (goto-char link-string-beginning))
631 ;; We set the reftex-default-bibliography
632 ;; here. it should be a local variable only in
633 ;; the current buffer. We need this for using
634 ;; reftex to do citations.
635 (set (make-local-variable 'reftex-default-bibliography)
637 (org-element-property :path object) ","))
639 ;; now if we have comma separated bibliographies
640 ;; we find the one clicked on. we want to
641 ;; search forward to next comma from point
643 (if (search-forward "," link-string-end 1 1)
645 (setq key-end (- (match-end 0) 1))
646 ;; no comma found so take the point
647 (setq key-end (point))))
648 ;; and backward to previous comma from point
650 (if (search-backward "," link-string-beginning 1 1)
652 (setq key-beginning (+ (match-beginning 0) 1))
653 (setq key-beginning (point)))) ; no match found
654 ;; save the key we clicked on.
655 (setq bibfile (org-ref-strip-string
656 (buffer-substring key-beginning key-end)))
657 ;; open file on click
658 (find-file bibfile)))
661 (lambda (keyword desc format)
663 ((eq format 'org) (org-ref-get-org-bibliography))
664 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
665 ((eq format 'html) (org-ref-get-html-bibliography))
667 ;; write out the latex bibliography command
668 (format "\\bibliography{%s}"
669 (replace-regexp-in-string
673 (mapcar 'expand-file-name
674 (split-string keyword ","))
677 (org-add-link-type "nobibliography"
678 ;; this code is run on clicking. The bibliography
679 ;; may contain multiple files. this code finds the
680 ;; one you clicked on and opens it.
681 (lambda (link-string)
682 ;; get link-string boundaries
683 ;; we have to go to the beginning of the line, and then search forward
686 ;; object is the link you clicked on
687 (object (org-element-context))
689 (link-string-beginning)
693 (goto-char (org-element-property :begin object))
694 (search-forward link-string nil nil 1)
695 (setq link-string-beginning (match-beginning 0))
696 (setq link-string-end (match-end 0)))
698 ;; We set the reftex-default-bibliography
699 ;; here. it should be a local variable only in
700 ;; the current buffer. We need this for using
701 ;; reftex to do citations.
702 (set (make-local-variable 'reftex-default-bibliography)
703 (split-string (org-element-property :path object) ","))
705 ;; now if we have comma separated bibliographies
706 ;; we find the one clicked on. we want to
707 ;; search forward to next comma from point
709 (if (search-forward "," link-string-end 1 1)
710 (setq key-end (- (match-end 0) 1)) ; we found a match
711 (setq key-end (point)))) ; no comma found so take the point
712 ;; and backward to previous comma from point
714 (if (search-backward "," link-string-beginning 1 1)
715 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
716 (setq key-beginning (point)))) ; no match found
717 ;; save the key we clicked on.
718 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
719 (find-file bibfile))) ; open file on click
722 (lambda (keyword desc format)
724 ((eq format 'org) (org-ref-get-org-bibliography))
725 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
726 ((eq format 'html) (org-ref-get-html-bibliography))
728 ;; write out the latex bibliography command
730 ; (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
731 ; (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
732 ; (mapcar 'expand-file-name
733 ; (split-string keyword ","))
736 (format "\\nobibliography{%s}"
737 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
738 (mapcar 'expand-file-name
739 (split-string keyword ","))
744 (org-add-link-type "printbibliography"
745 (lambda (arg) (message "Nothing implemented for clicking here."))
746 (lambda (keyword desc format)
748 ((eq format 'org) (org-ref-get-org-bibliography))
749 ((eq format 'html) (org-ref-get-html-bibliography))
751 ;; write out the biblatex bibliography command
752 "\\printbibliography"))
755 (org-add-link-type "bibliographystyle"
756 (lambda (arg) (message "Nothing implemented for clicking here."))
757 (lambda (keyword desc format)
760 ;; write out the latex bibliography command
761 (format "\\bibliographystyle{%s}" keyword)))))
764 (defun org-bibliographystyle-complete-link (&optional arg)
765 "Completion function for bibliographystyle link.
767 (format "bibliographystyle:%s" (ido-completing-read
769 '("unsrt" "plain" "alpha"
771 ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
772 "dinat" "humannat" "plainnat"
773 "abbrnat" "unsrtnat" "rusnat"
777 (defun org-bibliography-complete-link (&optional arg)
778 "Completion function for bibliography link.
780 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
783 (defun org-ref-insert-bibliography-link ()
784 "Insert a bibliography with completion."
786 (insert (org-bibliography-complete-link)))
790 (org-add-link-type "addbibresource"
791 ;; this code is run on clicking. The addbibresource
792 ;; may contain multiple files. this code finds the
793 ;; one you clicked on and opens it.
794 (lambda (link-string)
795 ;; get link-string boundaries
796 ;; we have to go to the beginning of the line, and then search forward
799 ;; object is the link you clicked on
800 (object (org-element-context))
802 (link-string-beginning)
806 (goto-char (org-element-property :begin object))
807 (search-forward link-string nil nil 1)
808 (setq link-string-beginning (match-beginning 0))
809 (setq link-string-end (match-end 0)))
811 ;; We set the reftex-default-addbibresource
812 ;; here. it should be a local variable only in
813 ;; the current buffer. We need this for using
814 ;; reftex to do citations.
815 (set (make-local-variable 'reftex-default-addbibresource)
816 (split-string (org-element-property :path object) ","))
818 ;; now if we have comma separated bibliographies
819 ;; we find the one clicked on. we want to
820 ;; search forward to next comma from point
822 (if (search-forward "," link-string-end 1 1)
823 (setq key-end (- (match-end 0) 1)) ; we found a match
824 (setq key-end (point)))) ; no comma found so take the point
825 ;; and backward to previous comma from point
827 (if (search-backward "," link-string-beginning 1 1)
828 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
829 (setq key-beginning (point)))) ; no match found
830 ;; save the key we clicked on.
831 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
832 (find-file bibfile))) ; open file on click
835 (lambda (keyword desc format)
837 ((eq format 'html) (format "")); no output for html
839 ;; write out the latex addbibresource command
840 (format "\\addbibresource{%s}" keyword)))))
842 ;; ** List of figures
843 (defun org-ref-list-of-figures (&optional arg)
844 "Generate buffer with list of figures in them.
847 (save-excursion (widen)
848 (let* ((c-b (buffer-name))
851 (org-element-map (org-element-parse-buffer) 'link
853 "create a link for to the figure"
855 (and (string= (org-element-property :type link) "file")
857 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
858 (org-element-property :path link)))
861 (let* ((start (org-element-property :begin link))
862 (parent (car (cdr (org-element-property :parent link))))
863 (caption (caaar (plist-get parent :caption)))
864 (name (plist-get parent :name)))
867 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
868 c-b start counter (or name "") caption)
870 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
871 c-b start counter (or name "")))))))))
872 (switch-to-buffer "*List of Figures*")
873 (setq buffer-read-only nil)
876 (insert (mapconcat 'identity list-of-figures ""))
877 (setq buffer-read-only t)
878 (use-local-map (copy-keymap org-mode-map))
879 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
883 'org-ref-list-of-figures ; on click
884 (lambda (keyword desc format)
887 (format "\\listoffigures")))))
890 (defun org-ref-list-of-tables (&optional arg)
891 "Generate a buffer with a list of tables.
896 (let* ((c-b (buffer-name))
899 (org-element-map (org-element-parse-buffer 'element) 'table
901 "create a link for to the table"
903 (let ((start (org-element-property :begin table))
904 (name (org-element-property :name table))
905 (caption (caaar (org-element-property :caption table))))
908 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
909 c-b start counter (or name "") caption)
911 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
912 c-b start counter (or name ""))))))))
913 (switch-to-buffer "*List of Tables*")
914 (setq buffer-read-only nil)
917 (insert (mapconcat 'identity list-of-tables ""))
918 (setq buffer-read-only t)
919 (use-local-map (copy-keymap org-mode-map))
920 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
924 'org-ref-list-of-tables
925 (lambda (keyword desc format)
928 (format "\\listoftables")))))
932 (defun org-ref-count-labels (label)
933 "Counts number of matches for LABEL in the document."
934 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
935 ;; for tblname, it is not enough to get word boundary
936 ;; tab-little and tab-little-2 match then.
937 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
938 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
939 ;; this is the org-format #+label:
940 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
941 (let ((custom-id-count 0))
944 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
945 (setq custom-id-count (+ 1 custom-id-count)))))
951 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
952 (let ((count (org-ref-count-labels label)))
953 (message (format "%s occurence%s"
959 (org-ref-count-labels label))))
960 (lambda (keyword desc format)
962 ((eq format 'html) (format "(<label>%s</label>)" path))
964 (format "\\label{%s}" keyword)))))
966 (defun org-label-store-link ()
967 "Store a link to a label. The output will be a ref to that label."
968 ;; First we have to make sure we are on a label link.
969 (let* ((object (org-element-context)))
970 (when (and (equal (org-element-type object) 'link)
971 (equal (org-element-property :type object) "label"))
972 (org-store-link-props
974 :link (concat "ref:" (org-element-property :path object))))
976 ;; Store link on table
977 (when (equal (org-element-type object) 'table)
978 (org-store-link-props
980 :link (concat "ref:" (org-element-property :name object))))
982 ;; store link on heading with custom_id
983 ;; this is not a ref link, but it is still what you want
984 (when (and (equal (org-element-type object) 'headline)
985 (org-entry-get (point) "CUSTOM_ID"))
986 (org-store-link-props
988 :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
990 ;; and to #+label: lines
992 (when (and (equal (org-element-type object) 'paragraph)
993 (org-element-property :name object))
994 (org-store-link-props
996 :link (concat "ref:" (org-element-property :name object))))))
998 (add-hook 'org-store-link-functions 'org-label-store-link)
1004 "on clicking goto the label. Navigate back with C-c &"
1005 (org-mark-ring-push)
1006 ;; next search from beginning of the buffer
1007 ;; it is possible you would not find the label if narrowing is in effect
1013 (goto-char (point-min))
1014 (re-search-forward (format "label:%s\\b" label) nil t))
1018 (goto-char (point-min))
1019 (re-search-forward (format "\\label{%s}" label) nil t))
1021 ;; #+label: name org-definition
1023 (goto-char (point-min))
1025 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1029 (goto-char (point-min))
1031 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1033 ;; we did not find anything, so go back to where we came
1034 (org-mark-ring-goto)
1035 (error "%s not found" label))
1037 (message "go back with (org-mark-ring-goto) `C-c &`"))
1039 (lambda (keyword desc format)
1041 ((eq format 'html) (format "(<ref>%s</ref>)" path))
1043 (format "\\ref{%s}" keyword)))))
1046 (defun org-ref-get-org-labels ()
1047 "Return a list of #+LABEL: labels."
1049 (goto-char (point-min))
1050 (let ((matches '()))
1051 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1052 ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1053 ;; who would have thought you have save match data here? Trust me. When
1054 ;; I wrote this, you did.
1055 (unless (save-match-data (equal (car (org-element-at-point)) 'table))
1056 (add-to-list 'matches (match-string-no-properties 1) t)))
1060 (defun org-ref-get-custom-ids ()
1061 "Return a list of custom_id properties in the buffer."
1062 (let ((results '()) custom_id)
1065 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1066 (when (not (null custom_id))
1067 (setq results (append results (list custom_id)))))))
1071 (defun org-ref-get-latex-labels ()
1072 "Return list of matchin LaTeX defined labels in buffer."
1074 (goto-char (point-min))
1075 (let ((matches '()))
1076 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1077 (add-to-list 'matches (match-string-no-properties 1) t))
1081 (defun org-ref-get-tblnames ()
1082 "Return list of table names in the buffer."
1083 (org-element-map (org-element-parse-buffer 'element) 'table
1085 (org-element-property :name table))))
1088 (defun org-ref-get-labels ()
1089 "Return a list of labels in the buffer that you can make a ref link to.
1090 This is used to complete ref links and in helm menus."
1094 (goto-char (point-min))
1095 (let ((matches '()))
1096 ;; these are the org-ref label:stuff kinds
1097 (while (re-search-forward
1098 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1099 (add-to-list 'matches (match-string-no-properties 1) t))
1100 ;; now add all the other kinds of labels.
1103 (org-ref-get-org-labels)
1105 (org-ref-get-latex-labels)
1106 ;; #+tblname: and actually #+label
1107 (org-ref-get-tblnames)
1109 (org-ref-get-custom-ids))))))
1112 (defun org-ref-helm-insert-label-link ()
1113 "Insert a label link. helm just shows you what labels already exist.
1114 If you are on a label link, replace it."
1116 (let* ((labels (org-ref-get-labels))
1117 (cb (current-buffer)))
1118 (helm :sources `(((name . "Existing labels")
1119 (candidates . ,labels)
1120 ;; default action is to open to the label
1121 (action . (lambda (label)
1122 ;; unfortunately I do not have markers here
1123 (org-open-link-from-string
1124 (format "ref:%s" label))))
1125 ;; if you select a label, replace current one
1126 (action . (lambda (label)
1127 (switch-to-buffer ,cb)
1129 ;; no prefix or on a link
1130 ((equal helm-current-prefix-arg nil)
1131 (let* ((object (org-element-context))
1132 (last-char (save-excursion
1133 (goto-char (org-element-property :end object))
1135 (if (looking-at " ")
1138 (when (-contains? '("label")
1139 (org-element-property :type object))
1140 ;; we are on a link, so replace it.
1143 (org-element-property :begin object)
1144 (org-element-property :end object))
1146 (replace-regexp-in-string
1147 (org-element-property :path object)
1149 (org-element-property :raw-link object))
1151 ;; no prefix options defined
1153 ;; no matching selection creates a new label
1154 ((name . "Create new label")
1156 ;; default action creates a new label, or replaces old one
1157 (action . (lambda (label)
1158 (switch-to-buffer ,cb)
1159 (let* ((object (org-element-context))
1160 (last-char (save-excursion
1161 (goto-char (org-element-property :end object))
1163 (if (looking-at " ")
1166 (if (-contains? '("label")
1167 (org-element-property :type object))
1168 ;; we are on a link, so replace it.
1171 (org-element-property :begin object)
1172 (org-element-property :end object))
1174 (replace-regexp-in-string
1175 (org-element-property :path object)
1177 (org-element-property :raw-link object))
1184 helm-pattern))))))))))))
1187 (defun org-ref-complete-link (&optional arg)
1188 "Completion function for ref links.
1189 Optional argument ARG Does nothing."
1191 (setq label (completing-read "label: " (org-ref-get-labels)))
1192 (format "ref:%s" label)))
1195 (defun org-ref-insert-ref-link ()
1196 "Completion function for a ref link."
1198 (insert (org-ref-complete-link)))
1201 (defun org-ref-helm-insert-ref-link ()
1202 "Helm menu to insert ref links to labels in the document.
1203 If you are on link, replace with newly selected label.
1204 Use C-u to insert a different kind of ref link.
1205 Use C-u C-u to insert a [[#custom-id]] link"
1207 (let* ((labels (org-ref-get-labels))
1208 (bs (buffer-string))
1209 (contexts (with-temp-buffer
1211 (mapcar 'org-ref-get-label-context labels)))
1212 (cb (current-buffer)))
1214 (helm :input (thing-at-point 'word)
1215 :sources `(((name . "Available labels to ref")
1216 (candidates . ,(loop for label in labels
1217 for context in contexts
1218 ;; we do some kludgy adding spaces
1219 ;; and bars to make it "easier" to
1221 collect (cons (concat
1226 (split-string context "\n")
1229 ;; default action to replace or insert ref link.
1230 (action . (lambda (label)
1231 (switch-to-buffer ,cb)
1234 ;; no prefix or on a link
1235 ((equal helm-current-prefix-arg nil)
1236 (let* ((object (org-element-context))
1237 (last-char (save-excursion
1238 (goto-char (org-element-property :end object))
1240 (if (looking-at " ")
1243 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1244 (org-element-property :type object))
1245 ;; we are on a link, so replace it.
1248 (org-element-property :begin object)
1249 (org-element-property :end object))
1251 (replace-regexp-in-string
1252 (org-element-property :path object)
1254 (org-element-property :raw-link object))
1256 ;; insert a new link
1261 ;; one prefix, alternate ref link
1262 ((equal helm-current-prefix-arg '(4))
1265 (helm :sources '((name . "Ref link types")
1266 (candidates . ("ref" "eqref" "pageref" "nameref"))
1267 (action . (lambda (x) x))))
1269 ;; two prefixes, insert section custom-id link
1270 ((equal helm-current-prefix-arg '(16))
1272 (format "[[#%s]]" label)))
1280 "on clicking goto the label. Navigate back with C-c &"
1281 (org-mark-ring-push)
1282 ;; next search from beginning of the buffer
1288 (goto-char (point-min))
1289 (re-search-forward (format "label:%s\\b" label) nil t))
1293 (goto-char (point-min))
1294 (re-search-forward (format "\\label{%s}" label) nil t))
1296 ;; #+label: name org-definition
1298 (goto-char (point-min))
1300 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1304 (goto-char (point-min))
1306 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1307 ;; we did not find anything, so go back to where we came
1308 (org-mark-ring-goto)
1309 (error "%s not found" label))
1310 (message "go back with (org-mark-ring-goto) `C-c &`"))
1312 (lambda (keyword desc format)
1314 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1316 (format "\\pageref{%s}" keyword)))))
1319 (defun org-pageref-complete-link (&optional arg)
1320 "Completion function for ref links.
1321 Optional argument ARG Does nothing."
1323 (setq label (completing-read "label: " (org-ref-get-labels)))
1324 (format "ref:%s" label)))
1327 (defun org-pageref-insert-ref-link ()
1328 "Insert a pageref link with completion."
1330 (insert (org-pageref-complete-link)))
1337 "on clicking goto the label. Navigate back with C-c &"
1338 (org-mark-ring-push)
1339 ;; next search from beginning of the buffer
1345 (goto-char (point-min))
1346 (re-search-forward (format "\\label{%s}" label) nil t))
1348 ;; we did not find anything, so go back to where we came
1349 (org-mark-ring-goto)
1350 (error "%s not found" label))
1351 (message "go back with (org-mark-ring-goto) `C-c &`"))
1353 (lambda (keyword desc format)
1355 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1357 (format "\\nameref{%s}" keyword)))))
1364 "on clicking goto the label. Navigate back with C-c &"
1365 (org-mark-ring-push)
1366 ;; next search from beginning of the buffer
1368 (goto-char (point-min))
1371 ;; search forward for the first match
1373 (re-search-forward (format "label:%s" label) nil t)
1375 (re-search-forward (format "\\label{%s}" label) nil t)
1376 ;; #+label: name org-definition
1377 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1378 (org-mark-ring-goto)
1379 (error "%s not found" label))
1380 (message "go back with (org-mark-ring-goto) `C-c &`"))
1382 (lambda (keyword desc format)
1384 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1386 (format "\\eqref{%s}" keyword)))))
1390 (defun org-ref-get-bibtex-key-under-cursor ()
1391 "Return key under the bibtex cursor.
1392 We search forward from
1393 point to get a comma, or the end of the link, and then backwards
1394 to get a comma, or the beginning of the link. that delimits the
1395 keyword we clicked on. We also strip the text properties."
1396 (let* ((object (org-element-context))
1397 (link-string (org-element-property :path object)))
1398 ;; you may click on the part before the citations. here we make
1399 ;; sure to move to the beginning so you get the first citation.
1401 (goto-char (org-element-property :begin object))
1402 (search-forward link-string (org-element-property :end object))
1403 (goto-char (match-beginning 0))
1404 ;; check if we clicked before the path and move as needed.
1405 (unless (< cp (point))
1408 (if (not (org-element-property :contents-begin object))
1409 ;; this means no description in the link
1411 ;; we need the link path start and end
1413 (goto-char (org-element-property :begin object))
1414 (search-forward link-string nil nil 1)
1415 (setq link-string-beginning (match-beginning 0))
1416 (setq link-string-end (match-end 0)))
1418 ;; The key is the text between commas, or the link boundaries
1420 (if (search-forward "," link-string-end t 1)
1421 (setq key-end (- (match-end 0) 1)) ; we found a match
1422 (setq key-end link-string-end))) ; no comma found so take the end
1423 ;; and backward to previous comma from point which defines the start character
1425 (if (search-backward "," link-string-beginning 1 1)
1426 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1427 (setq key-beginning link-string-beginning))) ; no match found
1428 ;; save the key we clicked on.
1430 (org-ref-strip-string
1431 (buffer-substring key-beginning key-end)))
1432 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1434 ;; link with description. assume only one key
1437 (defun org-ref-find-bibliography ()
1438 "Find the bibliography in the buffer.
1439 This function sets and returns cite-bibliography-files, which is a list of files
1440 either from bibliography:f1.bib,f2.bib
1441 \bibliography{f1,f2}
1442 internal bibliographies
1444 falling back to what the user has set in `org-ref-default-bibliography'"
1447 (goto-char (point-min))
1448 ;; look for a bibliography link
1449 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1450 (setq org-ref-bibliography-files
1451 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1452 (throw 'result org-ref-bibliography-files))
1455 ;; we did not find a bibliography link. now look for \bibliography
1456 (goto-char (point-min))
1457 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1458 ;; split, and add .bib to each file
1459 (setq org-ref-bibliography-files
1460 (mapcar (lambda (x) (concat x ".bib"))
1461 (mapcar 'org-ref-strip-string
1462 (split-string (match-string 1) ","))))
1463 (throw 'result org-ref-bibliography-files))
1465 ;; no bibliography found. maybe we need a biblatex addbibresource
1466 (goto-char (point-min))
1467 ;; look for a bibliography link
1468 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1469 (setq org-ref-bibliography-files
1470 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1471 (throw 'result org-ref-bibliography-files))
1473 ;; we did not find anything. use defaults
1474 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1476 ;; set reftex-default-bibliography so we can search
1477 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1478 org-ref-bibliography-files)
1480 (defun org-ref-key-in-file-p (key filename)
1481 "Determine if the KEY is in the FILENAME."
1482 (save-current-buffer
1483 (let ((bibtex-files (list filename)))
1484 ;; This is something I am trying because when the bibtex file is open, and
1485 ;; you have added to it, the only way I find to get the update to update
1486 ;; is to close it and reopen it. or to save it and revert it.
1487 (when (get-file-buffer filename)
1488 (set-buffer (get-file-buffer filename))
1490 (revert-buffer t t))
1491 (bibtex-search-entry key t))))
1493 (defun org-ref-get-bibtex-key-and-file (&optional key)
1494 "Return the bibtex KEY and file that it is in. If no key is provided, get one under point."
1495 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1498 (setq key (org-ref-get-bibtex-key-under-cursor)))
1499 (setq file (catch 'result
1500 (loop for file in org-ref-bibliography-files do
1501 (if (org-ref-key-in-file-p key (file-truename file))
1502 (throw 'result file)))))
1505 ;; *** key at point functions
1507 (defun org-ref-open-pdf-at-point ()
1508 "Open the pdf for bibtex key under point if it exists."
1510 (let* ((results (org-ref-get-bibtex-key-and-file))
1512 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1513 (if (file-exists-p pdf-file)
1514 (org-open-file pdf-file)
1515 (message "no pdf found for %s" key))))
1518 (defun org-ref-open-url-at-point ()
1519 "Open the url for bibtex key under point."
1521 (let* ((results (org-ref-get-bibtex-key-and-file))
1523 (bibfile (cdr results)))
1526 (insert-file-contents bibfile)
1527 (bibtex-search-entry key)
1528 ;; I like this better than bibtex-url which does not always find
1531 (let ((url (bibtex-autokey-get-field "url")))
1533 (browse-url (s-trim url))
1536 (let ((doi (bibtex-autokey-get-field "doi")))
1538 (if (string-match "^http" doi)
1540 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1541 (throw 'done nil))))))))
1544 (defun org-ref-open-notes-at-point ()
1545 "Open the notes for bibtex key under point."
1547 (let* ((results (org-ref-get-bibtex-key-and-file))
1549 (bibfile (cdr results)))
1552 (insert-file-contents bibfile)
1553 (bibtex-search-entry key)
1554 (org-ref-open-bibtex-notes)))))
1557 (defun org-ref-citation-at-point ()
1558 "Give message of current citation at point."
1560 (let* ((cb (current-buffer))
1561 (results (org-ref-get-bibtex-key-and-file))
1563 (bibfile (cdr results)))
1564 (message "%s" (progn
1566 (insert-file-contents bibfile)
1567 (bibtex-search-entry key)
1568 (org-ref-bib-citation))))))
1571 (defun org-ref-open-citation-at-point ()
1572 "Open bibtex file to key at point."
1574 (let* ((cb (current-buffer))
1575 (results (org-ref-get-bibtex-key-and-file))
1577 (bibfile (cdr results)))
1579 (bibtex-search-entry key)))
1583 (defvar org-ref-cite-menu-funcs '()
1584 "Functions to run on cite click menu.
1585 Each entry is a list of (key menu-name function).
1586 The function must take no arguments and work on the key at point. Do not modify this variable, it is set to empty in the menu click function, and functions are conditionally added to it.")
1589 (defvar org-ref-user-cite-menu-funcs
1590 '(("C" "rossref" org-ref-crossref-at-point)
1591 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1592 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1593 "User-defined functions to run on bibtex key at point.")
1596 (defun org-ref-copy-entry-as-summary ()
1597 "Copy the bibtex entry for the citation at point as a summary."
1599 (save-window-excursion
1600 (org-ref-open-citation-at-point)
1601 (kill-new (org-ref-bib-citation))))
1604 (defun org-ref-copy-entry-at-point-to-file ()
1605 "Copy the bibtex entry for the citation at point to NEW-FILE.
1606 Prompt for NEW-FILE includes bib files in `org-ref-default-bibliography', and bib files in current working directory. You can also specify a new file."
1608 (let ((new-file (ido-completing-read
1610 (append org-ref-default-bibliography
1611 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1612 (key (org-ref-get-bibtex-key-under-cursor)))
1613 (save-window-excursion
1614 (org-ref-open-citation-at-point)
1615 (bibtex-copy-entry-as-kill))
1617 (let ((bibtex-files (list (file-truename new-file))))
1618 (if (assoc key (bibtex-global-key-alist))
1619 (message "That key already exists in %s" new-file)
1621 (save-window-excursion
1622 (find-file new-file)
1623 (goto-char (point-max))
1624 ;; make sure we are at the beginning of a line.
1625 (unless (looking-at "^") (insert "\n\n"))
1630 (defun org-ref-get-doi-at-point ()
1631 "Get doi for key at point."
1632 (let* ((results (org-ref-get-bibtex-key-and-file))
1634 (bibfile (cdr results))
1638 (insert-file-contents bibfile)
1639 (bibtex-search-entry key)
1640 (setq doi (bibtex-autokey-get-field "doi"))
1641 ;; in case doi is a url, remove the url part.
1642 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1645 ;; **** functions that operate on key at point for click menu
1646 (defun org-ref-wos-at-point ()
1647 "Open the doi in wos for bibtex key under point."
1649 (doi-utils-wos (org-ref-get-doi-at-point)))
1652 (defun org-ref-wos-citing-at-point ()
1653 "Open the doi in wos citing articles for bibtex key under point."
1655 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1658 (defun org-ref-wos-related-at-point ()
1659 "Open the doi in wos related articles for bibtex key under point."
1661 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1664 (defun org-ref-google-scholar-at-point ()
1665 "Open the doi in google scholar for bibtex key under point."
1667 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1670 (defun org-ref-pubmed-at-point ()
1671 "Open the doi in pubmed for bibtex key under point."
1673 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1676 (defun org-ref-crossref-at-point ()
1677 "Open the doi in crossref for bibtex key under point."
1679 (doi-utils-crossref (org-ref-get-doi-at-point)))
1681 ;; *** Minibuffer menu
1683 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1684 "Action when a cite link is clicked on.
1685 Provides a menu of context sensitive actions. If the bibtex entry
1686 has a pdf, you get an option to open it. If there is a doi, you
1687 get a lot of options. LINK-STRING is used by the link function."
1689 (let* ((results (org-ref-get-bibtex-key-and-file))
1691 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1692 (bibfile (cdr results))
1693 (url (save-excursion
1695 (insert-file-contents bibfile)
1696 (bibtex-search-entry key)
1697 (bibtex-autokey-get-field "url"))))
1698 (doi (save-excursion
1700 (insert-file-contents bibfile)
1701 (bibtex-search-entry key)
1702 ;; I like this better than bibtex-url which does not always find
1704 (bibtex-autokey-get-field "doi")))))
1706 (when (string= "" doi) (setq doi nil))
1707 (when (string= "" url) (setq url nil))
1708 (setq org-ref-cite-menu-funcs '())
1714 'org-ref-cite-menu-funcs
1715 '("o" "pen" org-ref-open-citation-at-point)))
1718 (when (file-exists-p pdf-file)
1720 'org-ref-cite-menu-funcs
1721 `("p" "df" ,org-ref-open-pdf-function) t))
1725 'org-ref-cite-menu-funcs
1726 '("n" "otes" org-ref-open-notes-at-point) t)
1731 'org-ref-cite-menu-funcs
1732 '("u" "rl" org-ref-open-url-at-point) t))
1737 'org-ref-cite-menu-funcs
1738 '("w" "os" org-ref-wos-at-point) t)
1741 'org-ref-cite-menu-funcs
1742 '("c" "iting" org-ref-wos-citing-at-point) t)
1745 'org-ref-cite-menu-funcs
1746 '("r" "elated" org-ref-wos-related-at-point) t)
1749 'org-ref-cite-menu-funcs
1750 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1753 'org-ref-cite-menu-funcs
1754 '("P" "ubmed" org-ref-pubmed-at-point) t))
1756 ;; add user functions
1757 (dolist (tup org-ref-user-cite-menu-funcs)
1759 'org-ref-cite-menu-funcs
1764 'org-ref-cite-menu-funcs
1765 '("q" "uit" (lambda ())) t)
1767 ;; now we make a menu
1768 ;; construct menu string as a message
1771 (let* ((results (org-ref-get-bibtex-key-and-file))
1773 (bibfile (cdr results)))
1776 (insert-file-contents bibfile)
1777 (bibtex-search-entry key)
1778 (org-ref-bib-citation))))
1782 (concat "[" (elt tup 0) "]"
1784 org-ref-cite-menu-funcs "")))
1786 (let* ((input (read-char-exclusive))
1788 (char-to-string input) org-ref-cite-menu-funcs)))
1789 ;; now run the function (2nd element in choice)
1796 ;; *** Generation of the cite links
1797 (defmacro org-ref-make-completion-function (type)
1798 "Macro to make a link completion function for a link of TYPE."
1799 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1805 (let ((bibtex-files (org-ref-find-bibliography)))
1806 (bibtex-global-key-alist))))))
1808 (defmacro org-ref-make-format-function (type)
1809 "Macro to make a format function for a link of TYPE."
1810 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1815 (format "[[#%s][%s]]" key key))
1816 (org-ref-split-and-strip-string keyword) ","))
1823 (org-ref-split-and-strip-string keyword) ",") "]"))
1828 (format "<a href=\"#%s\">%s</a>" key key))
1829 (org-ref-split-and-strip-string keyword) ","))
1832 (if (string= (substring type -1) "s")
1833 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1834 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1835 (org-ref-split-and-strip-string keyword) ""))
1837 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1838 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1840 ;; for markdown we generate pandoc citations
1843 (desc ;; pre and or post text
1844 (let* ((text (split-string desc "::"))
1848 (format "[@%s," keyword)
1849 (when pre (format " %s" pre))
1850 (when post (format ", %s" post))
1855 (lambda (key) (concat "@" key))
1856 (org-ref-split-and-strip-string keyword)
1859 (defun org-ref-format-citation-description (desc)
1860 "Return formatted citation description.
1861 If the cite link has a DESC (description), it is optional text
1862 for the citation command. You can specify pre and post text by
1863 separating these with ::, for example [[cite:key][pre text::post
1866 ((string-match "::" desc)
1867 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1868 (t (format "[%s]" desc))))
1870 (defun org-ref-define-citation-link (type &optional key)
1871 "Add a citation link of TYPE for org-ref.
1872 With optional KEY, set the reftex binding. For example:
1873 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1874 citez link, with reftex key of z, and the completion function."
1875 (interactive "sCitation Type: \ncKey: ")
1877 ;; create the formatting function
1878 (eval `(org-ref-make-format-function ,type))
1883 org-ref-cite-onclick-function
1884 (quote ,(intern (format "org-ref-format-%s" type)))))
1886 ;; create the completion function
1887 (eval `(org-ref-make-completion-function ,type))
1889 ;; store new type so it works with adding citations, which checks
1890 ;; for existence in this list
1891 (add-to-list 'org-ref-cite-types type)
1893 ;; and finally if a key is specified, we modify the reftex menu
1895 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1896 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1897 `((,key . ,(concat type ":%l")))))))
1899 ;; create all the link types and their completion functions
1900 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1902 (defun org-ref-insert-cite-link (alternative-cite)
1903 "Insert a default citation link using reftex.
1904 If you are on a link, it appends to the end of the link,
1905 otherwise, a new link is inserted. Use a prefix
1906 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1908 (org-ref-find-bibliography)
1909 (let* ((object (org-element-context))
1910 (link-string-beginning (org-element-property :begin object))
1911 (link-string-end (org-element-property :end object))
1912 (path (org-element-property :path object)))
1914 (if (not alternative-cite)
1917 ;; case where we are in a link
1918 ((and (equal (org-element-type object) 'link)
1919 (-contains? org-ref-cite-types (org-element-property :type object)))
1920 (goto-char link-string-end)
1921 ;; sometimes there are spaces at the end of the link
1922 ;; this code moves point pack until no spaces are there
1923 (while (looking-back " ") (backward-char))
1924 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1926 ;; We are next to a link, and we want to append
1929 (and (equal (org-element-type (org-element-context)) 'link)
1930 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1931 (while (looking-back " ") (backward-char))
1932 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1934 ;; insert fresh link
1937 (concat org-ref-default-citation-link
1939 (mapconcat 'identity (reftex-citation t) ",")))))
1941 ;; you pressed a C-u so we run this code
1942 (reftex-citation))))
1944 (defun org-ref-insert-cite-with-completion (type)
1945 "Insert a cite link of TYPE with completion."
1946 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1947 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1949 (defun org-ref-store-bibtex-entry-link ()
1950 "Save a citation link to the current bibtex entry. Save in the default link type."
1952 (let ((link (concat org-ref-default-citation-link
1955 (bibtex-beginning-of-entry)
1956 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1957 (message "saved %s" link)
1958 (push (list link) org-stored-links)
1959 (car org-stored-links)))
1967 (lambda (path desc format)
1970 (format "\\index{%s}" path)))))
1972 ;; this will generate a temporary index of entries in the file.
1976 (let ((*index-links* '())
1977 (*initial-letters* '()))
1980 (org-element-map (org-element-parse-buffer) 'link
1982 (let ((type (nth 0 link))
1983 (plist (nth 1 link)))
1985 (when (equal (plist-get plist ':type) "index")
1988 (cons (plist-get plist :path)
1990 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
1992 (plist-get plist :begin) ;; position of link
1993 ;; grab a description
1995 (goto-char (plist-get plist :begin))
1996 (if (thing-at-point 'sentence)
1998 (replace-regexp-in-string
1999 "\n" "" (thing-at-point 'sentence))
2000 ;; or call it a link
2004 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2006 ;; now first letters
2007 (dolist (link *index-links*)
2008 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2010 ;; now create the index
2011 (switch-to-buffer (get-buffer-create "*index*"))
2014 (insert "#+TITLE: Index\n\n")
2015 (dolist (letter *initial-letters*)
2016 (insert (format "* %s\n" (upcase letter)))
2017 ;; now process the links
2020 (string= letter (substring (car (car *index-links*)) 0 1)))
2021 (let ((link (pop *index-links*)))
2022 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2023 (switch-to-buffer "*index*")))
2025 (lambda (path desc format)
2028 (format "\\printindex")))))
2033 nil ;; no follow action
2034 (lambda (path desc format)
2037 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2043 nil ;; no follow action
2044 (lambda (path desc format)
2047 (format "\\gls{%s}" path)))))
2052 nil ;; no follow action
2053 (lambda (path desc format)
2056 (format "\\glspl{%s}" path)))))
2061 nil ;; no follow action
2062 (lambda (path desc format)
2065 (format "\\Gls{%s}" path)))))
2070 nil ;; no follow action
2071 (lambda (path desc format)
2074 (format "\\Glspl{%s}" path)))))
2077 ;; ** create text citations from a bibtex entry
2078 (defun org-ref-bib-citation ()
2079 "From a bibtex entry, create and return a simple citation string.
2080 This assumes you are in an article."
2082 (bibtex-beginning-of-entry)
2083 (let* ((cb (current-buffer))
2084 (bibtex-expand-strings t)
2085 (entry (loop for (key . value) in (bibtex-parse-entry t)
2086 collect (cons (downcase key) value)))
2087 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2088 (year (reftex-get-bib-field "year" entry))
2089 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2090 (key (reftex-get-bib-field "=key=" entry))
2091 (journal (reftex-get-bib-field "journal" entry))
2092 (volume (reftex-get-bib-field "volume" entry))
2093 (pages (reftex-get-bib-field "pages" entry))
2094 (doi (reftex-get-bib-field "doi" entry))
2095 (url (reftex-get-bib-field "url" entry))
2097 ;;authors, "title", Journal, vol(iss):pages (year).
2098 (format "%s, \"%s\", %s, %s:%s (%s)"
2099 author title journal volume pages year)))
2101 (defun org-ref-bib-html-citation ()
2102 "From a bibtex entry, create and return a simple citation with html links."
2104 (bibtex-beginning-of-entry)
2105 (let* ((cb (current-buffer))
2106 (bibtex-expand-strings t)
2107 (entry (loop for (key . value) in (bibtex-parse-entry t)
2108 collect (cons (downcase key) value)))
2109 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2110 (year (reftex-get-bib-field "year" entry))
2111 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2112 (key (reftex-get-bib-field "=key=" entry))
2113 (journal (reftex-get-bib-field "journal" entry))
2114 (volume (reftex-get-bib-field "volume" entry))
2115 (pages (reftex-get-bib-field "pages" entry))
2116 (doi (reftex-get-bib-field "doi" entry))
2117 (url (reftex-get-bib-field "url" entry))
2119 ;;authors, "title", Journal, vol(iss):pages (year).
2120 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2121 author title journal volume pages year)
2122 (when url (format " <a href=\"%s\">link</a>" url))
2123 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2126 ;; ** Open pdf in bibtex entry
2127 (defun org-ref-open-bibtex-pdf ()
2128 "Open pdf for a bibtex entry, if it exists.
2130 the entry of interest in the bibfile. but does not check that."
2133 (bibtex-beginning-of-entry)
2134 (let* ((bibtex-expand-strings t)
2135 (entry (bibtex-parse-entry t))
2136 (key (reftex-get-bib-field "=key=" entry))
2137 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2139 (if (file-exists-p pdf)
2140 (org-open-link-from-string (format "[[file:%s]]" pdf))
2143 ;; ** Open notes from bibtex entry
2145 (defun org-ref-open-bibtex-notes ()
2146 "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2148 I never did figure out how to use reftex to make this happen
2149 non-interactively. the reftex-format-citation function did not
2150 work perfectly; there were carriage returns in the strings, and
2151 it did not put the key where it needed to be. so, below I replace
2152 the carriage returns and extra spaces with a single space and
2153 construct the heading by hand."
2156 (bibtex-beginning-of-entry)
2157 (let* ((cb (current-buffer))
2158 (bibtex-expand-strings t)
2159 (entry (loop for (key . value) in (bibtex-parse-entry t)
2160 collect (cons (downcase key) value)))
2161 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2162 (year (reftex-get-bib-field "year" entry))
2163 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2164 (key (reftex-get-bib-field "=key=" entry))
2165 (journal (reftex-get-bib-field "journal" entry))
2166 (volume (reftex-get-bib-field "volume" entry))
2167 (pages (reftex-get-bib-field "pages" entry))
2168 (doi (reftex-get-bib-field "doi" entry))
2169 (url (reftex-get-bib-field "url" entry))
2172 ;; save key to clipboard to make saving pdf later easier by pasting.
2175 (kill-ring-save (point-min) (point-max)))
2177 ;; now look for entry in the notes file
2178 (if org-ref-bibliography-notes
2179 (find-file-other-window org-ref-bibliography-notes)
2180 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2182 (goto-char (point-min))
2183 ;; put new entry in notes if we don't find it.
2184 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2185 (funcall org-ref-open-notes-function)
2186 ;; no entry found, so add one
2187 (insert (format "\n** TODO %s - %s" year title))
2199 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2200 key author journal year volume pages doi url key org-ref-pdf-directory key))
2203 (defun org-ref-open-notes-from-reftex ()
2204 "Call reftex, and open notes for selected entry."
2206 (let ((bibtex-key )))
2208 ;; now look for entry in the notes file
2209 (if org-ref-bibliography-notes
2210 (find-file-other-window org-ref-bibliography-notes)
2211 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2213 (goto-char (point-min))
2215 (re-search-forward (format
2217 (first (reftex-citation t)) nil 'end))
2218 (funcall org-ref-open-notes-function))
2220 ;; ** Open bibtex entry in browser
2221 (defun org-ref-open-in-browser ()
2222 "Open the bibtex entry at point in a browser using the url field or doi field."
2225 (bibtex-beginning-of-entry)
2227 (let ((url (bibtex-autokey-get-field "url")))
2232 (let ((doi (bibtex-autokey-get-field "doi")))
2234 (if (string-match "^http" doi)
2236 (browse-url (format "http://dx.doi.org/%s" doi)))
2238 (message "No url or doi found"))))
2240 ;; ** upload entry to citeulike
2242 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2243 "With point in a bibtex entry get bibtex string and submit to citeulike.
2245 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2247 (message "uploading to citeulike")
2249 (bibtex-narrow-to-entry)
2250 (let ((startpos (point-min))
2251 (endpos (point-max))
2252 (bibtex-string (buffer-string))
2253 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2254 (with-temp-buffer (insert bibtex-string)
2255 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2257 ;; ** Build a pdf of the bibtex file
2258 (defun org-ref-build-full-bibliography ()
2259 "Build pdf of all bibtex entries, and open it."
2261 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2262 (bib-base (file-name-sans-extension bibfile))
2263 (texfile (concat bib-base ".tex"))
2264 (pdffile (concat bib-base ".pdf")))
2267 (insert (format "\\documentclass[12pt]{article}
2268 \\usepackage[version=3]{mhchem}
2270 \\usepackage[numbers]{natbib}
2271 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2275 \\bibliographystyle{unsrtnat}
2277 \\end{document}" bib-base))
2279 (shell-command (concat "pdflatex " bib-base))
2280 (shell-command (concat "bibtex " bib-base))
2281 (shell-command (concat "pdflatex " bib-base))
2282 (shell-command (concat "pdflatex " bib-base))
2283 (kill-buffer texfile)
2284 (org-open-file pdffile)
2287 ;; ** Extract bibtex entries in org-file
2289 (defun org-ref-extract-bibtex-entries ()
2290 "Extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2292 If no bibliography is in the buffer the variable
2293 `reftex-default-bibliography' is used."
2295 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2296 (tempname (make-temp-file "extract-bib"))
2297 (contents (buffer-string))
2298 (cb (current-buffer))
2299 basename texfile bibfile results)
2301 ;; open tempfile and insert org-buffer contents
2302 (find-file tempname)
2304 (setq basename (file-name-sans-extension
2305 (file-name-nondirectory buffer-file-name))
2306 texfile (concat tempname ".tex")
2307 bibfile (concat tempname ".bib"))
2309 ;; see if we have a bibliography, and insert the default one if not.
2311 (goto-char (point-min))
2312 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2313 (insert (format "\nbibliography:%s"
2314 (mapconcat 'identity reftex-default-bibliography ",")))))
2317 ;; get a latex file and extract the references
2318 (org-latex-export-to-latex)
2321 (reftex-create-bibtex-file bibfile)
2323 ;; save results of the references
2324 (setq results (buffer-string))
2326 ;; kill buffers. these are named by basename, not full path
2327 (kill-buffer (concat basename ".bib"))
2328 (kill-buffer (concat basename ".tex"))
2329 (kill-buffer basename)
2331 (delete-file bibfile)
2332 (delete-file texfile)
2333 (delete-file tempname)
2335 ;; Now back to the original org buffer and insert the results
2336 (switch-to-buffer cb)
2337 (when (not (string= "" results))
2339 (goto-char (point-max))
2341 (org-insert-heading)
2342 (insert (format " Bibtex entries
2344 #+BEGIN_SRC text :tangle %s
2346 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2348 ;; ** Find bad citations
2351 (defun index (substring list)
2352 "Return the index of SUBSTRING in a LIST of strings."
2355 (dolist (arg list i)
2356 (if (string-match (concat "^" substring "$") arg)
2361 ;; return counter if found, otherwise return nil
2365 (defun org-ref-find-bad-citations ()
2366 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2368 Makes a new buffer with clickable links."
2370 ;; generate the list of bibtex-keys and cited keys
2371 (let* ((bibtex-files (org-ref-find-bibliography))
2372 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2373 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2374 (bad-citations '()))
2376 (org-element-map (org-element-parse-buffer) 'link
2378 (let ((plist (nth 1 link)))
2379 (when (-contains? org-ref-cite-types (plist-get plist :type))
2380 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2381 (when (not (index key bibtex-keys))
2386 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2389 (plist-get plist :begin)))))
2391 ;; set with-affilates to t to get citations in a caption
2396 (switch-to-buffer-other-window "*Missing citations*")
2399 (insert "* List of bad cite links\n")
2400 (insert (mapconcat 'identity bad-citations ""))
2401 ;(setq buffer-read-only t)
2402 (use-local-map (copy-keymap org-mode-map))
2403 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2405 (when (get-buffer "*Missing citations*")
2406 (kill-buffer "*Missing citations*"))
2407 (message "No bad cite links found"))))
2409 ;; ** helm interface to bad citations, labels, refs and files in orgfile
2410 (defun org-ref-bad-cite-candidates ()
2411 "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2412 (let* ((cp (point)) ; save to return to later
2413 (bibtex-files (org-ref-find-bibliography))
2414 (bibtex-file-path (mapconcat
2416 (file-name-directory (file-truename x)))
2418 (bibtex-keys (mapcar (lambda (x) (car x))
2419 (bibtex-global-key-alist)))
2420 (bad-citations '()))
2422 (org-element-map (org-element-parse-buffer) 'link
2424 (let ((plist (nth 1 link)))
2425 (when (-contains? org-ref-cite-types (plist-get plist :type))
2426 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2427 (when (not (index key bibtex-keys))
2428 (goto-char (plist-get plist :begin))
2429 (re-search-forward key)
2430 (push (cons key (point-marker)) bad-citations)))
2432 ;; add with-affiliates to get cites in caption
2438 (defun org-ref-bad-ref-candidates ()
2439 "Return a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2440 ;; first get a list of legitimate labels
2442 (labels (org-ref-get-labels))
2444 ;; now loop over ref links
2445 (goto-char (point-min))
2446 (org-element-map (org-element-parse-buffer) 'link
2448 (let ((plist (nth 1 link)))
2449 (when (or (equal (plist-get plist ':type) "ref")
2450 (equal (plist-get plist ':type) "eqref")
2451 (equal (plist-get plist ':type) "pageref")
2452 (equal (plist-get plist ':type) "nameref"))
2453 (unless (-contains? labels (plist-get plist :path))
2454 (goto-char (plist-get plist :begin))
2457 (cons (plist-get plist :path)
2458 (point-marker))))))))
2463 (defun org-ref-bad-label-candidates ()
2464 "Return a list of labels where label is multiply defined."
2465 (let ((labels (org-ref-get-labels))
2466 (multiple-labels '()))
2467 (when (not (= (length labels)
2468 (length (-uniq labels))))
2469 (dolist (label labels)
2470 (when (> (-count (lambda (a)
2473 ;; this is a multiply defined label.
2475 (goto-char (point-min))
2476 (while (re-search-forward
2477 (format "[^#+]label:%s\\s-" label) nil t)
2478 (push (cons label (point-marker)) multiple-labels))
2479 (goto-char (point-min))
2480 (while (re-search-forward
2481 (format "\\label{%s}\\s-?" label) nil t)
2482 (push (cons label (point-marker)) multiple-labels))
2484 (goto-char (point-min))
2485 (while (re-search-forward
2486 (format "^#\\+label:\\s-*%s" label) nil t)
2487 (push (cons label (point-marker)) multiple-labels))
2489 (goto-char (point-min))
2490 (while (re-search-forward
2491 (format "^#\\+tblname:\\s-*%s" label) nil t)
2492 (push (cons label (point-marker)) multiple-labels))
2496 (defun org-ref-bad-file-link-candidates ()
2497 "Return list of conses (link . marker) wehre the file in the link does not exist."
2498 (let* ((bad-files '()))
2499 (org-element-map (org-element-parse-buffer) 'link
2501 (let ((type (org-element-property :type link)))
2502 (when (or (string= "file" type)
2503 (string= "attachfile" type))
2504 (unless (file-exists-p (org-element-property :path link))
2505 (add-to-list 'bad-files
2506 (cons (org-element-property :path link)
2509 (org-element-property :begin link))
2510 (point-marker)))))))))
2511 ;; Let us also check \attachfile{fname}
2513 (goto-char (point-min))
2514 (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
2515 (unless (file-exists-p (match-string 1))
2516 (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
2521 "Opens a helm interface to actions for org-ref.
2522 Shows bad citations, ref links and labels"
2524 (let ((cb (current-buffer))
2525 (bad-citations (org-ref-bad-cite-candidates))
2526 (bad-refs (org-ref-bad-ref-candidates))
2527 (bad-labels (org-ref-bad-label-candidates))
2528 (bad-files (org-ref-bad-file-link-candidates)))
2530 (helm :sources `(((name . "Bad citations")
2531 (candidates . ,bad-citations)
2532 (action . (lambda (marker)
2533 (switch-to-buffer (marker-buffer marker))
2534 (goto-char marker))))
2536 ((name . "Bad Labels")
2537 (candidates . ,bad-labels)
2538 (action . (lambda (marker)
2539 (switch-to-buffer (marker-buffer marker))
2540 (goto-char marker))))
2542 ((name . "Bad ref links")
2543 (candidates . ,bad-refs)
2544 (action . (lambda (marker)
2545 (switch-to-buffer (marker-buffer marker))
2546 (goto-char marker))))
2548 ((name . "Bad file links")
2549 (candidates . ,bad-files)
2551 (switch-to-buffer (marker-buffer marker))
2552 (goto-char marker)))
2554 ((name . "Utilities")
2555 (candidates . (("Check buffer again" . org-ref)
2556 ("Insert citation" . helm-bibtex)
2557 ("Insert label link" . org-ref-helm-insert-label-link)
2558 ("Insert ref link" . org-ref-helm-insert-ref-link)
2559 ("List of figures" . org-ref-list-of-figures)
2560 ("List of tables" . org-ref-list-of-tables)
2561 ("Table of contents" . nil)
2563 (action . (lambda (x)
2564 (switch-to-buffer ,cb)
2567 ((name . "Export functions")
2568 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2569 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2570 ("Export to pdf and open" . (lambda ()
2571 (org-open-file (org-latex-export-to-pdf))))
2572 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2573 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2576 (action . (lambda (x)
2577 (switch-to-buffer ,cb)
2580 ;; ** Find non-ascii charaters
2581 (defun org-ref-find-non-ascii-characters ()
2582 "Find non-ascii characters in the buffer. Useful for cleaning up bibtex files."
2584 (occur "[^[:ascii:]]"))
2586 ;; ** Sort fields in a bibtex entry
2588 (defun org-ref-sort-bibtex-entry ()
2589 "Sort fields of entry in standard order and downcase them."
2591 (bibtex-beginning-of-entry)
2592 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2593 (entry (bibtex-parse-entry))
2596 (type (cdr (assoc "=type=" entry)))
2597 (key (cdr (assoc "=key=" entry))))
2599 ;; these are the fields we want to order that are in this entry
2600 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2601 ;; we do not want to reenter these fields
2602 (setq entry-fields (remove "=key=" entry-fields))
2603 (setq entry-fields (remove "=type=" entry-fields))
2605 ;;these are the other fields in the entry
2606 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2609 ;; right now we only resort articles
2610 ((string= (downcase type) "article")
2613 (concat "@article{" key ",\n"
2616 (when (member field entry-fields)
2617 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2620 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2622 (bibtex-find-entry key)
2624 (bibtex-clean-entry)
2627 ;; ** Clean a bibtex entry
2628 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2629 "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"
2631 (bibtex-beginning-of-entry)
2633 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2634 (unless (string-match ",$" (thing-at-point 'line))
2638 ;; check for empty pages, and put eid or article id in its place
2639 (let ((entry (bibtex-parse-entry))
2640 (pages (bibtex-autokey-get-field "pages"))
2641 (year (bibtex-autokey-get-field "year"))
2642 (doi (bibtex-autokey-get-field "doi"))
2643 ;; The Journal of Chemical Physics uses eid
2644 (eid (bibtex-autokey-get-field "eid")))
2646 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2647 ;; but we only want the doi.
2648 (when (string-match "^http://dx.doi.org/" doi)
2649 (bibtex-beginning-of-entry)
2650 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2652 (bibtex-make-field "doi")
2654 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2656 ;; asap articles often set year to 0, which messes up key
2657 ;; generation. fix that.
2658 (when (string= "0" year)
2659 (bibtex-beginning-of-entry)
2660 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2662 (bibtex-make-field "year")
2664 (insert (read-string "Enter year: ")))
2666 ;; fix pages if they are empty if there is an eid to put there.
2667 (when (string= "-" pages)
2669 (bibtex-beginning-of-entry)
2670 ;; this seems like a clunky way to set the pages field.But I
2671 ;; cannot find a better way.
2672 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2674 (bibtex-make-field "pages")
2678 ;; replace naked & with \&
2680 (bibtex-narrow-to-entry)
2681 (bibtex-beginning-of-entry)
2682 (message "checking &")
2683 (replace-regexp " & " " \\\\& ")
2686 ;; generate a key, and if it duplicates an existing key, edit it.
2688 (let ((key (bibtex-generate-autokey)))
2690 ;; first we delete the existing key
2691 (bibtex-beginning-of-entry)
2692 (re-search-forward bibtex-entry-maybe-empty-head)
2693 (if (match-beginning bibtex-key-in-head)
2694 (delete-region (match-beginning bibtex-key-in-head)
2695 (match-end bibtex-key-in-head)))
2696 ;; check if the key is in the buffer
2697 (when (save-excursion
2698 (bibtex-search-entry key))
2700 (bibtex-search-entry key)
2701 (bibtex-copy-entry-as-kill)
2702 (switch-to-buffer-other-window "*duplicate entry*")
2704 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2707 (kill-new key))) ;; save key for pasting
2709 ;; run hooks. each of these operates on the entry with no arguments.
2710 ;; this did not work like i thought, it gives a symbolp error.
2711 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2716 org-ref-clean-bibtex-entry-hook)
2718 ;; sort fields within entry
2719 (org-ref-sort-bibtex-entry)
2720 ;; check for non-ascii characters
2721 (occur "[^[:ascii:]]")
2724 (defun org-ref-get-citation-year (key)
2725 "Get the year of an entry with KEY. Return year as a string."
2726 (let* ((results (org-ref-get-bibtex-key-and-file key))
2727 (bibfile (cdr results)))
2729 (insert-file-contents bibfile)
2730 (bibtex-search-entry key nil 0)
2731 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2734 ;; ** Sort cite in cite link
2735 (defun org-ref-sort-citation-link ()
2736 "Replace link at point with sorted link by year."
2738 (let* ((object (org-element-context))
2739 (type (org-element-property :type object))
2740 (begin (org-element-property :begin object))
2741 (end (org-element-property :end object))
2742 (link-string (org-element-property :path object))
2744 (setq keys (org-ref-split-and-strip-string link-string))
2745 (setq years (mapcar 'org-ref-get-citation-year keys))
2746 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2747 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2748 ;; now get the keys separated by commas
2749 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2750 ;; and replace the link with the sorted keys
2751 (cl--set-buffer-substring begin end (concat type ":" keys))))
2753 ;; ** Shift-arrow sorting of keys in a cite link
2755 (defun org-ref-swap-keys (i j keys)
2756 "Swap the KEYS in a list with index I and J."
2757 (let ((tempi (nth i keys)))
2758 (setf (nth i keys) (nth j keys))
2759 (setf (nth j keys) tempi))
2763 (defun org-ref-swap-citation-link (direction)
2764 "Move citation at point in DIRECTION +1 is to the right, -1 to the left."
2766 (let* ((object (org-element-context))
2767 (type (org-element-property :type object))
2768 (begin (org-element-property :begin object))
2769 (end (org-element-property :end object))
2770 (link-string (org-element-property :path object))
2772 ;; We only want this to work on citation links
2773 (when (-contains? org-ref-cite-types type)
2774 (setq key (org-ref-get-bibtex-key-under-cursor))
2775 (setq keys (org-ref-split-and-strip-string link-string))
2776 (setq i (index key keys)) ;; defined in org-ref
2777 (if (> direction 0) ;; shift right
2778 (org-ref-swap-keys i (+ i 1) keys)
2779 (org-ref-swap-keys i (- i 1) keys))
2780 (setq keys (mapconcat 'identity keys ","))
2781 ;; and replace the link with the sorted keys
2782 (cl--set-buffer-substring
2786 ;; It seems the space at the end can get consumed, so we see if there
2787 ;; is a space, and add it if so. Sometimes there is a comma or period,
2788 ;; then we do not want a space.
2792 (looking-back " ")) " ")))
2793 ;; now go forward to key so we can move with the key
2794 (re-search-forward key)
2795 (goto-char (match-beginning 0)))))
2797 ;; add hooks to make it work
2798 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2799 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2801 ;; ** context around org-ref links
2802 (defun org-ref-get-label-context (label)
2803 "Return a string of context around a LABEL."
2806 (goto-char (point-min))
2807 (when (re-search-forward
2808 (format "label:%s\\b" label) nil t)
2809 (throw 'result (buffer-substring
2818 (goto-char (point-min))
2819 (when (re-search-forward
2820 (format "\\label{%s}" label) nil t)
2821 (throw 'result (buffer-substring
2830 (goto-char (point-min))
2831 (when (re-search-forward
2832 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2833 (throw 'result (buffer-substring
2842 (goto-char (point-min))
2843 (when (re-search-forward
2844 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2845 (throw 'result (buffer-substring
2853 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2856 (defun org-ref-link-message ()
2857 "Print a minibuffer message about the link that point is on."
2861 (when (eq major-mode 'org-mode)
2862 (let* ((object (org-element-context))
2863 (type (org-element-property :type object)))
2867 ((-contains? org-ref-cite-types type)
2868 (message (org-ref-get-citation-string-at-point)))
2870 ;; message some context about the label we are referring to
2871 ((string= type "ref")
2872 (message "%scount: %s"
2873 (org-ref-get-label-context
2874 (org-element-property :path object))
2875 (org-ref-count-labels
2876 (org-element-property :path object))))
2878 ((string= type "eqref")
2879 (message "%scount: %s"
2880 (org-ref-get-label-context
2881 (org-element-property :path object))
2882 (org-ref-count-labels
2883 (org-element-property :path object))))
2885 ;; message the count
2886 ((string= type "label")
2887 (let ((count (org-ref-count-labels
2888 (org-element-property :path object))))
2889 ;; get plurality on occurrence correct
2891 (number-to-string count)
2893 (when (or (= count 0)
2897 ((string= type "custom-id")
2899 (org-open-link-from-string
2900 (format "[[#%s]]" (org-element-property :path object)))
2901 (message "%s" (org-get-heading))))
2903 ;; check if the bibliography files exist.
2904 ((string= type "bibliography")
2906 ;; object is the link you clicked on
2907 (object (org-element-context))
2908 (link-string (org-element-property :path object))
2909 (link-string-beginning)
2912 (goto-char (org-element-property :begin object))
2913 (search-forward link-string nil nil 1)
2914 (setq link-string-beginning (match-beginning 0))
2915 (setq link-string-end (match-end 0)))
2917 ;; make sure we are in link and not before the :
2918 (when (> link-string-beginning (point))
2919 (goto-char link-string-beginning))
2921 ;; now if we have comma separated bibliographies
2922 ;; we find the one clicked on. we want to
2923 ;; search forward to next comma from point
2925 (if (search-forward "," link-string-end 1 1)
2926 (setq key-end (- (match-end 0) 1)) ; we found a match
2927 (setq key-end (point)))) ; no comma found so take the point
2929 ;; and backward to previous comma from point
2931 (if (search-backward "," link-string-beginning 1 1)
2932 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2933 (setq key-beginning (point)))) ; no match found
2934 ;; save the key we clicked on.
2936 (org-ref-strip-string
2937 (buffer-substring key-beginning key-end)))
2938 (if (file-exists-p bibfile)
2939 (message "%s exists." bibfile)
2940 (message "!!! %s NOT FOUND !!!" bibfile))))))))))
2943 (defalias 'oro 'org-ref-open-citation-at-point)
2944 (defalias 'orc 'org-ref-citation-at-point)
2945 (defalias 'orp 'org-ref-open-pdf-at-point)
2946 (defalias 'oru 'org-ref-open-url-at-point)
2947 (defalias 'orn 'org-ref-open-notes-at-point)
2948 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2950 (defalias 'orib 'org-ref-insert-bibliography-link)
2951 (defalias 'oric 'org-ref-insert-cite-link)
2952 (defalias 'orir 'org-ref-insert-ref-link)
2953 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2955 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2957 ;; * Helm bibtex setup
2959 (setq helm-bibtex-additional-search-fields '(keywords))
2961 (defun helm-bibtex-candidates-formatter (candidates source)
2962 "Formats BibTeX entries for display in results list.
2963 Argument CANDIDATES helm candidates.
2964 Argument SOURCE the helm source."
2966 with width = (with-helm-window (helm-bibtex-window-width))
2967 for entry in candidates
2968 for entry = (cdr entry)
2969 for entry-key = (helm-bibtex-get-value "=key=" entry)
2970 if (assoc-string "author" entry 'case-fold)
2971 for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2973 for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2974 for fields = (--map (helm-bibtex-clean-string
2975 (helm-bibtex-get-value it entry " "))
2977 for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
2978 for fields = (append fields
2979 (list (or (helm-bibtex-get-value "keywords" entry)
2982 (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
2983 (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
2984 fields (list 36 (- width 85) 4 1 1 7 7)))
2987 ;; * org-ref bibtex keywords
2988 ;; adapted from bibtex-utils.el
2989 ;; these are candidates for selecting keywords/tags
2990 (defun org-ref-bibtex-keywords ()
2991 "Get keywords defined in current bibtex file.
2992 These are in the keywords field, and are comma or semicolon separated."
2994 (goto-char (point-min))
2995 (let (keywords kstring)
2996 (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
2997 ;; TWS - remove newlines/multiple spaces:
2998 (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
3001 (add-to-list 'keywords v t))
3002 (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
3006 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
3007 "Add KEYWORDS to a bibtex entry.
3008 If KEYWORDS is a list, it is converted to a comma-separated
3009 string. The KEYWORDS are added to the beginning of the
3010 field. Otherwise KEYWORDS should be a string of comma-separate
3011 keywords. Optional argument ARG prefix arg to replace keywords."
3012 (interactive "sKeywords: \nP")
3017 (if (listp keywords)
3018 (mapconcat 'identity keywords ", ")
3020 ;; else concatentate
3022 (if (listp keywords)
3023 (mapconcat 'identity keywords ", ")
3025 (when (not (string= "" (bibtex-autokey-get-field "keywords")))
3026 (concat ", " (bibtex-autokey-get-field "keywords"))))))
3030 (defun helm-tag-bibtex-entry ()
3031 "Helm interface to add keywords to a bibtex entry.
3032 Run this with the point in a bibtex entry."
3034 (let ((keyword-source `((name . "Existing keywords")
3035 (candidates . ,(org-ref-bibtex-keywords))
3036 (action . (lambda (candidate)
3037 (org-ref-set-bibtex-keywords
3040 (helm-marked-candidates)
3042 (fallback-source `((name . "Add new keywords")
3044 (action . (lambda (candidate)
3045 (org-ref-set-bibtex-keywords helm-pattern)
3047 (helm :sources '(keyword-source fallback-source))))
3049 (defun helm-bibtex-show-entry (key)
3050 "Show the entry for KEY in the BibTeX file.
3051 The original function in `helm-bibtex' has a bug where it finds the
3052 first key that partially matches. This version avoids that."
3054 (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
3055 helm-bibtex-bibliography
3056 (list helm-bibtex-bibliography)))
3057 (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
3059 (find-file bibtex-file)
3061 (lambda (key start end)
3062 (add-to-list 'entries (cons key start))))
3063 (if (assoc key entries)
3065 (goto-char (cdr (assoc key entries)))
3070 (defun org-ref-helm-tag-entries (candidates)
3071 "Set tags on selected bibtex entries from `helm-bibtex'.
3072 User is prompted for tags. This function is called from `helm-bibtex'.
3073 Argument CANDIDATES helm candidates."
3075 (let ((keywords (read-input "Keywords (comma separated): ")))
3076 (loop for key in (helm-marked-candidates)
3078 (save-window-excursion
3079 (helm-bibtex-show-entry key)
3084 ", " (bibtex-autokey-get-field "keywords")))
3087 (setq helm-source-bibtex
3088 '((name . "BibTeX entries")
3089 (init . helm-bibtex-init)
3090 (candidates . helm-bibtex-candidates)
3091 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3092 (action . (("Insert citation" . helm-bibtex-insert-citation)
3093 ("Show entry" . helm-bibtex-show-entry)
3094 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3095 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3096 ("Insert formatted reference" . helm-bibtex-insert-reference)
3097 ("Insert BibTeX key" . helm-bibtex-insert-key)
3098 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3099 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3100 ("Edit notes" . helm-bibtex-edit-notes)
3101 ("Add keywords to entries" . org-ref-helm-tag-entries)
3104 (defun helm-bibtex-format-org-ref (keys)
3105 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3106 Technically, this function should return a string that is inserted by helm. This function does the insertion and gives helm an empty string to insert. This lets us handle appending to a link properly.
3108 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3110 C-u C-u will change the key at point to the selected keys."
3111 (let* ((object (org-element-context))
3112 (last-char (save-excursion
3113 (goto-char (org-element-property :end object))
3115 (if (looking-at " ")
3119 ;; case where we are in a link
3120 ((and (equal (org-element-type object) 'link)
3123 (org-element-property :type object)))
3125 ;; no prefix. append keys
3126 ((equal helm-current-prefix-arg nil)
3127 (goto-char (org-element-property :end object))
3128 (while (looking-back " ") (backward-char))
3129 (insert (concat "," (mapconcat 'identity keys ","))))
3130 ;; double prefix, replace key at point
3131 ((equal helm-current-prefix-arg '(16))
3132 (setf (buffer-substring
3133 (org-element-property :begin object)
3134 (org-element-property :end object))
3136 (replace-regexp-in-string
3137 (car (org-ref-get-bibtex-key-and-file)) ; key
3138 (mapconcat 'identity keys ",") ; new keys
3139 (org-element-property :raw-link object))
3140 ;; replace space at end to avoid collapsing into next word.
3142 ;; and we want to go to the end of the new link
3144 (org-element-property :end (org-element-context))))
3146 (message "Not found"))))
3148 ;; We are next to a link, and we want to append
3149 ;; next to a link means one character back is on a link.
3152 (and (equal (org-element-type (org-element-context)) 'link)
3155 (org-element-property :type (org-element-context)))))
3156 (while (looking-back " ") (backward-char))
3157 (insert (concat "," (mapconcat 'identity keys ","))))
3159 ;; insert fresh link
3161 ;;(message-box "fresh link")
3163 (concat (if (equal helm-current-prefix-arg '(4))
3164 (helm :sources `((name . "link types")
3165 (candidates . ,org-ref-cite-types)
3166 (action . (lambda (x) x))))
3167 org-ref-default-citation-link)
3169 (s-join "," keys))))))
3170 ;; return empty string for helm
3173 (setq helm-bibtex-format-citation-functions
3174 '((org-mode . helm-bibtex-format-org-ref)))
3177 (defun org-ref-helm-insert-cite-link (arg)
3178 "org-ref function to use helm-bibtex to insert a citation link.
3179 With one prefix arg, insert a ref link.
3180 With two prefix args, insert a label link."
3184 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3187 (org-ref-helm-insert-ref-link))
3189 (org-ref-helm-insert-label-link))))
3192 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3193 (setq helm-bibtex-fallback-options
3194 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3196 (setq helm-bibtex-fallback-options
3199 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3200 helm-bibtex-fallback-options))
3202 (setq helm-bibtex-fallback-options
3203 (-insert-at 1 '("WOS" . "http://gateway.webofknowledge.com/gateway/Gateway.cgi?topic=%s&GWVersion=2&SrcApp=WEB&SrcAuth=HSB&DestApp=UA&DestLinkType=GeneralSearchSummary") helm-bibtex-fallback-options))
3205 (defun org-ref-get-citation-string-at-point ()
3206 "Get a string of a formatted citation."
3207 (let* ((results (org-ref-get-bibtex-key-and-file))
3209 (bibfile (cdr results)))
3213 (insert-file-contents bibfile)
3214 (bibtex-search-entry key)
3215 (org-ref-bib-citation)))
3216 "!!! No entry found !!!" )))
3219 (defun org-ref-cite-candidates ()
3220 "Generate the list of possible candidates for click actions on a cite link.
3221 Checks for pdf and doi, and add appropriate functions."
3222 (let* ((results (org-ref-get-bibtex-key-and-file))
3224 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3225 (bibfile (cdr results))
3226 (url (save-excursion
3228 (insert-file-contents bibfile)
3229 (bibtex-search-entry key)
3230 (bibtex-autokey-get-field "url"))))
3231 (doi (save-excursion
3233 (insert-file-contents bibfile)
3234 (bibtex-search-entry key)
3235 ;; I like this better than bibtex-url which does not always find
3237 (bibtex-autokey-get-field "doi"))))
3238 (candidates `(("Quit" . org-ref-citation-at-point)
3239 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3240 ;; for some reason, when there is no doi or url, they are returned as "". I
3241 ;; prefer nil so we correct this here.
3242 (when (string= doi "") (setq doi nil))
3243 (when (string= url "") (setq url nil))
3245 ;; Conditional pdf functions
3246 (if (file-exists-p pdf-file)
3249 '("Open pdf" . org-ref-open-pdf-at-point)
3253 '("Try to get pdf" . (lambda ()
3254 (save-window-excursion
3255 (org-ref-open-citation-at-point)
3256 (bibtex-beginning-of-entry)
3257 (doi-utils-get-bibtex-entry-pdf))))
3263 '("Open notes" . org-ref-open-notes-at-point)
3266 ;; conditional url and doi functions
3270 '("Open in browser" . org-ref-open-url-at-point)
3275 (add-to-list 'candidates x t))
3276 `(("WOS" . org-ref-wos-at-point)
3277 ("Related articles in WOS" . org-ref-wos-related-at-point)
3278 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3279 ("Google Scholar" . org-ref-google-scholar-at-point)
3280 ("Pubmed" . org-ref-pubmed-at-point)
3281 ("Crossref" . org-ref-crossref-at-point)
3286 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3291 '("Copy key to clipboard" . (lambda ()
3293 (car (org-ref-get-bibtex-key-and-file)))))
3298 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3303 '("Email bibtex entry and pdf" . (lambda ()
3305 (org-ref-open-citation-at-point)
3306 (email-bibtex-entry))))
3308 ;; finally return a numbered list of the candidates
3310 for cell in candidates
3311 collect (cons (format "%2s. %s" i (car cell))
3315 (defvar org-ref-helm-user-candidates '()
3316 "List of user-defined candidates to act when clicking on a cite link.
3317 This is a list of cons cells '((\"description\" . action)). The action function should not take an argument, and should assume point is on the cite key of interest.")
3319 ;; example of adding your own function
3321 'org-ref-helm-user-candidates
3322 '("Example" . (lambda () (message-box "You did it!")))
3326 (defun org-ref-cite-click-helm (key)
3327 "Open helm for actions on a cite link.
3330 1. get name and candidates before entering helm because we need
3333 2. switch back to the org buffer before evaluating the
3334 action. most of them need the point and buffer.
3336 KEY is returned for the selected item(s) in helm."
3338 (let ((name (org-ref-get-citation-string-at-point))
3339 (candidates (org-ref-cite-candidates))
3340 (cb (current-buffer)))
3342 (helm :sources `(((name . ,name)
3343 (candidates . ,candidates)
3344 (action . (lambda (f)
3345 (switch-to-buffer cb)
3347 ((name . "User functions")
3348 (candidates . ,org-ref-helm-user-candidates)
3349 (action . (lambda (f)
3350 (switch-to-buffer cb)
3354 ;; * Hydra menus in org-ref
3356 (when (featurep 'hydra)
3358 (setq hydra-is-helpful t)
3360 (defhydra org-ref-cite-hydra (:color blue)
3362 _p_: Open pdf _w_: WOS _g_: Google Scholar _K_: Copy citation to clipboard
3363 _u_: Open url _r_: WOS related _P_: Pubmed _k_: Copy key to clipboard
3364 _n_: Open notes _c_: WOS citing _C_: Crossref _f_: Copy bibtex entry to file
3365 _o_: Open entry _e_: Email entry and pdf
3367 ("o" org-ref-open-citation-at-point nil)
3368 ("p" org-ref-open-pdf-at-point nil)
3369 ("n" org-ref-open-notes-at-point nil)
3370 ("u" org-ref-open-url-at-point nil)
3371 ("w" org-ref-wos-at-point nil)
3372 ("r" org-ref-wos-related-at-point nil)
3373 ("c" org-ref-wos-citing-at-point nil)
3374 ("g" org-ref-google-scholar-at-point nil)
3375 ("P" org-ref-pubmed-at-point nil)
3376 ("C" org-ref-crossref-at-point nil)
3377 ("K" org-ref-copy-entry-as-summary nil)
3380 (car (org-ref-get-bibtex-key-and-file)))) nil)
3381 ("f" org-ref-copy-entry-at-point-to-file nil)
3383 ("e" (save-excursion
3384 (org-ref-open-citation-at-point)
3385 (email-bibtex-entry)) nil)))
3388 (defun org-ref-help ()
3389 "Open the org-ref manual."
3391 (find-file (expand-file-name
3393 (file-name-directory
3394 (find-library-name "org-ref")))))
3397 (defun org-ref-org-menu ()
3398 "Add org-ref menu to the Org menu."
3402 '( ["Insert citation" org-ref-helm-insert-cite-link]
3403 ["Insert ref" org-ref-helm-insert-ref-link]
3404 ["Insert label" org-ref-helm-insert-label-link]
3406 ["List of figures" org-ref-list-of-figures]
3407 ["List of tables" org-ref-list-of-tables]
3408 ["Extract bibtex entries" org-ref-extract-bibtex-entries]
3409 ["Check org-file" org-ref]
3411 ["Help" org-ref-help]
3412 ["Customize org-ref" (customize-group 'org-ref)])
3415 (easy-menu-change '("Org") "--" nil "Show/Hide"))
3417 (add-hook 'org-mode-hook 'org-ref-org-menu)
3422 ;;; org-ref.el ends here