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: ((dash) (helm) (helm-bibtex))
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 to where you will put all your notes about an entry in
52 the default bibliography."
56 (defcustom org-ref-default-bibliography
58 "list of bibtex files to search for. 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
130 the minibuffer just by putting the cursor in a link"
133 (defcustom org-ref-cite-types
134 '("cite" "nocite" ;; the default latex cite commands
135 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
136 "citet" "citet*" "citep" "citep*"
137 "citealt" "citealt*" "citealp" "citealp*"
139 "citeauthor" "citeauthor*"
140 "citeyear" "citeyear*"
141 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
143 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
145 "parencite" "Parencite"
146 "footcite" "footcitetext"
147 "textcite" "Textcite"
148 "smartcite" "Smartcite"
149 "cite*" "parencite*" "supercite"
150 "autocite" "Autocite" "autocite*" "Autocite*"
152 "citetitle" "citetitle*"
153 "citedate" "citedate*"
155 "fullcite" "footfullcite"
156 ;; "volcite" "Volcite" cannot support the syntax
157 "notecite" "Notecite"
158 "pnotecite" "Pnotecite"
160 ;; multicites. Very limited support for these.
161 "cites" "Cites" "parencites" "Parencites"
162 "footcites" "footcitetexts"
163 "smartcites" "Smartcites" "textcites" "Textcites"
164 "supercites" "autocites" "Autocites"
165 ;; for the bibentry package
168 "List of citation types known in org-ref"
169 :type '(repeat :tag "List of citation types" string)
172 (defcustom org-ref-clean-bibtex-entry-hook nil
173 "Hook that is run in org-ref-clean-bibtex-entry. The functions should take no arguments, and operate on the bibtex entry at point."
177 (defvar org-ref-bibliography-files
179 "variable to hold bibliography files to be searched")
181 ;; * org-mode / reftex setup
183 (defun org-mode-reftex-setup ()
184 (and (buffer-file-name)
185 (file-exists-p (buffer-file-name))
186 (global-auto-revert-mode t)
187 ;; I do not remember why I put this next line in. It doesn't
188 ;; work for org-files. Nothing very bad happens, but it gives
189 ;; an annoying error. Commenting it out for now.
192 (make-local-variable 'reftex-cite-format)
193 (setq reftex-cite-format 'org))
195 ;; define key for inserting citations
196 (define-key org-mode-map
197 (kbd org-ref-insert-cite-key)
198 org-ref-insert-cite-function)
200 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
202 (eval-after-load 'reftex-vars
204 (add-to-list 'reftex-cite-format-builtin
205 '(org "Org-mode citation"
206 ((?\C-m . "cite:%l") ; default
207 (?d . ",%l") ; for appending
213 (?h . "citeauthor:%l")
214 (?H . "citeauthor*:%l")
220 ;; * Messages for link at cursor
221 (defvar org-ref-message-timer nil
222 "Variable to store the link message timer in.")
225 (defun org-ref-show-link-messages ()
226 "Turn on link messages. You will see a message in the
227 minibuffer when on a cite, ref or label link."
229 (or org-ref-message-timer
230 (setq org-ref-message-timer
231 (run-with-idle-timer 0.5 t 'org-ref-link-message))))
234 (defun org-ref-cancel-link-messages ()
235 "Stop showing messages in minibuffer when on a link."
237 (cancel-timer org-ref-message-timer)
238 (setq org-ref-message-timer nil))
241 (when org-ref-show-citation-on-enter
242 (org-ref-show-link-messages))
244 ;; ** Messages for context under mouse pointer
246 (defvar org-ref-last-mouse-pos nil
247 "Stores last mouse position for use in `org-ref-mouse-message'.")
249 (defun org-ref-can-move-p ()
250 "See if a character is under the mouse. If so return the position for `goto-char'."
251 (let* ((line (cddr org-ref-last-mouse-pos))
252 (col (cadr org-ref-last-mouse-pos)))
254 (goto-char (window-start))
257 (> (- (line-end-position) (line-beginning-position)) col)
258 (progn (forward-char col) (point))
262 (defun org-ref-mouse-message ()
263 "Display message for link under mouse cursor"
265 (when (not (equal (mouse-position) org-ref-last-mouse-pos))
266 (setq org-ref-last-mouse-pos (mouse-position))
267 (let ((p (org-ref-can-move-p)))
271 (org-ref-link-message))))))
274 (defvar org-ref-message-timer-mouse nil
275 "Store mouse timer.")
278 (defvar org-ref-mouse-message-interval 0.5
279 "How often to run the mouse message timer in seconds")
282 (defun org-ref-mouse-messages-on ()
283 "Turn on mouse messages."
285 (or org-ref-message-timer-mouse
286 (setq org-ref-message-timer-mouse
287 (run-at-time "0.5 sec"
288 org-ref-mouse-message-interval
289 'org-ref-mouse-message))))
292 (defun org-ref-mouse-messages-off ()
293 "Turn off mouse messages"
295 (cancel-timer org-ref-message-timer-mouse)
296 (setq org-ref-message-timer-mouse nil)
297 (message "Mouse messages are off"))
299 ;; Colorizing org-ref links
300 (defcustom org-ref-colorize-links
302 "When non-nil, change colors of links"
306 (defcustom org-ref-cite-color
308 "Color of cite like links"
312 (defcustom org-ref-ref-color
314 "Color of ref like links"
318 (defcustom org-ref-label-color
320 "Color of label links"
324 (defvar org-ref-cite-re nil
325 "regexp for cite links")
328 (setq org-ref-cite-re
329 (concat "\\(" (mapconcat
331 (replace-regexp-in-string "\*" "\\\\*" x)
333 org-ref-cite-types "\\|") "\\)"
334 ":\\([a-zA-Z0-9-_:]*,?\\)*"))
337 (setq org-ref-label-re
338 "label:\\([a-zA-Z0-9-_:]*,?\\)*")
342 "ref:\\([a-zA-Z0-9-_:]*,?\\)*")
345 (defface org-ref-cite-face
346 `((t (:inherit org-link :foreground ,org-ref-cite-color)))
347 "Color for cite-like links in org-ref.")
350 (defface org-ref-label-face
351 `((t (:inherit org-link :foreground ,org-ref-label-color)))
352 "Color for ref links in org-ref.")
355 (defface org-ref-ref-face
356 `((t (:inherit org-link :foreground ,org-ref-ref-color)))
357 "Face for ref links in org-ref.")
360 (defun org-ref-colorize-links ()
361 "Colorize org-ref links."
363 (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
364 (highlight-regexp org-ref-label-re 'org-ref-label-face)
365 (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
368 (when org-ref-colorize-links
369 (add-hook 'org-mode-hook 'org-ref-colorize-links))
371 ;; * General org-ref utilities
372 (defun org-ref-strip-string (string)
373 "strip leading and trailing whitespace from the string"
374 (replace-regexp-in-string
375 (concat search-whitespace-regexp "$" ) ""
376 (replace-regexp-in-string
377 (concat "^" search-whitespace-regexp ) "" string)))
379 (defun org-ref-split-and-strip-string (string)
380 "split key-string and strip keys. Assumes the key-string is comma delimited"
381 (mapcar 'org-ref-strip-string (split-string string ",")))
383 (defun org-ref-reftex-get-bib-field (field entry &optional format)
384 "similar to reftex-get-bib-field, but removes enclosing braces and quotes"
386 (setq result (reftex-get-bib-field field entry format))
387 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
388 (setq result (substring result 1 -1)))
389 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
390 (setq result (substring result 1 -1)))
393 (defun org-ref-reftex-format-citation (entry format)
394 "return a formatted string for the bibtex entry (from bibtex-parse-entry) according
395 to the format argument. The format is a string with these percent escapes.
397 In the format, the following percent escapes will be expanded.
399 %l The BibTeX label of the citation.
400 %a List of author names, see also `reftex-cite-punctuation'.
401 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
402 %A First author name only.
403 %e Works like %a, but on list of editor names. (%2e and %E work a well)
405 It is also possible to access all other BibTeX database fields:
406 %b booktitle %c chapter %d edition %h howpublished
407 %i institution %j journal %k key %m month
408 %n number %o organization %p pages %P first page
409 %r address %s school %u publisher %t title
411 %B booktitle, abbreviated %T title, abbreviated
416 Usually, only %l is needed. The other stuff is mainly for the echo area
417 display, and for (setq reftex-comment-citations t).
419 %< as a special operator kills punctuation and space around it after the
420 string has been formatted.
422 A pair of square brackets indicates an optional argument, and RefTeX
423 will prompt for the values of these arguments.
425 Beware that all this only works with BibTeX database files. When
426 citations are made from the \bibitems in an explicit thebibliography
427 environment, only %l is available."
428 ;; Format a citation from the info in the BibTeX ENTRY
430 (unless (stringp format) (setq format "\\cite{%l}"))
432 (if (and reftex-comment-citations
433 (string-match "%l" reftex-cite-comment-format))
434 (error "reftex-cite-comment-format contains invalid %%l"))
437 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
439 (let ((n (string-to-number (match-string 4 format)))
440 (l (string-to-char (match-string 5 format)))
446 (org-ref-reftex-get-bib-field "&key" entry)
447 (if reftex-comment-citations
448 reftex-cite-comment-format
450 ((= l ?a) (reftex-format-names
451 (reftex-get-bib-names "author" entry)
453 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
454 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
455 ((= l ?B) (reftex-abbreviate-title
456 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
457 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
458 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
459 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
460 ((= l ?e) (reftex-format-names
461 (reftex-get-bib-names "editor" entry)
463 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
464 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
465 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
466 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
467 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
468 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
469 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
470 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
471 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
472 ((= l ?P) (car (split-string
473 (org-ref-reftex-get-bib-field "pages" entry)
475 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
476 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
477 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
478 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
479 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
480 ;; strip enclosing brackets from title if they are there
481 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
482 ((= l ?T) (reftex-abbreviate-title
483 (org-ref-reftex-get-bib-field "title" entry)))
484 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
485 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
488 (setq b (match-beginning 2) e (match-end 2))
489 (setq b (match-beginning 3) e (match-end 3)))
490 (setq format (concat (substring format 0 b) rpl (substring format e)))))
491 (while (string-match "%%" format)
492 (setq format (replace-match "%" t t format)))
493 (while (string-match "[ ,.;:]*%<" format)
494 (setq format (replace-match "" t t format)))
495 ;; also replace carriage returns, tabs, and multiple whitespaces
496 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
499 (defun org-ref-get-bibtex-entry-citation (key)
500 "returns a string for the bibliography entry corresponding to key, and formatted according to the type in `org-ref-bibliography-entry-format'"
502 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
503 (file) (entry) (bibtex-entry) (entry-type) (format))
505 (setq file (catch 'result
506 (loop for file in org-ref-bibliography-files do
507 (if (org-ref-key-in-file-p key (file-truename file))
509 (message "%s not found in %s" key (file-truename file))))))
512 (insert-file-contents file)
513 (bibtex-search-entry key nil 0)
514 (setq bibtex-entry (bibtex-parse-entry))
515 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
516 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
518 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
520 (bibtex-narrow-to-entry)
521 (setq entry (buffer-string)))))
524 (defun org-ref-get-bibtex-keys ()
525 "Return a list of unique keys in the buffer."
527 (org-element-map (org-element-parse-buffer) 'link
529 (let ((plist (nth 1 link)))
530 (when (-contains? org-ref-cite-types (plist-get plist ':type))
533 (org-ref-split-and-strip-string (plist-get plist ':path)))
534 (when (not (-contains? keys key))
535 (setq keys (append keys (list key))))))))
536 ;; set with-affiliated to get keys in captions
538 ;; Sort keys alphabetically
539 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
542 (defun org-ref-get-bibtex-entry-html (key)
543 "returns an html string for the bibliography entry corresponding to key"
545 (format "<li><a id=\"%s\">[%s] %s</a></li>" key key (org-ref-get-bibtex-entry-citation key)))
547 (defun org-ref-get-html-bibliography ()
548 "Create an html bibliography when there are keys"
549 (let ((keys (org-ref-get-bibtex-keys)))
551 (concat "<h1>Bibliography</h1>
553 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
556 (defun org-ref-get-bibtex-entry-org (key)
557 "returns an org string for the bibliography entry corresponding to key"
558 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
559 (file) (entry) (bibtex-entry) (entry-type) (format))
561 (setq file (catch 'result
562 (loop for file in org-ref-bibliography-files do
563 (if (org-ref-key-in-file-p key (file-truename file))
565 (message "%s not found in %s" key (file-truename file))))))
568 (insert-file-contents file)
569 (bibtex-search-entry key nil 0)
570 (setq entry (bibtex-parse-entry))
575 " (org-ref-reftex-get-bib-field "author" entry)
576 (org-ref-reftex-get-bib-field "title" entry)
577 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
578 (mapconcat (lambda (element) (format " :%s: %s"
579 (upcase (car element))
584 (defun org-ref-get-org-bibliography ()
585 "Create an org bibliography when there are keys"
586 (let ((keys (org-ref-get-bibtex-keys)))
588 (concat "* Bibliography
590 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
593 (defun org-ref-get-bibtex-entry-ascii (key)
594 "returns an ascii string for the bibliography entry corresponding to key"
596 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
598 (defun org-ref-get-ascii-bibliography ()
599 "Create an html bibliography when there are keys"
600 (let ((keys (org-ref-get-bibtex-keys)))
606 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
610 ;; ** bibliography and bibliographystyle
611 (org-add-link-type "bibliography"
612 ;; this code is run on clicking. The bibliography
613 ;; may contain multiple files. this code finds the
614 ;; one you clicked on and opens it.
615 (lambda (link-string)
616 ;; get link-string boundaries
617 ;; we have to go to the beginning of the line, and then search forward
620 ;; object is the link you clicked on
621 (object (org-element-context))
622 (link-string-beginning)
626 (goto-char (org-element-property :begin object))
627 (search-forward link-string nil nil 1)
628 (setq link-string-beginning (match-beginning 0))
629 (setq link-string-end (match-end 0)))
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)
636 (split-string (org-element-property :path object) ","))
638 ;; now if we have comma separated bibliographies
639 ;; we find the one clicked on. we want to
640 ;; search forward to next comma from point
642 (if (search-forward "," link-string-end 1 1)
643 (setq key-end (- (match-end 0) 1)) ; we found a match
644 (setq key-end (point)))) ; no comma found so take the point
645 ;; and backward to previous comma from point
647 (if (search-backward "," link-string-beginning 1 1)
648 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
649 (setq key-beginning (point)))) ; no match found
650 ;; save the key we clicked on.
651 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
652 (find-file bibfile))) ; open file on click
655 (lambda (keyword desc format)
657 ((eq format 'org) (org-ref-get-org-bibliography))
658 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
659 ((eq format 'html) (org-ref-get-html-bibliography))
661 ;; write out the latex bibliography command
662 (format "\\bibliography{%s}" (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
663 (mapcar 'expand-file-name
664 (split-string keyword ","))
667 (org-add-link-type "nobibliography"
668 ;; this code is run on clicking. The bibliography
669 ;; may contain multiple files. this code finds the
670 ;; one you clicked on and opens it.
671 (lambda (link-string)
672 ;; get link-string boundaries
673 ;; we have to go to the beginning of the line, and then search forward
676 ;; object is the link you clicked on
677 (object (org-element-context))
679 (link-string-beginning)
683 (goto-char (org-element-property :begin object))
684 (search-forward link-string nil nil 1)
685 (setq link-string-beginning (match-beginning 0))
686 (setq link-string-end (match-end 0)))
688 ;; We set the reftex-default-bibliography
689 ;; here. it should be a local variable only in
690 ;; the current buffer. We need this for using
691 ;; reftex to do citations.
692 (set (make-local-variable 'reftex-default-bibliography)
693 (split-string (org-element-property :path object) ","))
695 ;; now if we have comma separated bibliographies
696 ;; we find the one clicked on. we want to
697 ;; search forward to next comma from point
699 (if (search-forward "," link-string-end 1 1)
700 (setq key-end (- (match-end 0) 1)) ; we found a match
701 (setq key-end (point)))) ; no comma found so take the point
702 ;; and backward to previous comma from point
704 (if (search-backward "," link-string-beginning 1 1)
705 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
706 (setq key-beginning (point)))) ; no match found
707 ;; save the key we clicked on.
708 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
709 (find-file bibfile))) ; open file on click
712 (lambda (keyword desc format)
714 ((eq format 'org) (org-ref-get-org-bibliography))
715 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
716 ((eq format 'html) (org-ref-get-html-bibliography))
718 ;; write out the latex bibliography command
720 ; (format "{\\setbox0\\vbox{\\bibliography{%s}}}"
721 ; (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
722 ; (mapcar 'expand-file-name
723 ; (split-string keyword ","))
726 (format "\\nobibliography{%s}"
727 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
728 (mapcar 'expand-file-name
729 (split-string keyword ","))
734 (org-add-link-type "printbibliography"
735 (lambda (arg) (message "Nothing implemented for clicking here."))
736 (lambda (keyword desc format)
738 ((eq format 'org) (org-ref-get-org-bibliography))
739 ((eq format 'html) (org-ref-get-html-bibliography))
741 ;; write out the biblatex bibliography command
742 "\\printbibliography"))
745 (org-add-link-type "bibliographystyle"
746 (lambda (arg) (message "Nothing implemented for clicking here."))
747 (lambda (keyword desc format)
750 ;; write out the latex bibliography command
751 (format "\\bibliographystyle{%s}" keyword)))))
753 (defun org-bibliography-complete-link (&optional arg)
754 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
756 (defun org-ref-insert-bibliography-link ()
757 "insert a bibliography with completion"
759 (insert (org-bibliography-complete-link)))
763 (org-add-link-type "addbibresource"
764 ;; this code is run on clicking. The addbibresource
765 ;; may contain multiple files. this code finds the
766 ;; one you clicked on and opens it.
767 (lambda (link-string)
768 ;; get link-string boundaries
769 ;; we have to go to the beginning of the line, and then search forward
772 ;; object is the link you clicked on
773 (object (org-element-context))
775 (link-string-beginning)
779 (goto-char (org-element-property :begin object))
780 (search-forward link-string nil nil 1)
781 (setq link-string-beginning (match-beginning 0))
782 (setq link-string-end (match-end 0)))
784 ;; We set the reftex-default-addbibresource
785 ;; here. it should be a local variable only in
786 ;; the current buffer. We need this for using
787 ;; reftex to do citations.
788 (set (make-local-variable 'reftex-default-addbibresource)
789 (split-string (org-element-property :path object) ","))
791 ;; now if we have comma separated bibliographies
792 ;; we find the one clicked on. we want to
793 ;; search forward to next comma from point
795 (if (search-forward "," link-string-end 1 1)
796 (setq key-end (- (match-end 0) 1)) ; we found a match
797 (setq key-end (point)))) ; no comma found so take the point
798 ;; and backward to previous comma from point
800 (if (search-backward "," link-string-beginning 1 1)
801 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
802 (setq key-beginning (point)))) ; no match found
803 ;; save the key we clicked on.
804 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
805 (find-file bibfile))) ; open file on click
808 (lambda (keyword desc format)
810 ((eq format 'html) (format "")); no output for html
812 ;; write out the latex addbibresource command
813 (format "\\addbibresource{%s}" keyword)))))
815 ;; ** List of figures
816 (defun org-ref-list-of-figures (&optional arg)
817 "Generate buffer with list of figures in them"
819 (save-excursion (widen)
820 (let* ((c-b (buffer-name))
823 (org-element-map (org-element-parse-buffer) 'link
825 "create a link for to the figure"
827 (and (string= (org-element-property :type link) "file")
829 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
830 (org-element-property :path link)))
833 (let* ((start (org-element-property :begin link))
834 (parent (car (cdr (org-element-property :parent link))))
835 (caption (caaar (plist-get parent :caption)))
836 (name (plist-get parent :name)))
839 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
840 c-b start counter (or name "") caption)
842 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
843 c-b start counter (or name "")))))))))
844 (switch-to-buffer "*List of Figures*")
845 (setq buffer-read-only nil)
848 (insert (mapconcat 'identity list-of-figures ""))
849 (setq buffer-read-only t)
850 (use-local-map (copy-keymap org-mode-map))
851 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
855 'org-ref-list-of-figures ; on click
856 (lambda (keyword desc format)
859 (format "\\listoffigures")))))
862 (defun org-ref-list-of-tables (&optional arg)
863 "Generate a buffer with a list of tables"
867 (let* ((c-b (buffer-name))
870 (org-element-map (org-element-parse-buffer 'element) 'table
872 "create a link for to the table"
874 (let ((start (org-element-property :begin table))
875 (name (org-element-property :name table))
876 (caption (caaar (org-element-property :caption table))))
879 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
880 c-b start counter (or name "") caption)
882 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
883 c-b start counter (or name ""))))))))
884 (switch-to-buffer "*List of Tables*")
885 (setq buffer-read-only nil)
888 (insert (mapconcat 'identity list-of-tables ""))
889 (setq buffer-read-only t)
890 (use-local-map (copy-keymap org-mode-map))
891 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
895 'org-ref-list-of-tables
896 (lambda (keyword desc format)
899 (format "\\listoftables")))))
901 (defun org-ref-count-labels (label)
902 "Counts number of matches for label in the document"
903 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
904 ;; for tblname, it is not enough to get word boundary
905 ;; tab-little and tab-little-2 match then.
906 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
907 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
908 ;; this is the org-format #+label:
909 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
910 (let ((custom-id-count 0))
913 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
914 (setq custom-id-count (+ 1 custom-id-count)))))
921 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
922 (let ((count (org-ref-count-labels label)))
923 (message (format "%s occurence%s"
929 (org-ref-count-labels label))))
930 (lambda (keyword desc format)
932 ((eq format 'html) (format "(<label>%s</label>)" path))
934 (format "\\label{%s}" keyword)))))
936 (defun org-label-store-link ()
937 "store a link to a label. The output will be a ref to that label"
938 ;; First we have to make sure we are on a label link.
939 (let* ((object (org-element-context)))
940 (when (and (equal (org-element-type object) 'link)
941 (equal (org-element-property :type object) "label"))
942 (org-store-link-props
944 :link (concat "ref:" (org-element-property :path object))))
946 ;; Store link on table
947 (when (equal (org-element-type object) 'table)
948 (org-store-link-props
950 :link (concat "ref:" (org-element-property :name object))))
952 ;; it turns out this does not work. you can already store a link to a heading with a CUSTOM_ID
953 ;; store link on heading with custom_id
954 ; (when (and (equal (org-element-type object) 'headline)
955 ; (org-entry-get (point) "CUSTOM_ID"))
956 ; (org-store-link-props
958 ; :link (concat "ref:" (org-entry-get (point) "CUSTOM_ID"))))
960 ;; and to #+label: lines
961 (when (and (equal (org-element-type object) 'paragraph)
962 (org-element-property :name object))
963 (org-store-link-props
965 :link (concat "ref:" (org-element-property :name object))))
968 (add-hook 'org-store-link-functions 'org-label-store-link)
974 "on clicking goto the label. Navigate back with C-c &"
976 ;; next search from beginning of the buffer
978 ;; it is possible you would not find the label if narrowing is in effect
985 (goto-char (point-min))
986 (re-search-forward (format "label:%s\\b" label) nil t))
990 (goto-char (point-min))
991 (re-search-forward (format "\\label{%s}" label) nil t))
993 ;; #+label: name org-definition
995 (goto-char (point-min))
996 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1000 (goto-char (point-min))
1001 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1003 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1004 ;; you need [[#label]] links.
1007 ; (goto-char (point-min))
1008 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1010 ;; we did not find anything, so go back to where we came
1011 (org-mark-ring-goto)
1012 (error "%s not found" label))
1014 (message "go back with (org-mark-ring-goto) `C-c &`"))
1016 (lambda (keyword desc format)
1018 ((eq format 'html) (format "(<ref>%s</ref>)" path))
1020 (format "\\ref{%s}" keyword)))))
1022 (defun org-ref-get-org-labels ()
1023 "Return a list of #+LABEL: labels."
1025 (goto-char (point-min))
1026 (let ((matches '()))
1027 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1028 (add-to-list 'matches (match-string-no-properties 1) t))
1031 (defun org-ref-get-custom-ids ()
1032 "Return a list of custom_id properties in the buffer."
1033 (let ((results '()) custom_id)
1036 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1037 (when (not (null custom_id))
1038 (setq results (append results (list custom_id)))))))
1041 (defun org-ref-get-latex-labels ()
1043 (goto-char (point-min))
1044 (let ((matches '()))
1045 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1046 (add-to-list 'matches (match-string-no-properties 1) t))
1049 (defun org-ref-get-tblnames ()
1050 "Return list of table names in the buffer."
1051 (org-element-map (org-element-parse-buffer 'element) 'table
1053 (org-element-property :name table))))
1055 (defun org-ref-get-labels ()
1056 "Returns a list of labels in the buffer that you can make a ref link to.
1057 This is used to auto-complete ref links and in helm menus."
1061 (goto-char (point-min))
1062 (let ((matches '()))
1063 ;; these are the label:stuff kinds
1064 (while (re-search-forward "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1065 (add-to-list 'matches (match-string-no-properties 1) t))
1067 (org-ref-get-org-labels)
1068 (org-ref-get-latex-labels)
1069 (org-ref-get-tblnames)
1070 (org-ref-get-custom-ids))))))
1072 (defun org-ref-helm-insert-label-link ()
1073 "Insert a label link. helm just shows you what labels already exist.
1074 If you are on a label link, replace it."
1076 (let* ((labels (org-ref-get-labels))
1077 (cb (current-buffer)))
1078 (helm :sources `(((name . "Existing labels")
1079 (candidates . ,labels)
1080 ;; default action is to open to the label
1081 (action . (lambda (label)
1082 ;; unfortunately I do not have markers here
1083 (org-open-link-from-string (format "ref:%s" label))))
1084 ;; if you select a label, replace current one
1085 (action . (lambda (label)
1086 (switch-to-buffer ,cb)
1088 ;; no prefix or on a link
1089 ((equal helm-current-prefix-arg nil)
1090 (let* ((object (org-element-context))
1091 (last-char (save-excursion
1092 (goto-char (org-element-property :end object))
1094 (if (looking-at " ")
1097 (when (-contains? '("label")
1098 (org-element-property :type object))
1099 ;; we are on a link, so replace it.
1102 (org-element-property :begin object)
1103 (org-element-property :end object))
1105 (replace-regexp-in-string
1106 (org-element-property :path object)
1108 (org-element-property :raw-link object))
1110 ;; no prefix options defined
1112 ;; no matching selection creates a new label
1113 ((name . "Create new label")
1115 ;; default action creates a new label, or replaces old one
1116 (action . (lambda (label)
1117 (switch-to-buffer ,cb)
1118 (let* ((object (org-element-context))
1119 (last-char (save-excursion
1120 (goto-char (org-element-property :end object))
1122 (if (looking-at " ")
1125 (if (-contains? '("label")
1126 (org-element-property :type object))
1127 ;; we are on a link, so replace it.
1130 (org-element-property :begin object)
1131 (org-element-property :end object))
1133 (replace-regexp-in-string
1134 (org-element-property :path object)
1136 (org-element-property :raw-link object))
1143 helm-pattern))))))))))))
1145 (defun org-ref-complete-link (&optional arg)
1146 "Completion function for ref links"
1148 (setq label (completing-read "label: " (org-ref-get-labels)))
1149 (format "ref:%s" label)))
1151 (defun org-ref-insert-ref-link ()
1153 (insert (org-ref-complete-link)))
1155 (defun org-ref-helm-insert-ref-link ()
1156 "Helm menu to insert ref links to labels in the document.
1157 If you are on link, replace with newly selected label.
1158 Use C-u to insert a different kind of ref link.
1159 Use C-u C-u to insert a [[#custom-id]] link
1162 (let* ((labels (org-ref-get-labels))
1163 (bs (buffer-string))
1164 (contexts (with-temp-buffer
1166 (mapcar 'org-ref-get-label-context labels)))
1167 (cb (current-buffer)))
1169 (helm :input (thing-at-point 'word)
1170 :sources `(((name . "Available labels to ref")
1171 (candidates . ,(loop for label in labels
1172 for context in contexts
1173 ;; we do some kludgy adding spaces
1174 ;; and bars to make it "easier" to
1176 collect (cons (concat
1181 (split-string context "\n")
1184 ;; default action to replace or insert ref link.
1185 (action . (lambda (label)
1186 (switch-to-buffer ,cb)
1189 ;; no prefix or on a link
1190 ((equal helm-current-prefix-arg nil)
1191 (let* ((object (org-element-context))
1192 (last-char (save-excursion
1193 (goto-char (org-element-property :end object))
1195 (if (looking-at " ")
1198 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1199 (org-element-property :type object))
1200 ;; we are on a link, so replace it.
1203 (org-element-property :begin object)
1204 (org-element-property :end object))
1206 (replace-regexp-in-string
1207 (org-element-property :path object)
1209 (org-element-property :raw-link object))
1211 ;; insert a new link
1216 ;; one prefix, alternate ref link
1217 ((equal helm-current-prefix-arg '(4))
1220 (helm :sources '((name . "Ref link types")
1221 (candidates . ("ref" "eqref" "pageref" "nameref"))
1222 (action . (lambda (x) x))))
1224 ;; two prefixes, insert section custom-id link
1225 ((equal helm-current-prefix-arg '(16))
1227 (format "[[#%s]]" label)))
1235 "on clicking goto the label. Navigate back with C-c &"
1236 (org-mark-ring-push)
1237 ;; next search from beginning of the buffer
1243 (goto-char (point-min))
1244 (re-search-forward (format "label:%s\\b" label) nil t))
1248 (goto-char (point-min))
1249 (re-search-forward (format "\\label{%s}" label) nil t))
1251 ;; #+label: name org-definition
1253 (goto-char (point-min))
1254 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1258 (goto-char (point-min))
1259 (re-search-forward (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t))
1261 ;; Commented out because these ref links do not actually translate correctly in LaTeX.
1262 ;; you need [[#label]] links.
1265 ; (goto-char (point-min))
1266 ; (re-search-forward (format ":CUSTOM_ID:\s-*\\(%s\\)" label) nil t))
1268 ;; we did not find anything, so go back to where we came
1269 (org-mark-ring-goto)
1270 (error "%s not found" label))
1271 (message "go back with (org-mark-ring-goto) `C-c &`"))
1273 (lambda (keyword desc format)
1275 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1277 (format "\\pageref{%s}" keyword)))))
1279 (defun org-pageref-complete-link (&optional arg)
1280 "Completion function for ref links"
1282 (setq label (completing-read "label: " (org-ref-get-labels)))
1283 (format "ref:%s" label)))
1285 (defun org-pageref-insert-ref-link ()
1287 (insert (org-pageref-complete-link)))
1293 "on clicking goto the label. Navigate back with C-c &"
1294 (org-mark-ring-push)
1295 ;; next search from beginning of the buffer
1301 (goto-char (point-min))
1302 (re-search-forward (format "\\label{%s}" label) nil t))
1304 ;; we did not find anything, so go back to where we came
1305 (org-mark-ring-goto)
1306 (error "%s not found" label))
1307 (message "go back with (org-mark-ring-goto) `C-c &`"))
1309 (lambda (keyword desc format)
1311 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1313 (format "\\nameref{%s}" keyword)))))
1320 "on clicking goto the label. Navigate back with C-c &"
1321 (org-mark-ring-push)
1322 ;; next search from beginning of the buffer
1324 (goto-char (point-min))
1327 ;; search forward for the first match
1329 (re-search-forward (format "label:%s" label) nil t)
1331 (re-search-forward (format "\\label{%s}" label) nil t)
1332 ;; #+label: name org-definition
1333 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1334 (org-mark-ring-goto)
1335 (error "%s not found" label))
1336 (message "go back with (org-mark-ring-goto) `C-c &`"))
1338 (lambda (keyword desc format)
1340 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1342 (format "\\eqref{%s}" keyword)))))
1346 (defun org-ref-get-bibtex-key-under-cursor ()
1347 "returns key under the bibtex cursor. We search forward from
1348 point to get a comma, or the end of the link, and then backwards
1349 to get a comma, or the beginning of the link. that delimits the
1350 keyword we clicked on. We also strip the text properties."
1351 (let* ((object (org-element-context))
1352 (link-string (org-element-property :path object)))
1353 ;; you may click on the part before the citations. here we make
1354 ;; sure to move to the beginning so you get the first citation.
1356 (goto-char (org-element-property :begin object))
1357 (search-forward link-string (org-element-property :end object))
1358 (goto-char (match-beginning 0))
1359 ;; check if we clicked before the path and move as needed.
1360 (unless (< cp (point))
1363 (if (not (org-element-property :contents-begin object))
1364 ;; this means no description in the link
1366 ;; we need the link path start and end
1368 (goto-char (org-element-property :begin object))
1369 (search-forward link-string nil nil 1)
1370 (setq link-string-beginning (match-beginning 0))
1371 (setq link-string-end (match-end 0)))
1373 ;; The key is the text between commas, or the link boundaries
1375 (if (search-forward "," link-string-end t 1)
1376 (setq key-end (- (match-end 0) 1)) ; we found a match
1377 (setq key-end link-string-end))) ; no comma found so take the end
1378 ;; and backward to previous comma from point which defines the start character
1380 (if (search-backward "," link-string-beginning 1 1)
1381 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1382 (setq key-beginning link-string-beginning))) ; no match found
1383 ;; save the key we clicked on.
1384 (setq bibtex-key (org-ref-strip-string (buffer-substring key-beginning key-end)))
1385 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1387 ;; link with description. assume only one key
1390 (defun org-ref-find-bibliography ()
1391 "find the bibliography in the buffer.
1392 This function sets and returns cite-bibliography-files, which is a list of files
1393 either from bibliography:f1.bib,f2.bib
1394 \bibliography{f1,f2}
1395 internal bibliographies
1397 falling back to what the user has set in org-ref-default-bibliography
1401 (goto-char (point-min))
1402 ;; look for a bibliography link
1403 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1404 (setq org-ref-bibliography-files
1405 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1406 (throw 'result org-ref-bibliography-files))
1409 ;; we did not find a bibliography link. now look for \bibliography
1410 (goto-char (point-min))
1411 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1412 ;; split, and add .bib to each file
1413 (setq org-ref-bibliography-files
1414 (mapcar (lambda (x) (concat x ".bib"))
1415 (mapcar 'org-ref-strip-string
1416 (split-string (match-string 1) ","))))
1417 (throw 'result org-ref-bibliography-files))
1419 ;; no bibliography found. maybe we need a biblatex addbibresource
1420 (goto-char (point-min))
1421 ;; look for a bibliography link
1422 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1423 (setq org-ref-bibliography-files
1424 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1425 (throw 'result org-ref-bibliography-files))
1427 ;; we did not find anything. use defaults
1428 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1430 ;; set reftex-default-bibliography so we can search
1431 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1432 org-ref-bibliography-files)
1434 (defun org-ref-key-in-file-p (key filename)
1435 "determine if the key is in the file"
1436 (save-current-buffer
1437 (let ((bibtex-files (list filename)))
1438 ;; This is something I am trying because when the bibtex file is open, and
1439 ;; you have added to it, the only way I find to get the update to update
1440 ;; is to close it and reopen it. or to save it and revert it.
1441 (when (get-file-buffer filename)
1442 (set-buffer (get-file-buffer filename))
1444 (revert-buffer t t))
1445 (bibtex-search-entry key t))))
1447 (defun org-ref-get-bibtex-key-and-file (&optional key)
1448 "returns the bibtex key and file that it is in. If no key is provided, get one under point"
1449 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1452 (setq key (org-ref-get-bibtex-key-under-cursor)))
1453 (setq file (catch 'result
1454 (loop for file in org-ref-bibliography-files do
1455 (if (org-ref-key-in-file-p key (file-truename file))
1456 (throw 'result file)))))
1459 ;; *** key at point functions
1461 (defun org-ref-open-pdf-at-point ()
1462 "open the pdf for bibtex key under point if it exists"
1464 (let* ((results (org-ref-get-bibtex-key-and-file))
1466 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1467 (if (file-exists-p pdf-file)
1468 (org-open-file pdf-file)
1469 (message "no pdf found for %s" key))))
1472 (defun org-ref-open-url-at-point ()
1473 "open the url for bibtex key under point."
1475 (let* ((results (org-ref-get-bibtex-key-and-file))
1477 (bibfile (cdr results)))
1480 (insert-file-contents bibfile)
1481 (bibtex-search-entry key)
1482 ;; I like this better than bibtex-url which does not always find
1485 (let ((url (bibtex-autokey-get-field "url")))
1487 (browse-url (s-trim url))
1490 (let ((doi (bibtex-autokey-get-field "doi")))
1492 (if (string-match "^http" doi)
1494 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1495 (throw 'done nil))))))))
1498 (defun org-ref-open-notes-at-point ()
1499 "open the notes for bibtex key under point."
1501 (let* ((results (org-ref-get-bibtex-key-and-file))
1503 (bibfile (cdr results)))
1506 (insert-file-contents bibfile)
1507 (bibtex-search-entry key)
1508 (org-ref-open-bibtex-notes)))))
1511 (defun org-ref-citation-at-point ()
1512 "give message of current citation at point"
1514 (let* ((cb (current-buffer))
1515 (results (org-ref-get-bibtex-key-and-file))
1517 (bibfile (cdr results)))
1518 (message "%s" (progn
1520 (insert-file-contents bibfile)
1521 (bibtex-search-entry key)
1522 (org-ref-bib-citation))))))
1525 (defun org-ref-open-citation-at-point ()
1526 "open bibtex file to key at point"
1528 (let* ((cb (current-buffer))
1529 (results (org-ref-get-bibtex-key-and-file))
1531 (bibfile (cdr results)))
1533 (bibtex-search-entry key)))
1537 (defvar org-ref-cite-menu-funcs '()
1538 "Functions to run on cite click menu. Each entry is a list of (key menu-name function).
1539 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.")
1542 (defvar org-ref-user-cite-menu-funcs
1543 '(("C" "rossref" org-ref-crossref-at-point)
1544 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1545 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1546 "user-defined functions to run on bibtex key at point.")
1549 (defun org-ref-copy-entry-as-summary ()
1550 "Copy the bibtex entry for the citation at point as a summary."
1552 (save-window-excursion
1553 (org-ref-open-citation-at-point)
1554 (kill-new (org-ref-bib-citation))))
1557 (defun org-ref-copy-entry-at-point-to-file ()
1558 "Copy the bibtex entry for the citation at point to NEW-FILE.
1559 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."
1561 (let ((new-file (ido-completing-read
1563 (append org-ref-default-bibliography
1564 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1565 (key (org-ref-get-bibtex-key-under-cursor)))
1566 (save-window-excursion
1567 (org-ref-open-citation-at-point)
1568 (bibtex-copy-entry-as-kill))
1570 (let ((bibtex-files (list (file-truename new-file))))
1571 (if (assoc key (bibtex-global-key-alist))
1572 (message "That key already exists in %s" new-file)
1574 (save-window-excursion
1575 (find-file new-file)
1576 (goto-char (point-max))
1577 ;; make sure we are at the beginning of a line.
1578 (unless (looking-at "^") (insert "\n\n"))
1583 (defun org-ref-get-doi-at-point ()
1584 "Get doi for key at point."
1585 (let* ((results (org-ref-get-bibtex-key-and-file))
1587 (bibfile (cdr results))
1591 (insert-file-contents bibfile)
1592 (bibtex-search-entry key)
1593 (setq doi (bibtex-autokey-get-field "doi"))
1594 ;; in case doi is a url, remove the url part.
1595 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1598 ;; **** functions that operate on key at point for click menu
1599 (defun org-ref-wos-at-point ()
1600 "open the doi in wos for bibtex key under point."
1602 (doi-utils-wos (org-ref-get-doi-at-point)))
1605 (defun org-ref-wos-citing-at-point ()
1606 "open the doi in wos citing articles for bibtex key under point."
1608 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1611 (defun org-ref-wos-related-at-point ()
1612 "open the doi in wos related articles for bibtex key under point."
1614 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1617 (defun org-ref-google-scholar-at-point ()
1618 "open the doi in google scholar for bibtex key under point."
1620 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1623 (defun org-ref-pubmed-at-point ()
1624 "open the doi in pubmed for bibtex key under point."
1626 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1629 (defun org-ref-crossref-at-point ()
1630 "open the doi in crossref for bibtex key under point."
1632 (doi-utils-crossref (org-ref-get-doi-at-point)))
1634 ;; *** Minibuffer menu
1636 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1637 "action when a cite link is clicked on.
1638 Provides a menu of context sensitive actions. If the bibtex entry has a pdf, you get an option to open it. If there is a doi, you get a lot of options."
1640 (let* ((results (org-ref-get-bibtex-key-and-file))
1642 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1643 (bibfile (cdr results))
1644 (url (save-excursion
1646 (insert-file-contents bibfile)
1647 (bibtex-search-entry key)
1648 (bibtex-autokey-get-field "url"))))
1649 (doi (save-excursion
1651 (insert-file-contents bibfile)
1652 (bibtex-search-entry key)
1653 ;; I like this better than bibtex-url which does not always find
1655 (bibtex-autokey-get-field "doi")))))
1657 (when (string= "" doi) (setq doi nil))
1658 (when (string= "" url) (setq url nil))
1659 (setq org-ref-cite-menu-funcs '())
1665 'org-ref-cite-menu-funcs
1666 '("o" "pen" org-ref-open-citation-at-point)))
1669 (when (file-exists-p pdf-file)
1671 'org-ref-cite-menu-funcs
1672 `("p" "df" ,org-ref-open-pdf-function) t))
1676 'org-ref-cite-menu-funcs
1677 '("n" "otes" org-ref-open-notes-at-point) t)
1682 'org-ref-cite-menu-funcs
1683 '("u" "rl" org-ref-open-url-at-point) t))
1688 'org-ref-cite-menu-funcs
1689 '("w" "os" org-ref-wos-at-point) t)
1692 'org-ref-cite-menu-funcs
1693 '("c" "iting" org-ref-wos-citing-at-point) t)
1696 'org-ref-cite-menu-funcs
1697 '("r" "elated" org-ref-wos-related-at-point) t)
1700 'org-ref-cite-menu-funcs
1701 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1704 'org-ref-cite-menu-funcs
1705 '("P" "ubmed" org-ref-pubmed-at-point) t))
1707 ;; add user functions
1708 (dolist (tup org-ref-user-cite-menu-funcs)
1710 'org-ref-cite-menu-funcs
1715 'org-ref-cite-menu-funcs
1716 '("q" "uit" (lambda ())) t)
1718 ;; now we make a menu
1719 ;; construct menu string as a message
1722 (let* ((results (org-ref-get-bibtex-key-and-file))
1724 (bibfile (cdr results)))
1727 (insert-file-contents bibfile)
1728 (bibtex-search-entry key)
1729 (org-ref-bib-citation))))
1733 (concat "[" (elt tup 0) "]"
1735 org-ref-cite-menu-funcs "")))
1737 (let* ((input (read-char-exclusive))
1739 (char-to-string input) org-ref-cite-menu-funcs)))
1740 ;; now run the function (2nd element in choice)
1747 ;; ** Generation of the cite links
1748 (defmacro org-ref-make-completion-function (type)
1749 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1755 (let ((bibtex-files (org-ref-find-bibliography)))
1756 (bibtex-global-key-alist))))))
1758 (defmacro org-ref-make-format-function (type)
1759 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1764 (format "[[#%s][%s]]" key key))
1765 (org-ref-split-and-strip-string keyword) ","))
1772 (org-ref-split-and-strip-string keyword) ",") "]"))
1777 (format "<a href=\"#%s\">%s</a>" key key))
1778 (org-ref-split-and-strip-string keyword) ","))
1781 (if (string= (substring type -1) "s")
1782 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1783 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1784 (org-ref-split-and-strip-string keyword) ""))
1786 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1787 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1789 ;; for markdown we generate pandoc citations
1792 (desc ;; pre and or post text
1793 (let* ((text (split-string desc "::"))
1797 (format "[@%s," keyword)
1798 (when pre (format " %s" pre))
1799 (when post (format ", %s" post))
1804 (lambda (key) (concat "@" key))
1805 (org-ref-split-and-strip-string keyword)
1808 (defun org-ref-format-citation-description (desc)
1809 "Return formatted citation description. If the cite link has a
1810 description, it is optional text for the citation command. You
1811 can specify pre and post text by separating these with ::, for
1812 example [[cite:key][pre text::post text]]."
1814 ((string-match "::" desc)
1815 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1816 (t (format "[%s]" desc))))
1818 (defun org-ref-define-citation-link (type &optional key)
1819 "Add a citation link of TYPE for org-ref.
1820 With optional KEY, set the reftex binding. For example:
1821 (org-ref-define-citation-link \"citez\" ?z) will create a new citez link, with reftex key of z,
1822 and the completion function."
1823 (interactive "sCitation Type: \ncKey: ")
1825 ;; create the formatting function
1826 (eval `(org-ref-make-format-function ,type))
1831 org-ref-cite-onclick-function
1832 (quote ,(intern (format "org-ref-format-%s" type)))))
1834 ;; create the completion function
1835 (eval `(org-ref-make-completion-function ,type))
1837 ;; store new type so it works with adding citations, which checks
1838 ;; for existence in this list
1839 (add-to-list 'org-ref-cite-types type)
1841 ;; and finally if a key is specified, we modify the reftex menu
1843 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1844 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1845 `((,key . ,(concat type ":%l")))))))
1847 ;; create all the link types and their completion functions
1848 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1850 (defun org-ref-insert-cite-link (alternative-cite)
1851 "Insert a default citation link using reftex. If you are on a link, it
1852 appends to the end of the link, otherwise, a new link is
1853 inserted. Use a prefix arg to get a menu of citation types."
1855 (org-ref-find-bibliography)
1856 (let* ((object (org-element-context))
1857 (link-string-beginning (org-element-property :begin object))
1858 (link-string-end (org-element-property :end object))
1859 (path (org-element-property :path object)))
1861 (if (not alternative-cite)
1864 ;; case where we are in a link
1865 ((and (equal (org-element-type object) 'link)
1866 (-contains? org-ref-cite-types (org-element-property :type object)))
1867 (goto-char link-string-end)
1868 ;; sometimes there are spaces at the end of the link
1869 ;; this code moves point pack until no spaces are there
1870 (while (looking-back " ") (backward-char))
1871 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1873 ;; We are next to a link, and we want to append
1876 (and (equal (org-element-type (org-element-context)) 'link)
1877 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1878 (while (looking-back " ") (backward-char))
1879 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1881 ;; insert fresh link
1884 (concat org-ref-default-citation-link
1886 (mapconcat 'identity (reftex-citation t) ",")))))
1888 ;; you pressed a C-u so we run this code
1889 (reftex-citation))))
1891 (defun org-ref-insert-cite-with-completion (type)
1892 "Insert a cite link with completion"
1893 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1894 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1896 (defun org-ref-store-bibtex-entry-link ()
1897 "Save a citation link to the current bibtex entry. Saves in the default link type."
1899 (let ((link (concat org-ref-default-citation-link
1902 (bibtex-beginning-of-entry)
1903 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1904 (message "saved %s" link)
1905 (push (list link) org-stored-links)
1906 (car org-stored-links)))
1914 (lambda (path desc format)
1917 (format "\\index{%s}" path)))))
1919 ;; this will generate a temporary index of entries in the file.
1923 (let ((*index-links* '())
1924 (*initial-letters* '()))
1927 (org-element-map (org-element-parse-buffer) 'link
1929 (let ((type (nth 0 link))
1930 (plist (nth 1 link)))
1932 (when (equal (plist-get plist ':type) "index")
1935 (cons (plist-get plist :path)
1937 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
1939 (plist-get plist :begin) ;; position of link
1940 ;; grab a description
1942 (goto-char (plist-get plist :begin))
1943 (if (thing-at-point 'sentence)
1945 (replace-regexp-in-string
1946 "\n" "" (thing-at-point 'sentence))
1947 ;; or call it a link
1951 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
1953 ;; now first letters
1954 (dolist (link *index-links*)
1955 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
1957 ;; now create the index
1958 (switch-to-buffer (get-buffer-create "*index*"))
1961 (insert "#+TITLE: Index\n\n")
1962 (dolist (letter *initial-letters*)
1963 (insert (format "* %s\n" (upcase letter)))
1964 ;; now process the links
1967 (string= letter (substring (car (car *index-links*)) 0 1)))
1968 (let ((link (pop *index-links*)))
1969 (insert (format "%s %s\n\n" (car link) (cdr link))))))
1970 (switch-to-buffer "*index*")))
1972 (lambda (path desc format)
1975 (format "\\printindex")))))
1980 nil ;; no follow action
1981 (lambda (path desc format)
1984 (format "\\newglossaryentry{%s}{%s}" path desc)))))
1990 nil ;; no follow action
1991 (lambda (path desc format)
1994 (format "\\gls{%s}" path)))))
1999 nil ;; no follow action
2000 (lambda (path desc format)
2003 (format "\\glspl{%s}" path)))))
2008 nil ;; no follow action
2009 (lambda (path desc format)
2012 (format "\\Gls{%s}" path)))))
2017 nil ;; no follow action
2018 (lambda (path desc format)
2021 (format "\\Glspl{%s}" path)))))
2024 ;; ** create text citations from a bibtex entry
2025 (defun org-ref-bib-citation ()
2026 "From a bibtex entry, create and return a simple citation string.
2027 This assumes you are in an article."
2029 (bibtex-beginning-of-entry)
2030 (let* ((cb (current-buffer))
2031 (bibtex-expand-strings t)
2032 (entry (loop for (key . value) in (bibtex-parse-entry t)
2033 collect (cons (downcase key) value)))
2034 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2035 (year (reftex-get-bib-field "year" entry))
2036 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2037 (key (reftex-get-bib-field "=key=" entry))
2038 (journal (reftex-get-bib-field "journal" entry))
2039 (volume (reftex-get-bib-field "volume" entry))
2040 (pages (reftex-get-bib-field "pages" entry))
2041 (doi (reftex-get-bib-field "doi" entry))
2042 (url (reftex-get-bib-field "url" entry))
2044 ;;authors, "title", Journal, vol(iss):pages (year).
2045 (format "%s, \"%s\", %s, %s:%s (%s)"
2046 author title journal volume pages year)))
2048 (defun org-ref-bib-html-citation ()
2049 "from a bibtex entry, create and return a simple citation with html links."
2051 (bibtex-beginning-of-entry)
2052 (let* ((cb (current-buffer))
2053 (bibtex-expand-strings t)
2054 (entry (loop for (key . value) in (bibtex-parse-entry t)
2055 collect (cons (downcase key) value)))
2056 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2057 (year (reftex-get-bib-field "year" entry))
2058 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2059 (key (reftex-get-bib-field "=key=" entry))
2060 (journal (reftex-get-bib-field "journal" entry))
2061 (volume (reftex-get-bib-field "volume" entry))
2062 (pages (reftex-get-bib-field "pages" entry))
2063 (doi (reftex-get-bib-field "doi" entry))
2064 (url (reftex-get-bib-field "url" entry))
2066 ;;authors, "title", Journal, vol(iss):pages (year).
2067 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2068 author title journal volume pages year)
2069 (when url (format " <a href=\"%s\">link</a>" url))
2070 (when doi (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))
2073 ;; ** Open pdf in bibtex entry
2074 (defun org-ref-open-bibtex-pdf ()
2075 "open pdf for a bibtex entry, if it exists. assumes point is in
2076 the entry of interest in the bibfile. but does not check that."
2079 (bibtex-beginning-of-entry)
2080 (let* ((bibtex-expand-strings t)
2081 (entry (bibtex-parse-entry t))
2082 (key (reftex-get-bib-field "=key=" entry))
2083 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2085 (if (file-exists-p pdf)
2086 (org-open-link-from-string (format "[[file:%s]]" pdf))
2089 ;; ** Open notes from bibtex entry
2091 (defun org-ref-open-bibtex-notes ()
2092 "from a bibtex entry, open the notes if they exist, and create a heading if they do not.
2094 I never did figure out how to use reftex to make this happen
2095 non-interactively. the reftex-format-citation function did not
2096 work perfectly; there were carriage returns in the strings, and
2097 it did not put the key where it needed to be. so, below I replace
2098 the carriage returns and extra spaces with a single space and
2099 construct the heading by hand."
2102 (bibtex-beginning-of-entry)
2103 (let* ((cb (current-buffer))
2104 (bibtex-expand-strings t)
2105 (entry (loop for (key . value) in (bibtex-parse-entry t)
2106 collect (cons (downcase key) value)))
2107 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2108 (year (reftex-get-bib-field "year" entry))
2109 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2110 (key (reftex-get-bib-field "=key=" entry))
2111 (journal (reftex-get-bib-field "journal" entry))
2112 (volume (reftex-get-bib-field "volume" entry))
2113 (pages (reftex-get-bib-field "pages" entry))
2114 (doi (reftex-get-bib-field "doi" entry))
2115 (url (reftex-get-bib-field "url" entry))
2118 ;; save key to clipboard to make saving pdf later easier by pasting.
2121 (kill-ring-save (point-min) (point-max)))
2123 ;; now look for entry in the notes file
2124 (if org-ref-bibliography-notes
2125 (find-file-other-window org-ref-bibliography-notes)
2126 (error "org-ref-bib-bibliography-notes is not set to anything"))
2128 (goto-char (point-min))
2129 ;; put new entry in notes if we don't find it.
2130 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2131 (funcall org-ref-open-notes-function)
2132 ;; no entry found, so add one
2133 (insert (format "\n** TODO %s - %s" year title))
2145 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2146 key author journal year volume pages doi url key org-ref-pdf-directory key))
2149 (defun org-ref-open-notes-from-reftex ()
2150 "Call reftex, and open notes for selected entry."
2152 (let ((bibtex-key )))
2154 ;; now look for entry in the notes file
2155 (if org-ref-bibliography-notes
2156 (find-file-other-window org-ref-bibliography-notes)
2157 (error "org-ref-bib-bibliography-notes is not set to anything"))
2159 (goto-char (point-min))
2161 (re-search-forward (format
2163 (first (reftex-citation t)) nil 'end))
2164 (funcall org-ref-open-notes-function))
2166 ;; ** Open bibtex entry in browser
2167 (defun org-ref-open-in-browser ()
2168 "Open the bibtex entry at point in a browser using the url field or doi field"
2171 (bibtex-beginning-of-entry)
2173 (let ((url (bibtex-autokey-get-field "url")))
2178 (let ((doi (bibtex-autokey-get-field "doi")))
2180 (if (string-match "^http" doi)
2182 (browse-url (format "http://dx.doi.org/%s" doi)))
2184 (message "No url or doi found"))))
2186 ;; ** upload entry to citeulike
2188 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2189 "with point in a bibtex entry get bibtex string and submit to citeulike.
2191 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2193 (message "uploading to citeulike")
2195 (bibtex-narrow-to-entry)
2196 (let ((startpos (point-min))
2197 (endpos (point-max))
2198 (bibtex-string (buffer-string))
2199 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2200 (with-temp-buffer (insert bibtex-string)
2201 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2203 ;; ** Build a pdf of the bibtex file
2204 (defun org-ref-build-full-bibliography ()
2205 "build pdf of all bibtex entries, and open it."
2207 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2208 (bib-base (file-name-sans-extension bibfile))
2209 (texfile (concat bib-base ".tex"))
2210 (pdffile (concat bib-base ".pdf")))
2213 (insert (format "\\documentclass[12pt]{article}
2214 \\usepackage[version=3]{mhchem}
2216 \\usepackage[numbers]{natbib}
2217 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2221 \\bibliographystyle{unsrtnat}
2223 \\end{document}" bib-base))
2225 (shell-command (concat "pdflatex " bib-base))
2226 (shell-command (concat "bibtex " bib-base))
2227 (shell-command (concat "pdflatex " bib-base))
2228 (shell-command (concat "pdflatex " bib-base))
2229 (kill-buffer texfile)
2230 (org-open-file pdffile)
2233 ;; ** Extract bibtex entries in org-file
2235 (defun org-ref-extract-bibtex-entries ()
2236 "extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2238 If no bibliography is in the buffer the `reftex-default-bibliography' is used."
2240 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2241 (tempname (make-temp-file "extract-bib"))
2242 (contents (buffer-string))
2243 (cb (current-buffer))
2244 basename texfile bibfile results)
2246 ;; open tempfile and insert org-buffer contents
2247 (find-file tempname)
2249 (setq basename (file-name-sans-extension
2250 (file-name-nondirectory buffer-file-name))
2251 texfile (concat tempname ".tex")
2252 bibfile (concat tempname ".bib"))
2254 ;; see if we have a bibliography, and insert the default one if not.
2256 (goto-char (point-min))
2257 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2258 (insert (format "\nbibliography:%s"
2259 (mapconcat 'identity reftex-default-bibliography ",")))))
2262 ;; get a latex file and extract the references
2263 (org-latex-export-to-latex)
2266 (reftex-create-bibtex-file bibfile)
2268 ;; save results of the references
2269 (setq results (buffer-string))
2271 ;; kill buffers. these are named by basename, not full path
2272 (kill-buffer (concat basename ".bib"))
2273 (kill-buffer (concat basename ".tex"))
2274 (kill-buffer basename)
2276 (delete-file bibfile)
2277 (delete-file texfile)
2278 (delete-file tempname)
2280 ;; Now back to the original org buffer and insert the results
2281 (switch-to-buffer cb)
2282 (when (not (string= "" results))
2284 (goto-char (point-max))
2286 (org-insert-heading)
2287 (insert (format " Bibtex entries
2289 #+BEGIN_SRC text :tangle %s
2291 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2293 ;; ** Find bad citations
2296 (defun index (substring list)
2297 "return the index of string in a list of strings"
2300 (dolist (arg list i)
2301 (if (string-match (concat "^" substring "$") arg)
2306 ;; return counter if found, otherwise return nil
2310 (defun org-ref-find-bad-citations ()
2311 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2313 Makes a new buffer with clickable links."
2315 ;; generate the list of bibtex-keys and cited keys
2316 (let* ((bibtex-files (org-ref-find-bibliography))
2317 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2318 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2319 (bad-citations '()))
2321 (org-element-map (org-element-parse-buffer) 'link
2323 (let ((plist (nth 1 link)))
2324 (when (-contains? org-ref-cite-types (plist-get plist :type))
2325 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2326 (when (not (index key bibtex-keys))
2331 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2334 (plist-get plist :begin)))))
2336 ;; set with-affilates to t to get citations in a caption
2341 (switch-to-buffer-other-window "*Missing citations*")
2344 (insert "* List of bad cite links\n")
2345 (insert (mapconcat 'identity bad-citations ""))
2346 ;(setq buffer-read-only t)
2347 (use-local-map (copy-keymap org-mode-map))
2348 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2350 (when (get-buffer "*Missing citations*")
2351 (kill-buffer "*Missing citations*"))
2352 (message "No bad cite links found"))))
2354 ;; ** helm interface to bad citations, labels, refs in orgfile
2355 (defun org-ref-bad-cite-candidates ()
2356 "Returns a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2357 (let* ((cp (point)) ; save to return to later
2358 (bibtex-files (org-ref-find-bibliography))
2359 (bibtex-file-path (mapconcat
2361 (file-name-directory (file-truename x)))
2363 (bibtex-keys (mapcar (lambda (x) (car x))
2364 (bibtex-global-key-alist)))
2365 (bad-citations '()))
2367 (org-element-map (org-element-parse-buffer) 'link
2369 (let ((plist (nth 1 link)))
2370 (when (-contains? org-ref-cite-types (plist-get plist :type))
2371 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2372 (when (not (index key bibtex-keys))
2373 (goto-char (plist-get plist :begin))
2374 (re-search-forward key)
2375 (push (cons key (point-marker)) bad-citations)))
2377 ;; add with-affiliates to get cites in caption
2383 (defun org-ref-bad-ref-candidates ()
2384 "Returns a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2385 ;; first get a list of legitimate labels
2387 (labels (org-ref-get-labels))
2389 ;; now loop over ref links
2390 (goto-char (point-min))
2391 (org-element-map (org-element-parse-buffer) 'link
2393 (let ((plist (nth 1 link)))
2394 (when (or (equal (plist-get plist ':type) "ref")
2395 (equal (plist-get plist ':type) "eqref")
2396 (equal (plist-get plist ':type) "pageref")
2397 (equal (plist-get plist ':type) "nameref"))
2398 (unless (-contains? labels (plist-get plist :path))
2399 (goto-char (plist-get plist :begin))
2402 (cons (plist-get plist :path)
2403 (point-marker))))))))
2408 (defun org-ref-bad-label-candidates ()
2409 "Return a list of labels where label is multiply defined."
2410 (let ((labels (org-ref-get-labels))
2411 (multiple-labels '()))
2412 (when (not (= (length labels)
2413 (length (-uniq labels))))
2414 (dolist (label labels)
2415 (when (> (-count (lambda (a)
2418 ;; this is a multiply defined label.
2420 (goto-char (point-min))
2421 (while (re-search-forward
2422 (format "[^#+]label:%s\\s-" label) nil t)
2423 (push (cons label (point-marker)) multiple-labels))
2425 (goto-char (point-min))
2426 (while (re-search-forward
2427 (format "\\label{%s}\\s-?" label) nil t)
2428 (push (cons label (point-marker)) multiple-labels))
2430 (goto-char (point-min))
2431 (while (re-search-forward
2432 (format "^#\\+label:\\s-*%s" label) nil t)
2433 (push (cons label (point-marker)) multiple-labels))
2435 (goto-char (point-min))
2436 (while (re-search-forward
2437 (format "^#\\+tblname:\\s-*%s" label) nil t)
2438 (push (cons label (point-marker)) multiple-labels))
2444 "Opens a helm interface to actions for org-ref.
2445 Shows bad citations, ref links and labels"
2447 (let ((cb (current-buffer))
2448 (bad-citations (org-ref-bad-cite-candidates))
2449 (bad-refs (org-ref-bad-ref-candidates))
2450 (bad-labels (org-ref-bad-label-candidates)))
2452 (helm :sources `(((name . "Bad citations")
2453 (candidates . ,bad-citations)
2454 (action . (lambda (marker)
2455 (switch-to-buffer (marker-buffer marker))
2456 (goto-char marker))))
2458 ((name . "Bad Labels")
2459 (candidates . ,bad-labels)
2460 (action . (lambda (marker)
2461 (switch-to-buffer (marker-buffer marker))
2462 (goto-char marker))))
2464 ((name . "Bad ref links")
2465 (candidates . ,bad-refs)
2466 (action . (lambda (marker)
2467 (switch-to-buffer (marker-buffer marker))
2468 (goto-char marker))))
2470 ((name . "Utilities")
2471 (candidates . (("Check buffer again" . org-ref)
2472 ("Insert citation" . helm-bibtex)
2473 ("Insert label link" . org-ref-helm-insert-label-link)
2474 ("Insert ref link" . org-ref-helm-insert-ref-link)
2475 ("List of figures" . org-ref-list-of-figures)
2476 ("List of tables" . org-ref-list-of-tables)
2477 ("Table of contents" . nil)
2479 (action . (lambda (x)
2480 (switch-to-buffer ,cb)
2483 ((name . "Export functions")
2484 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2485 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2486 ("Export to pdf and open" . (lambda ()
2487 (org-open-file (org-latex-export-to-pdf))))
2488 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2489 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2492 (action . (lambda (x)
2493 (switch-to-buffer ,cb)
2497 ;; ** Find non-ascii charaters
2498 (defun org-ref-find-non-ascii-characters ()
2499 "finds non-ascii characters in the buffer. Useful for cleaning up bibtex files"
2501 (occur "[^[:ascii:]]"))
2503 ;; ** Sort fields in a bibtex entry
2505 (defun org-ref-sort-bibtex-entry ()
2506 "sort fields of entry in standard order and downcase them"
2508 (bibtex-beginning-of-entry)
2509 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2510 (entry (bibtex-parse-entry))
2513 (type (cdr (assoc "=type=" entry)))
2514 (key (cdr (assoc "=key=" entry))))
2516 ;; these are the fields we want to order that are in this entry
2517 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2518 ;; we do not want to reenter these fields
2519 (setq entry-fields (remove "=key=" entry-fields))
2520 (setq entry-fields (remove "=type=" entry-fields))
2522 ;;these are the other fields in the entry
2523 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2526 ;; right now we only resort articles
2527 ((string= (downcase type) "article")
2530 (concat "@article{" key ",\n"
2533 (when (member field entry-fields)
2534 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2537 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2539 (bibtex-find-entry key)
2541 (bibtex-clean-entry)
2544 ;; ** Clean a bibtex entry
2545 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2546 "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"
2548 (bibtex-beginning-of-entry)
2550 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2551 (unless (string-match ",$" (thing-at-point 'line))
2555 ;; check for empty pages, and put eid or article id in its place
2556 (let ((entry (bibtex-parse-entry))
2557 (pages (bibtex-autokey-get-field "pages"))
2558 (year (bibtex-autokey-get-field "year"))
2559 (doi (bibtex-autokey-get-field "doi"))
2560 ;; The Journal of Chemical Physics uses eid
2561 (eid (bibtex-autokey-get-field "eid")))
2563 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2564 ;; but we only want the doi.
2565 (when (string-match "^http://dx.doi.org/" doi)
2566 (bibtex-beginning-of-entry)
2567 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2569 (bibtex-make-field "doi")
2571 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2573 ;; asap articles often set year to 0, which messes up key
2574 ;; generation. fix that.
2575 (when (string= "0" year)
2576 (bibtex-beginning-of-entry)
2577 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2579 (bibtex-make-field "year")
2581 (insert (read-string "Enter year: ")))
2583 ;; fix pages if they are empty if there is an eid to put there.
2584 (when (string= "-" pages)
2586 (bibtex-beginning-of-entry)
2587 ;; this seems like a clunky way to set the pages field.But I
2588 ;; cannot find a better way.
2589 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2591 (bibtex-make-field "pages")
2595 ;; replace naked & with \&
2597 (bibtex-narrow-to-entry)
2598 (bibtex-beginning-of-entry)
2599 (message "checking &")
2600 (replace-regexp " & " " \\\\& ")
2603 ;; generate a key, and if it duplicates an existing key, edit it.
2605 (let ((key (bibtex-generate-autokey)))
2607 ;; first we delete the existing key
2608 (bibtex-beginning-of-entry)
2609 (re-search-forward bibtex-entry-maybe-empty-head)
2610 (if (match-beginning bibtex-key-in-head)
2611 (delete-region (match-beginning bibtex-key-in-head)
2612 (match-end bibtex-key-in-head)))
2613 ;; check if the key is in the buffer
2614 (when (save-excursion
2615 (bibtex-search-entry key))
2617 (bibtex-search-entry key)
2618 (bibtex-copy-entry-as-kill)
2619 (switch-to-buffer-other-window "*duplicate entry*")
2621 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2624 (kill-new key))) ;; save key for pasting
2626 ;; run hooks. each of these operates on the entry with no arguments.
2627 ;; this did not work like i thought, it gives a symbolp error.
2628 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2633 org-ref-clean-bibtex-entry-hook)
2635 ;; sort fields within entry
2636 (org-ref-sort-bibtex-entry)
2637 ;; check for non-ascii characters
2638 (occur "[^[:ascii:]]")
2641 (defun org-ref-get-citation-year (key)
2642 "get the year of an entry with key. Returns year as a string."
2643 (let* ((results (org-ref-get-bibtex-key-and-file key))
2644 (bibfile (cdr results)))
2646 (insert-file-contents bibfile)
2647 (bibtex-search-entry key nil 0)
2648 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2651 ;; ** Sort cite in cite link
2652 (defun org-ref-sort-citation-link ()
2653 "Replace link at point with sorted link by year."
2655 (let* ((object (org-element-context))
2656 (type (org-element-property :type object))
2657 (begin (org-element-property :begin object))
2658 (end (org-element-property :end object))
2659 (link-string (org-element-property :path object))
2661 (setq keys (org-ref-split-and-strip-string link-string))
2662 (setq years (mapcar 'org-ref-get-citation-year keys))
2663 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2664 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2665 ;; now get the keys separated by commas
2666 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2667 ;; and replace the link with the sorted keys
2668 (cl--set-buffer-substring begin end (concat type ":" keys))))
2670 ;; ** Shift-arrow sorting of keys in a cite link
2672 (defun org-ref-swap-keys (i j keys)
2673 "Swap the KEYS in a list with index I and J."
2674 (let ((tempi (nth i keys)))
2675 (setf (nth i keys) (nth j keys))
2676 (setf (nth j keys) tempi))
2680 (defun org-ref-swap-citation-link (direction)
2681 "move citation at point in direction +1 is to the right, -1 to the left"
2683 (let* ((object (org-element-context))
2684 (type (org-element-property :type object))
2685 (begin (org-element-property :begin object))
2686 (end (org-element-property :end object))
2687 (link-string (org-element-property :path object))
2689 ;; We only want this to work on citation links
2690 (when (-contains? org-ref-cite-types type)
2691 (setq key (org-ref-get-bibtex-key-under-cursor))
2692 (setq keys (org-ref-split-and-strip-string link-string))
2693 (setq i (index key keys)) ;; defined in org-ref
2694 (if (> direction 0) ;; shift right
2695 (org-ref-swap-keys i (+ i 1) keys)
2696 (org-ref-swap-keys i (- i 1) keys))
2697 (setq keys (mapconcat 'identity keys ","))
2698 ;; and replace the link with the sorted keys
2699 (cl--set-buffer-substring
2703 ;; It seems the space at the end can get consumed, so we see if there
2704 ;; is a space, and add it if so. Sometimes there is a comma or period,
2705 ;; then we do not want a space.
2709 (looking-back " ")) " ")))
2710 ;; now go forward to key so we can move with the key
2711 (re-search-forward key)
2712 (goto-char (match-beginning 0)))))
2714 ;; add hooks to make it work
2715 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2716 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2718 ;; ** context around org-ref links
2719 (defun org-ref-get-label-context (label)
2720 "Return a string of context around a label."
2723 (goto-char (point-min))
2724 (when (re-search-forward
2725 (format "label:%s\\b" label) nil t)
2726 (throw 'result (buffer-substring
2735 (goto-char (point-min))
2736 (when (re-search-forward
2737 (format "\\label{%s}" label) nil t)
2738 (throw 'result (buffer-substring
2747 (goto-char (point-min))
2748 (when (re-search-forward
2749 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2750 (throw 'result (buffer-substring
2759 (goto-char (point-min))
2760 (when (re-search-forward
2761 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2762 (throw 'result (buffer-substring
2770 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2773 (defun org-ref-link-message ()
2774 "Print a minibuffer message about the link that point is on."
2776 (when (eq major-mode 'org-mode)
2777 (let* ((object (org-element-context))
2778 (type (org-element-property :type object)))
2782 ((-contains? org-ref-cite-types type)
2783 (message (org-ref-get-citation-string-at-point)))
2785 ;; message some context about the label we are referring to
2786 ((string= type "ref")
2787 (message "%scount: %s"
2788 (org-ref-get-label-context
2789 (org-element-property :path object))
2790 (org-ref-count-labels
2791 (org-element-property :path object))))
2793 ((string= type "eqref")
2794 (message "%scount: %s"
2795 (org-ref-get-label-context
2796 (org-element-property :path object))
2797 (org-ref-count-labels
2798 (org-element-property :path object))))
2800 ;; message the count
2801 ((string= type "label")
2802 (let ((count (org-ref-count-labels
2803 (org-element-property :path object))))
2804 ;; get plurality on occurrence correct
2806 (number-to-string count)
2808 (when (or (= count 0)
2812 ((string= type "custom-id")
2814 (org-open-link-from-string
2815 (format "[[#%s]]" (org-element-property :path object)))
2816 (message "%s" (org-get-heading))))
2818 ;; check if the bibliography files exist.
2819 ((string= type "bibliography")
2821 ;; object is the link you clicked on
2822 (object (org-element-context))
2823 (link-string (org-element-property :path object))
2824 (link-string-beginning)
2827 (goto-char (org-element-property :begin object))
2828 (search-forward link-string nil nil 1)
2829 (setq link-string-beginning (match-beginning 0))
2830 (setq link-string-end (match-end 0)))
2832 ;; make sure we are in link and not before the :
2833 (when (> link-string-beginning (point))
2834 (goto-char link-string-beginning))
2836 ;; now if we have comma separated bibliographies
2837 ;; we find the one clicked on. we want to
2838 ;; search forward to next comma from point
2840 (if (search-forward "," link-string-end 1 1)
2841 (setq key-end (- (match-end 0) 1)) ; we found a match
2842 (setq key-end (point)))) ; no comma found so take the point
2844 ;; and backward to previous comma from point
2846 (if (search-backward "," link-string-beginning 1 1)
2847 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2848 (setq key-beginning (point)))) ; no match found
2849 ;; save the key we clicked on.
2851 (org-ref-strip-string
2852 (buffer-substring key-beginning key-end)))
2853 (if (file-exists-p bibfile)
2854 (message "%s exists." bibfile)
2855 (message "!!! %s NOT FOUND !!!" bibfile))))
2859 (defalias 'oro 'org-ref-open-citation-at-point)
2860 (defalias 'orc 'org-ref-citation-at-point)
2861 (defalias 'orp 'org-ref-open-pdf-at-point)
2862 (defalias 'oru 'org-ref-open-url-at-point)
2863 (defalias 'orn 'org-ref-open-notes-at-point)
2864 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2866 (defalias 'orib 'org-ref-insert-bibliography-link)
2867 (defalias 'oric 'org-ref-insert-cite-link)
2868 (defalias 'orir 'org-ref-insert-ref-link)
2869 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2871 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2873 ;; * Helm bibtex setup
2875 (setq helm-bibtex-additional-search-fields '(keywords))
2877 (defun helm-bibtex-candidates-formatter (candidates source)
2878 "Formats BibTeX entries for display in results list."
2880 with width = (with-helm-window (helm-bibtex-window-width))
2881 for entry in candidates
2882 for entry = (cdr entry)
2883 for entry-key = (helm-bibtex-get-value "=key=" entry)
2884 if (assoc-string "author" entry 'case-fold)
2885 for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2887 for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2888 for fields = (--map (helm-bibtex-clean-string
2889 (helm-bibtex-get-value it entry " "))
2891 for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
2892 for fields = (append fields
2893 (list (or (helm-bibtex-get-value "keywords" entry)
2896 (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
2897 (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
2898 fields (list 36 (- width 85) 4 1 1 7 7)))
2901 ;; * org-ref bibtex keywords
2902 ;; adapted from bibtex-utils.el
2903 ;; these are candidates for selecting keywords/tags
2904 (defun org-ref-bibtex-keywords ()
2905 "Get keywords defined in current bibtex file.
2906 These are in the keywords field, and are comma or semicolon separated."
2908 (goto-char (point-min))
2909 (let (keywords kstring)
2910 (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
2911 ;; TWS - remove newlines/multiple spaces:
2912 (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
2915 (add-to-list 'keywords v t))
2916 (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
2920 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
2921 "Add KEYWORDS to a bibtex entry.
2922 If KEYWORDS is a list, it is converted to a comma-separated string. The KEYWORDS are added to the beginning of the field. Otherwise KEYWORDS should be a string of comma-separate keywords."
2923 (interactive "sKeywords: \nP")
2928 (if (listp keywords)
2929 (mapconcat 'identity keywords ", ")
2931 ;; else concatentate
2933 (if (listp keywords)
2934 (mapconcat 'identity keywords ", ")
2936 (when (not (string= "" (bibtex-autokey-get-field "keywords")))
2937 (concat ", " (bibtex-autokey-get-field "keywords"))))))
2941 (defun helm-tag-bibtex-entry ()
2942 "Helm interface to add keywords to a bibtex entry.
2943 Run this with the point in a bibtex entry."
2945 (let ((keyword-source `((name . "Existing keywords")
2946 (candidates . ,(org-ref-bibtex-keywords))
2947 (action . (lambda (candidate)
2948 (org-ref-set-bibtex-keywords
2951 (helm-marked-candidates)
2953 (fallback-source `((name . "Add new keywords")
2955 (action . (lambda (candidate)
2956 (org-ref-set-bibtex-keywords helm-pattern)
2958 (helm :sources '(keyword-source fallback-source))))
2960 (defun helm-bibtex-show-entry (key)
2961 "Show the entry in the BibTeX file.
2962 The original function in helm-bibtex has a bug where it finds the
2963 first key that partially matches. This version avoids that."
2965 (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
2966 helm-bibtex-bibliography
2967 (list helm-bibtex-bibliography)))
2968 (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
2970 (find-file bibtex-file)
2972 (lambda (key start end)
2973 (add-to-list 'entries (cons key start))))
2974 (if (assoc key entries)
2976 (goto-char (cdr (assoc key entries)))
2981 (defun org-ref-helm-tag-entries (candidates)
2982 "Set tags on selected bibtex entries from helm-bibtex.
2983 User is prompted for tags. This function is called from `helm-bibtex'."
2985 (let ((keywords (read-input "Keywords (comma separated): ")))
2986 (loop for key in (helm-marked-candidates)
2988 (save-window-excursion
2989 (helm-bibtex-show-entry key)
2994 ", " (bibtex-autokey-get-field "keywords")))
2997 (setq helm-source-bibtex
2998 '((name . "BibTeX entries")
2999 (init . helm-bibtex-init)
3000 (candidates . helm-bibtex-candidates)
3001 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3002 (action . (("Insert citation" . helm-bibtex-insert-citation)
3003 ("Show entry" . helm-bibtex-show-entry)
3004 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3005 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3006 ("Insert formatted reference" . helm-bibtex-insert-reference)
3007 ("Insert BibTeX key" . helm-bibtex-insert-key)
3008 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3009 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3010 ("Edit notes" . helm-bibtex-edit-notes)
3011 ("Add keywords to entries" . org-ref-helm-tag-entries)
3014 (defun helm-bibtex-format-org-ref (keys)
3015 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3016 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.
3018 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3020 C-u C-u will change the key at point to the selected keys.
3022 (let* ((object (org-element-context))
3023 (last-char (save-excursion
3024 (goto-char (org-element-property :end object))
3026 (if (looking-at " ")
3030 ;; case where we are in a link
3031 ((and (equal (org-element-type object) 'link)
3034 (org-element-property :type object)))
3036 ;; no prefix. append keys
3037 ((equal helm-current-prefix-arg nil)
3038 (goto-char (org-element-property :end object))
3039 (while (looking-back " ") (backward-char))
3040 (insert (concat "," (mapconcat 'identity keys ","))))
3041 ;; double prefix, replace key at point
3042 ((equal helm-current-prefix-arg '(16))
3043 (setf (buffer-substring
3044 (org-element-property :begin object)
3045 (org-element-property :end object))
3047 (replace-regexp-in-string
3048 (car (org-ref-get-bibtex-key-and-file)) ; key
3049 (mapconcat 'identity keys ",") ; new keys
3050 (org-element-property :raw-link object))
3051 ;; replace space at end to avoid collapsing into next word.
3053 ;; and we want to go to the end of the new link
3055 (org-element-property :end (org-element-context))))
3057 (message "Not found"))))
3059 ;; We are next to a link, and we want to append
3060 ;; next to a link means one character back is on a link.
3063 (and (equal (org-element-type (org-element-context)) 'link)
3066 (org-element-property :type (org-element-context)))))
3067 (while (looking-back " ") (backward-char))
3068 (insert (concat "," (mapconcat 'identity keys ","))))
3070 ;; insert fresh link
3072 ;;(message-box "fresh link")
3074 (concat (if (equal helm-current-prefix-arg '(4))
3075 (helm :sources `((name . "link types")
3076 (candidates . ,org-ref-cite-types)
3077 (action . (lambda (x) x))))
3078 org-ref-default-citation-link)
3080 (s-join "," keys))))))
3081 ;; return empty string for helm
3084 (setq helm-bibtex-format-citation-functions
3085 '((org-mode . helm-bibtex-format-org-ref)))
3088 (defun org-ref-helm-insert-cite-link (arg)
3089 "org-ref function to use helm-bibtex to insert a citation link.
3090 With one prefix arg, insert a ref link.
3091 With two prefix args, insert a label link."
3095 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3098 (org-ref-helm-insert-ref-link))
3100 (org-ref-helm-insert-label-link))))
3103 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3104 (setq helm-bibtex-fallback-options
3105 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3107 (setq helm-bibtex-fallback-options
3110 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3111 helm-bibtex-fallback-options))
3113 (setq helm-bibtex-fallback-options
3114 (-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))
3116 (defun org-ref-get-citation-string-at-point ()
3117 "Get a string of a formatted citation"
3118 (let* ((results (org-ref-get-bibtex-key-and-file))
3120 (bibfile (cdr results)))
3124 (insert-file-contents bibfile)
3125 (bibtex-search-entry key)
3126 (org-ref-bib-citation)))
3127 "!!! No entry found !!!" )))
3130 (defun org-ref-cite-candidates ()
3131 "Generate the list of possible candidates for click actions on a cite link.
3132 Checks for pdf and doi, and add appropriate functions."
3133 (let* ((results (org-ref-get-bibtex-key-and-file))
3135 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3136 (bibfile (cdr results))
3137 (url (save-excursion
3139 (insert-file-contents bibfile)
3140 (bibtex-search-entry key)
3141 (bibtex-autokey-get-field "url"))))
3142 (doi (save-excursion
3144 (insert-file-contents bibfile)
3145 (bibtex-search-entry key)
3146 ;; I like this better than bibtex-url which does not always find
3148 (bibtex-autokey-get-field "doi"))))
3149 (candidates `(("Quit" . org-ref-citation-at-point)
3150 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3151 ;; for some reason, when there is no doi or url, they are returned as "". I
3152 ;; prefer nil so we correct this here.
3153 (when (string= doi "") (setq doi nil))
3154 (when (string= url "") (setq url nil))
3156 ;; Conditional pdf functions
3157 (if (file-exists-p pdf-file)
3160 '("Open pdf" . org-ref-open-pdf-at-point)
3164 '("Try to get pdf" . (lambda ()
3165 (save-window-excursion
3166 (org-ref-open-citation-at-point)
3167 (bibtex-beginning-of-entry)
3168 (doi-utils-get-bibtex-entry-pdf))))
3174 '("Open notes" . org-ref-open-notes-at-point)
3177 ;; conditional url and doi functions
3181 '("Open in browser" . org-ref-open-url-at-point)
3186 (add-to-list 'candidates x t))
3187 `(("WOS" . org-ref-wos-at-point)
3188 ("Related articles in WOS" . org-ref-wos-related-at-point)
3189 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3190 ("Google Scholar" . org-ref-google-scholar-at-point)
3191 ("Pubmed" . org-ref-pubmed-at-point)
3192 ("Crossref" . org-ref-crossref-at-point)
3197 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3202 '("Copy key to clipboard" . (lambda ()
3204 (car (org-ref-get-bibtex-key-and-file)))))
3209 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3214 '("Email bibtex entry and pdf" . (lambda ()
3216 (org-ref-open-citation-at-point)
3217 (email-bibtex-entry))))
3219 ;; finally return a numbered list of the candidates
3221 for cell in candidates
3222 collect (cons (format "%2s. %s" i (car cell))
3226 (defvar org-ref-helm-user-candidates '()
3227 "List of user-defined candidates to act when clicking on a cite link.
3228 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.
3231 ;; example of adding your own function
3233 'org-ref-helm-user-candidates
3234 '("Example" . (lambda () (message-box "You did it!")))
3238 (defun org-ref-cite-click-helm (key)
3239 "Open helm for actions on a cite link.
3241 1. get name and candidates before entering helm because we need the org-buffer.
3242 2. switch back to the org buffer before evaluating the action. most of them need the point and buffer."
3244 (let ((name (org-ref-get-citation-string-at-point))
3245 (candidates (org-ref-cite-candidates))
3246 (cb (current-buffer)))
3248 (helm :sources `(((name . ,name)
3249 (candidates . ,candidates)
3250 (action . (lambda (f)
3251 (switch-to-buffer cb)
3253 ((name . "User functions")
3254 (candidates . ,org-ref-helm-user-candidates)
3255 (action . (lambda (f)
3256 (switch-to-buffer cb)
3260 ;; * Hydra menus in org-ref
3262 (when (featurep 'hydra)
3264 (setq hydra-is-helpful t)
3266 (defhydra org-ref-cite-hydra (:color blue)
3268 _p_: Open pdf _w_: WOS _g_: Google Scholar _K_: Copy citation to clipboard
3269 _u_: Open url _r_: WOS related _P_: Pubmed _k_: Copy key to clipboard
3270 _n_: Open notes _c_: WOS citing _C_: Crossref _f_: Copy bibtex entry to file
3271 _o_: Open entry _e_: Email entry and pdf
3273 ("o" org-ref-open-citation-at-point nil)
3274 ("p" org-ref-open-pdf-at-point nil)
3275 ("n" org-ref-open-notes-at-point nil)
3276 ("u" org-ref-open-url-at-point nil)
3277 ("w" org-ref-wos-at-point nil)
3278 ("r" org-ref-wos-related-at-point nil)
3279 ("c" org-ref-wos-citing-at-point nil)
3280 ("g" org-ref-google-scholar-at-point nil)
3281 ("P" org-ref-pubmed-at-point nil)
3282 ("C" org-ref-crossref-at-point nil)
3283 ("K" org-ref-copy-entry-as-summary nil)
3286 (car (org-ref-get-bibtex-key-and-file)))) nil)
3287 ("f" org-ref-copy-entry-at-point-to-file nil)
3289 ("e" (save-excursion
3290 (org-ref-open-citation-at-point)
3291 (email-bibtex-entry)) nil)))
3296 ;;; org-ref.el ends here