1 ;;; org-ref.el --- cite and cross-reference in org-mode
3 ;; Copyright(C) 2014 John Kitchin
5 ;; Author: John Kitchin <jkitchin@andrew.cmu.edu>
6 ;; URL: https://github.com/jkitchin/org-ref
8 ;; Keywords: org-mode, cite, ref, label
9 ;; Package-Requires: ((org) (dash) (helm) (helm-bibtex) (hydra))
11 ;; This file is not currently part of GNU Emacs.
13 ;; This program is free software; you can redistribute it and/or
14 ;; modify it under the terms of the GNU General Public License as
15 ;; published by the Free Software Foundation; either version 2, or (at
16 ;; your option) any later version.
18 ;; This program is distributed in the hope that it will be useful, but
19 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
21 ;; General Public License for more details.
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with this program ; see the file COPYING. If not, write to
25 ;; the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
26 ;; Boston, MA 02111-1307, USA.
30 ;; Lisp code to setup bibliography cite, ref and label org-mode links.
31 ;; also sets up reftex and helm for org-mode citations. The links are
32 ;; clickable and do things that are useful. You should really read
33 ;; org-ref.org for details.
38 (require 'reftex-cite)
41 (require 'helm-config)
42 (require 'helm-bibtex)
47 "Customization group for org-ref.")
49 (defcustom org-ref-bibliography-notes
51 "Filename where you will put all your notes about an entry in the default bibliography."
55 (defcustom org-ref-default-bibliography
57 "List of bibtex files to search for.
58 You should use full-paths for each file."
59 :type '(repeat :tag "List of bibtex files" file)
62 (defcustom org-ref-pdf-directory
64 "Directory where pdfs are stored by key. put a trailing / in."
68 (defcustom org-ref-default-citation-link
70 "The default type of citation link to use."
74 (defcustom org-ref-insert-cite-key
76 "Keyboard shortcut to insert a citation."
80 (defcustom org-ref-bibliography-entry-format
81 '(("article" . "%a, %t, <i>%j</i>, <b>%v(%n)</b>, %p (%y). <a href=\"%U\">link</a>. <a href=\"http://dx.doi.org/%D\">doi</a>.")
83 ("book" . "%a, %t, %u (%y).")
84 ("techreport" . "%a, %t, %u (%y).")
85 ("proceedings" . "%e, %t in %S, %u (%y).")
86 ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
87 "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."
91 (defcustom org-ref-open-notes-function
97 ;;(org-tree-to-indirect-buffer)
98 (outline-previous-visible-heading 1)
99 (recenter-top-bottom 0))
100 "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."
105 (defcustom org-ref-open-pdf-function
106 'org-ref-open-pdf-at-point
107 "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'."
112 (defcustom org-ref-insert-cite-function
113 'org-ref-helm-insert-cite-link
114 "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."
119 (defcustom org-ref-cite-onclick-function
120 'org-ref-cite-click-helm
121 "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'."
126 (defcustom org-ref-show-citation-on-enter t
127 "If non-nil add a hook function to show the citation summary in the minibuffer."
130 (defcustom org-ref-cite-types
131 '("cite" "nocite" ;; the default latex cite commands
132 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
133 "citet" "citet*" "citep" "citep*"
134 "citealt" "citealt*" "citealp" "citealp*"
136 "citeauthor" "citeauthor*"
137 "citeyear" "citeyear*"
138 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
140 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
142 "parencite" "Parencite"
143 "footcite" "footcitetext"
144 "textcite" "Textcite"
145 "smartcite" "Smartcite"
146 "cite*" "parencite*" "supercite"
147 "autocite" "Autocite" "autocite*" "Autocite*"
149 "citetitle" "citetitle*"
150 "citedate" "citedate*"
152 "fullcite" "footfullcite"
153 ;; "volcite" "Volcite" cannot support the syntax
154 "notecite" "Notecite"
155 "pnotecite" "Pnotecite"
157 ;; multicites. Very limited support for these.
158 "cites" "Cites" "parencites" "Parencites"
159 "footcites" "footcitetexts"
160 "smartcites" "Smartcites" "textcites" "Textcites"
161 "supercites" "autocites" "Autocites"
162 ;; for the bibentry package
165 "List of citation types known in `org-ref'."
166 :type '(repeat :tag "List of citation types" string)
169 (defcustom org-ref-clean-bibtex-entry-hook nil
170 "Hook that is run in `org-ref-clean-bibtex-entry'. The functions should take no arguments, and operate on the bibtex entry at point."
174 (defvar org-ref-bibliography-files
176 "Variable to hold bibliography files to be searched.")
178 ;; * org-mode / reftex setup
180 (defun org-mode-reftex-setup ()
181 "Setup `org-mode' and reftex for org-ref."
182 (and (buffer-file-name)
183 (file-exists-p (buffer-file-name))
184 (global-auto-revert-mode t))
185 (make-local-variable 'reftex-cite-format)
186 (setq reftex-cite-format 'org))
188 ;; define key for inserting citations
189 (define-key org-mode-map
190 (kbd org-ref-insert-cite-key)
191 org-ref-insert-cite-function)
193 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
195 (eval-after-load 'reftex-vars
197 (add-to-list 'reftex-cite-format-builtin
198 '(org "Org-mode citation"
199 ((?\C-m . "cite:%l") ; default
200 (?d . ",%l") ; for appending
206 (?h . "citeauthor:%l")
207 (?H . "citeauthor*:%l")
213 ;; * Messages for link at cursor
214 (defvar org-ref-message-timer nil
215 "Variable to store the link message timer in.")
218 (defun org-ref-show-link-messages ()
219 "Turn on link messages.
220 You will see a message in the minibuffer when on a cite, ref or label link."
222 (or org-ref-message-timer
223 (setq org-ref-message-timer
224 (run-with-idle-timer 0.5 t 'org-ref-link-message))))
227 (defun org-ref-cancel-link-messages ()
228 "Stop showing messages in minibuffer when on a link."
230 (cancel-timer org-ref-message-timer)
231 (setq org-ref-message-timer nil))
234 (when org-ref-show-citation-on-enter
235 (org-ref-show-link-messages))
237 ;; ** Messages for context under mouse pointer
239 (defvar org-ref-last-mouse-pos nil
240 "Stores last mouse position for use in `org-ref-mouse-message'.")
242 (defun org-ref-can-move-p ()
243 "See if a character is under the mouse. If so return the position for `goto-char'."
244 (let* ((line (cddr org-ref-last-mouse-pos))
245 (col (cadr org-ref-last-mouse-pos)))
247 (goto-char (window-start))
250 (> (- (line-end-position) (line-beginning-position)) col)
251 (progn (forward-char col) (point))
255 (defun org-ref-mouse-message ()
256 "Display message for link under mouse cursor."
258 (when (not (equal (mouse-position) org-ref-last-mouse-pos))
259 (setq org-ref-last-mouse-pos (mouse-position))
260 (let ((p (org-ref-can-move-p)))
264 (org-ref-link-message))))))
267 (defvar org-ref-message-timer-mouse nil
268 "Store mouse timer.")
271 (defvar org-ref-mouse-message-interval 0.5
272 "How often to run the mouse message timer in seconds.")
275 (defun org-ref-mouse-messages-on ()
276 "Turn on mouse messages."
278 (or org-ref-message-timer-mouse
279 (setq org-ref-message-timer-mouse
280 (run-at-time "0.5 sec"
281 org-ref-mouse-message-interval
282 'org-ref-mouse-message))))
285 (defun org-ref-mouse-messages-off ()
286 "Turn off mouse messages."
288 (cancel-timer org-ref-message-timer-mouse)
289 (setq org-ref-message-timer-mouse nil)
290 (message "Mouse messages are off"))
292 ;; Colorizing org-ref links
293 (defcustom org-ref-colorize-links
295 "When non-nil, change colors of links."
299 (defcustom org-ref-cite-color
301 "Color of cite like links."
305 (defcustom org-ref-ref-color
307 "Color of ref like links."
311 (defcustom org-ref-label-color
313 "Color of label links."
317 (defvar org-ref-cite-re nil
318 "Regexp for cite links.")
321 (setq org-ref-cite-re
322 (concat "\\(" (mapconcat
324 (replace-regexp-in-string "\*" "\\\\*" x)
326 org-ref-cite-types "\\|") "\\)"
327 ":\\([a-zA-Z0-9-_:\\./]*,?\\)*"))
330 (setq org-ref-label-re
331 "label:\\([a-zA-Z0-9-_:]*,?\\)*")
335 "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
338 (defface org-ref-cite-face
339 `((t (:inherit org-link :foreground ,org-ref-cite-color)))
340 "Color for cite-like links in org-ref.")
343 (defface org-ref-label-face
344 `((t (:inherit org-link :foreground ,org-ref-label-color)))
345 "Color for ref links in org-ref.")
348 (defface org-ref-ref-face
349 `((t (:inherit org-link :foreground ,org-ref-ref-color)))
350 "Face for ref links in org-ref.")
353 (defun org-ref-colorize-links ()
354 "Colorize org-ref links."
356 (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
357 (highlight-regexp org-ref-label-re 'org-ref-label-face)
358 (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
361 (when org-ref-colorize-links
362 (add-hook 'org-mode-hook 'org-ref-colorize-links))
364 ;; * General org-ref utilities
365 (defun org-ref-strip-string (string)
366 "Strip leading and trailing whitespace from the STRING."
367 (replace-regexp-in-string
368 (concat search-whitespace-regexp "$" ) ""
369 (replace-regexp-in-string
370 (concat "^" search-whitespace-regexp ) "" string)))
372 (defun org-ref-split-and-strip-string (string)
373 "Split key-string and strip keys in STRING.
374 Assumes the key-string is comma delimited."
375 (mapcar 'org-ref-strip-string (split-string string ",")))
377 (defun org-ref-reftex-get-bib-field (field entry &optional format)
378 "Similar to reftex-get-bib-field, but removes enclosing braces and quotes in FIELD in the bibtex ENTRY.
379 Optional argument FORMAT bibtex format."
381 (setq result (reftex-get-bib-field field entry format))
382 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
383 (setq result (substring result 1 -1)))
384 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
385 (setq result (substring result 1 -1)))
388 (defun org-ref-reftex-format-citation (entry format)
389 "Return a formatted string for the bibtex ENTRY (from bibtex-parse-entry) according to the FORMAT argument.
390 The format is a string with these percent escapes.
392 In the format, the following percent escapes will be expanded.
394 %l The BibTeX label of the citation.
395 %a List of author names, see also `reftex-cite-punctuation'.
396 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
397 %A First author name only.
398 %e Works like %a, but on list of editor names. (%2e and %E work a well)
400 It is also possible to access all other BibTeX database fields:
401 %b booktitle %c chapter %d edition %h howpublished
402 %i institution %j journal %k key %m month
403 %n number %o organization %p pages %P first page
404 %r address %s school %u publisher %t title
406 %B booktitle, abbreviated %T title, abbreviated
411 Usually, only %l is needed. The other stuff is mainly for the echo area
412 display, and for (setq reftex-comment-citations t).
414 %< as a special operator kills punctuation and space around it after the
415 string has been formatted.
417 A pair of square brackets indicates an optional argument, and RefTeX
418 will prompt for the values of these arguments.
420 Beware that all this only works with BibTeX database files. When
421 citations are made from the \bibitems in an explicit thebibliography
422 environment, only %l is available."
423 ;; Format a citation from the info in the BibTeX ENTRY
424 (unless (stringp format) (setq format "\\cite{%l}"))
426 (if (and reftex-comment-citations
427 (string-match "%l" reftex-cite-comment-format))
428 (error "Reftex-cite-comment-format contains invalid %%l"))
431 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
433 (let ((n (string-to-number (match-string 4 format)))
434 (l (string-to-char (match-string 5 format)))
440 (org-ref-reftex-get-bib-field "&key" entry)
441 (if reftex-comment-citations
442 reftex-cite-comment-format
444 ((= l ?a) (reftex-format-names
445 (reftex-get-bib-names "author" entry)
447 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
448 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
449 ((= l ?B) (reftex-abbreviate-title
450 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
451 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
452 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
453 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
454 ((= l ?e) (reftex-format-names
455 (reftex-get-bib-names "editor" entry)
457 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
458 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
459 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
460 ((= l ?j) (org-ref-reftex-get-bib-field "journal" entry))
461 ((= l ?k) (org-ref-reftex-get-bib-field "key" entry))
462 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
463 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
464 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
465 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
466 ((= l ?P) (car (split-string
467 (org-ref-reftex-get-bib-field "pages" entry)
469 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
470 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
471 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
472 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
473 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
474 ;; strip enclosing brackets from title if they are there
475 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
476 ((= l ?T) (reftex-abbreviate-title
477 (org-ref-reftex-get-bib-field "title" entry)))
478 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
479 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
482 (setq b (match-beginning 2) e (match-end 2))
483 (setq b (match-beginning 3) e (match-end 3)))
484 (setq format (concat (substring format 0 b) rpl (substring format e)))))
485 (while (string-match "%%" format)
486 (setq format (replace-match "%" t t format)))
487 (while (string-match "[ ,.;:]*%<" format)
488 (setq format (replace-match "" t t format)))
489 ;; also replace carriage returns, tabs, and multiple whitespaces
490 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
493 (defun org-ref-get-bibtex-entry-citation (key)
494 "Return a string for the bibliography entry corresponding to KEY.
495 Format according to the type in `org-ref-bibliography-entry-format'."
497 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
498 (file) (entry) (bibtex-entry) (entry-type) (format))
500 (setq file (catch 'result
501 (loop for file in org-ref-bibliography-files do
502 (if (org-ref-key-in-file-p key (file-truename file))
504 (message "%s not found in %s"
505 key (file-truename file))))))
508 (insert-file-contents file)
509 (bibtex-search-entry key nil 0)
510 (setq bibtex-entry (bibtex-parse-entry))
511 ;; downcase field names so they work in the format-citation code
512 (dolist (cons-cell bibtex-entry)
513 (setf (car cons-cell) (downcase (car cons-cell))))
514 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
515 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
517 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
518 ;; if no format, we use the bibtex entry itself as a fallback
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 "Return an html string for the bibliography entry corresponding to KEY."
545 (setq output (org-ref-get-bibtex-entry-citation key))
547 (setq output (replace-regexp-in-string "\\\\&" "&" output))
548 ;; hack to replace {} around text
549 (setq output (replace-regexp-in-string "{" "" output))
550 (setq output (replace-regexp-in-string "}" "" output))
551 ;; get rid of empty parens
552 (setq output (replace-regexp-in-string "()" "" output))
553 ;; get rid of empty link and doi
554 (setq output (replace-regexp-in-string " <a href=\"\">link</a>\\." "" output))
555 (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
556 (format "<li><a id=\"%s\">[%s] %s</a></li>"
559 (defun org-ref-get-html-bibliography ()
560 "Create an html bibliography when there are keys."
561 (let ((keys (org-ref-get-bibtex-keys)))
563 (concat "<h1>Bibliography</h1>
565 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
568 (defun org-ref-get-bibtex-entry-org (key)
569 "Return an org string for the bibliography entry corresponding to KEY."
570 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
571 (file) (entry) (bibtex-entry) (entry-type) (format))
573 (setq file (catch 'result
574 (loop for file in org-ref-bibliography-files do
575 (if (org-ref-key-in-file-p key (file-truename file))
577 (message "%s not found in %s" key (file-truename file))))))
580 (insert-file-contents file)
581 (bibtex-search-entry key nil 0)
582 (setq entry (bibtex-parse-entry))
587 " (org-ref-reftex-get-bib-field "author" entry)
588 (org-ref-reftex-get-bib-field "title" entry)
589 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
590 (mapconcat (lambda (element) (format " :%s: %s"
591 (upcase (car element))
596 (defun org-ref-get-org-bibliography ()
597 "Create an org bibliography when there are keys."
598 (let ((keys (org-ref-get-bibtex-keys)))
600 (concat "* Bibliography
602 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
605 (defun org-ref-get-bibtex-entry-ascii (key)
606 "Return an ascii string for the bibliography entry corresponding to KEY."
608 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
610 (defun org-ref-get-ascii-bibliography ()
611 "Create an html bibliography when there are keys."
612 (let ((keys (org-ref-get-bibtex-keys)))
618 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
622 ;; ** bibliography and bibliographystyle
623 (org-add-link-type "bibliography"
624 ;; this code is run on clicking. The bibliography
625 ;; may contain multiple files. this code finds the
626 ;; one you clicked on and opens it.
627 (lambda (link-string)
628 ;; get link-string boundaries we have to go to the
629 ;; beginning of the line, and then search forward
631 ;; object is the link you clicked on
632 (object (org-element-context))
633 (link-string-beginning)
637 (goto-char (org-element-property :begin object))
638 (search-forward link-string nil nil 1)
639 (setq link-string-beginning (match-beginning 0))
640 (setq link-string-end (match-end 0)))
642 ;; Make sure point is in the link-path.
643 (if (< cp link-string-beginning)
644 (goto-char link-string-beginning))
645 ;; We set the reftex-default-bibliography
646 ;; here. it should be a local variable only in
647 ;; the current buffer. We need this for using
648 ;; reftex to do citations.
649 (set (make-local-variable 'reftex-default-bibliography)
651 (org-element-property :path object) ","))
653 ;; now if we have comma separated bibliographies
654 ;; we find the one clicked on. we want to
655 ;; search forward to next comma from point
657 (if (search-forward "," link-string-end 1 1)
659 (setq key-end (- (match-end 0) 1))
660 ;; no comma found so take the point
661 (setq key-end (point))))
662 ;; and backward to previous comma from point
664 (if (search-backward "," link-string-beginning 1 1)
666 (setq key-beginning (+ (match-beginning 0) 1))
667 (setq key-beginning (point)))) ; no match found
668 ;; save the key we clicked on.
669 (setq bibfile (org-ref-strip-string
670 (buffer-substring key-beginning key-end)))
671 ;; open file on click
672 (find-file bibfile)))
675 (lambda (keyword desc format)
677 ((eq format 'org) (org-ref-get-org-bibliography))
678 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
679 ((eq format 'html) (org-ref-get-html-bibliography))
681 ;; write out the latex bibliography command
682 (format "\\bibliography{%s}"
683 (replace-regexp-in-string
687 (mapcar 'expand-file-name
688 (split-string keyword ","))
691 (org-add-link-type "nobibliography"
692 ;; this code is run on clicking. The bibliography
693 ;; may contain multiple files. this code finds the
694 ;; one you clicked on and opens it.
695 (lambda (link-string)
696 ;; get link-string boundaries
697 ;; we have to go to the beginning of the line, and then search forward
700 ;; object is the link you clicked on
701 (object (org-element-context))
703 (link-string-beginning)
707 (goto-char (org-element-property :begin object))
708 (search-forward link-string nil nil 1)
709 (setq link-string-beginning (match-beginning 0))
710 (setq link-string-end (match-end 0)))
712 ;; We set the reftex-default-bibliography
713 ;; here. it should be a local variable only in
714 ;; the current buffer. We need this for using
715 ;; reftex to do citations.
716 (set (make-local-variable 'reftex-default-bibliography)
717 (split-string (org-element-property :path object) ","))
719 ;; now if we have comma separated bibliographies
720 ;; we find the one clicked on. we want to
721 ;; search forward to next comma from point
723 (if (search-forward "," link-string-end 1 1)
724 (setq key-end (- (match-end 0) 1)) ; we found a match
725 (setq key-end (point)))) ; no comma found so take the point
726 ;; and backward to previous comma from point
728 (if (search-backward "," link-string-beginning 1 1)
729 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
730 (setq key-beginning (point)))) ; no match found
731 ;; save the key we clicked on.
732 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
733 (find-file bibfile))) ; open file on click
736 (lambda (keyword desc format)
738 ((eq format 'org) (org-ref-get-org-bibliography))
739 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
740 ((eq format 'html) (org-ref-get-html-bibliography))
742 ;; write out the latex bibliography command
743 (format "\\nobibliography{%s}"
744 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
745 (mapcar 'expand-file-name
746 (split-string keyword ","))
749 (org-add-link-type "printbibliography"
750 (lambda (arg) (message "Nothing implemented for clicking here."))
751 (lambda (keyword desc format)
753 ((eq format 'org) (org-ref-get-org-bibliography))
754 ((eq format 'html) (org-ref-get-html-bibliography))
756 ;; write out the biblatex bibliography command
757 "\\printbibliography"))))
759 (org-add-link-type "bibliographystyle"
760 (lambda (arg) (message "Nothing implemented for clicking here."))
761 (lambda (keyword desc format)
764 ;; write out the latex bibliography command
765 (format "\\bibliographystyle{%s}" keyword))
766 ;; Other styles should not have an output for this
771 (defun org-bibliographystyle-complete-link (&optional arg)
772 "Completion function for bibliographystyle link.
774 (format "bibliographystyle:%s" (ido-completing-read
776 '("unsrt" "plain" "alpha"
778 ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
779 "dinat" "humannat" "plainnat"
780 "abbrnat" "unsrtnat" "rusnat"
784 (defun org-bibliography-complete-link (&optional arg)
785 "Completion function for bibliography link.
787 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
790 (defun org-ref-insert-bibliography-link ()
791 "Insert a bibliography with completion."
793 (insert (org-bibliography-complete-link)))
797 (org-add-link-type "addbibresource"
798 ;; this code is run on clicking. The addbibresource
799 ;; may contain multiple files. this code finds the
800 ;; one you clicked on and opens it.
801 (lambda (link-string)
802 ;; get link-string boundaries
803 ;; we have to go to the beginning of the line, and then search forward
806 ;; object is the link you clicked on
807 (object (org-element-context))
809 (link-string-beginning)
813 (goto-char (org-element-property :begin object))
814 (search-forward link-string nil nil 1)
815 (setq link-string-beginning (match-beginning 0))
816 (setq link-string-end (match-end 0)))
818 ;; We set the reftex-default-addbibresource
819 ;; here. it should be a local variable only in
820 ;; the current buffer. We need this for using
821 ;; reftex to do citations.
822 (set (make-local-variable 'reftex-default-addbibresource)
823 (split-string (org-element-property :path object) ","))
825 ;; now if we have comma separated bibliographies
826 ;; we find the one clicked on. we want to
827 ;; search forward to next comma from point
829 (if (search-forward "," link-string-end 1 1)
830 (setq key-end (- (match-end 0) 1)) ; we found a match
831 (setq key-end (point)))) ; no comma found so take the point
832 ;; and backward to previous comma from point
834 (if (search-backward "," link-string-beginning 1 1)
835 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
836 (setq key-beginning (point)))) ; no match found
837 ;; save the key we clicked on.
838 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
839 (find-file bibfile))) ; open file on click
842 (lambda (keyword desc format)
844 ((eq format 'html) (format "")); no output for html
846 ;; write out the latex addbibresource command
847 (format "\\addbibresource{%s}" keyword)))))
849 ;; ** List of figures
850 (defun org-ref-list-of-figures (&optional arg)
851 "Generate buffer with list of figures in them.
854 (save-excursion (widen)
855 (let* ((c-b (buffer-name))
858 (org-element-map (org-element-parse-buffer) 'link
860 "create a link for to the figure"
862 (and (string= (org-element-property :type link) "file")
864 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
865 (org-element-property :path link)))
868 (let* ((start (org-element-property :begin link))
869 (parent (car (cdr (org-element-property :parent link))))
870 (caption (caaar (plist-get parent :caption)))
871 (name (plist-get parent :name)))
874 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
875 c-b start counter (or name "") caption)
877 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
878 c-b start counter (or name "")))))))))
879 (switch-to-buffer "*List of Figures*")
880 (setq buffer-read-only nil)
883 (insert (mapconcat 'identity list-of-figures ""))
884 (setq buffer-read-only t)
885 (use-local-map (copy-keymap org-mode-map))
886 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
890 'org-ref-list-of-figures ; on click
891 (lambda (keyword desc format)
894 (format "\\listoffigures")))))
897 (defun org-ref-list-of-tables (&optional arg)
898 "Generate a buffer with a list of tables.
903 (let* ((c-b (buffer-name))
906 (org-element-map (org-element-parse-buffer 'element) 'table
908 "create a link for to the table"
910 (let ((start (org-element-property :begin table))
911 (name (org-element-property :name table))
912 (caption (caaar (org-element-property :caption table))))
915 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
916 c-b start counter (or name "") caption)
918 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
919 c-b start counter (or name ""))))))))
920 (switch-to-buffer "*List of Tables*")
921 (setq buffer-read-only nil)
924 (insert (mapconcat 'identity list-of-tables ""))
925 (setq buffer-read-only t)
926 (use-local-map (copy-keymap org-mode-map))
927 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
931 'org-ref-list-of-tables
932 (lambda (keyword desc format)
935 (format "\\listoftables")))))
939 (defun org-ref-count-labels (label)
940 "Counts number of matches for LABEL in the document."
941 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
942 ;; for tblname, it is not enough to get word boundary
943 ;; tab-little and tab-little-2 match then.
944 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
945 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
946 ;; this is the org-format #+label:
947 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
948 (let ((custom-id-count 0))
951 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
952 (setq custom-id-count (+ 1 custom-id-count)))))
958 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
959 (let ((count (org-ref-count-labels label)))
960 (message (format "%s occurence%s"
966 (org-ref-count-labels label))))
967 (lambda (keyword desc format)
969 ((eq format 'html) (format "(<label>%s</label>)" path))
971 (format "\\label{%s}" keyword)))))
973 (defun org-label-store-link ()
974 "Store a link to a label. The output will be a ref to that label."
975 ;; First we have to make sure we are on a label link.
976 (let* ((object (org-element-context)))
977 (when (and (equal (org-element-type object) 'link)
978 (equal (org-element-property :type object) "label"))
979 (org-store-link-props
981 :link (concat "ref:" (org-element-property :path object))))
983 ;; Store link on table
984 (when (equal (org-element-type object) 'table)
985 (org-store-link-props
987 :link (concat "ref:" (org-element-property :name object))))
989 ;; store link on heading with custom_id
990 ;; this is not a ref link, but it is still what you want
991 (when (and (equal (org-element-type object) 'headline)
992 (org-entry-get (point) "CUSTOM_ID"))
993 (org-store-link-props
995 :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
997 ;; and to #+label: lines
999 (when (and (equal (org-element-type object) 'paragraph)
1000 (org-element-property :name object))
1001 (org-store-link-props
1003 :link (concat "ref:" (org-element-property :name object))))))
1005 (add-hook 'org-store-link-functions 'org-label-store-link)
1011 "on clicking goto the label. Navigate back with C-c &"
1012 (org-mark-ring-push)
1013 ;; next search from beginning of the buffer
1014 ;; it is possible you would not find the label if narrowing is in effect
1020 (goto-char (point-min))
1021 (re-search-forward (format "label:%s\\b" label) nil t))
1025 (goto-char (point-min))
1026 (re-search-forward (format "\\label{%s}" label) nil t))
1028 ;; #+label: name org-definition
1030 (goto-char (point-min))
1032 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1036 (goto-char (point-min))
1038 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1040 ;; we did not find anything, so go back to where we came
1041 (org-mark-ring-goto)
1042 (error "%s not found" label))
1044 (message "go back with (org-mark-ring-goto) `C-c &`"))
1046 (lambda (keyword desc format)
1048 ((eq format 'html) (format "(<ref>%s</ref>)" path))
1050 (format "\\ref{%s}" keyword)))))
1053 (defun org-ref-get-org-labels ()
1054 "Return a list of #+LABEL: labels."
1056 (goto-char (point-min))
1057 (let ((matches '()))
1058 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1059 ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1060 ;; who would have thought you have save match data here? Trust me. When
1061 ;; I wrote this, you did.
1062 (unless (save-match-data (equal (car (org-element-at-point)) 'table))
1063 (add-to-list 'matches (match-string-no-properties 1) t)))
1067 (defun org-ref-get-custom-ids ()
1068 "Return a list of custom_id properties in the buffer."
1069 (let ((results '()) custom_id)
1072 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1073 (when (not (null custom_id))
1074 (setq results (append results (list custom_id)))))))
1078 (defun org-ref-get-latex-labels ()
1079 "Return list of matchin LaTeX defined labels in buffer."
1081 (goto-char (point-min))
1082 (let ((matches '()))
1083 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1084 (add-to-list 'matches (match-string-no-properties 1) t))
1088 (defun org-ref-get-tblnames ()
1089 "Return list of table names in the buffer."
1090 (org-element-map (org-element-parse-buffer 'element) 'table
1092 (org-element-property :name table))))
1095 (defun org-ref-get-labels ()
1096 "Return a list of labels in the buffer that you can make a ref link to.
1097 This is used to complete ref links and in helm menus."
1101 (goto-char (point-min))
1102 (let ((matches '()))
1103 ;; these are the org-ref label:stuff kinds
1104 (while (re-search-forward
1105 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1106 (add-to-list 'matches (match-string-no-properties 1) t))
1107 ;; now add all the other kinds of labels.
1110 (org-ref-get-org-labels)
1112 (org-ref-get-latex-labels)
1113 ;; #+tblname: and actually #+label
1114 (org-ref-get-tblnames)
1116 (org-ref-get-custom-ids))))))
1119 (defun org-ref-helm-insert-label-link ()
1120 "Insert a label link. helm just shows you what labels already exist.
1121 If you are on a label link, replace it."
1123 (let* ((labels (org-ref-get-labels))
1124 (cb (current-buffer)))
1125 (helm :sources `(((name . "Existing labels")
1126 (candidates . ,labels)
1127 ;; default action is to open to the label
1128 (action . (lambda (label)
1129 ;; unfortunately I do not have markers here
1130 (org-open-link-from-string
1131 (format "ref:%s" label))))
1132 ;; if you select a label, replace current one
1133 (action . (lambda (label)
1134 (switch-to-buffer ,cb)
1136 ;; no prefix or on a link
1137 ((equal helm-current-prefix-arg nil)
1138 (let* ((object (org-element-context))
1139 (last-char (save-excursion
1140 (goto-char (org-element-property :end object))
1142 (if (looking-at " ")
1145 (when (-contains? '("label")
1146 (org-element-property :type object))
1147 ;; we are on a link, so replace it.
1150 (org-element-property :begin object)
1151 (org-element-property :end object))
1153 (replace-regexp-in-string
1154 (org-element-property :path object)
1156 (org-element-property :raw-link object))
1158 ;; no prefix options defined
1160 ;; no matching selection creates a new label
1161 ((name . "Create new label")
1163 ;; default action creates a new label, or replaces old one
1164 (action . (lambda (label)
1165 (switch-to-buffer ,cb)
1166 (let* ((object (org-element-context))
1167 (last-char (save-excursion
1168 (goto-char (org-element-property :end object))
1170 (if (looking-at " ")
1173 (if (-contains? '("label")
1174 (org-element-property :type object))
1175 ;; we are on a link, so replace it.
1178 (org-element-property :begin object)
1179 (org-element-property :end object))
1181 (replace-regexp-in-string
1182 (org-element-property :path object)
1184 (org-element-property :raw-link object))
1191 helm-pattern))))))))))))
1194 (defun org-ref-complete-link (&optional arg)
1195 "Completion function for ref links.
1196 Optional argument ARG Does nothing."
1198 (setq label (completing-read "label: " (org-ref-get-labels)))
1199 (format "ref:%s" label)))
1202 (defun org-ref-insert-ref-link ()
1203 "Completion function for a ref link."
1205 (insert (org-ref-complete-link)))
1208 (defun org-ref-helm-insert-ref-link ()
1209 "Helm menu to insert ref links to labels in the document.
1210 If you are on link, replace with newly selected label.
1211 Use C-u to insert a different kind of ref link.
1212 Use C-u C-u to insert a [[#custom-id]] link"
1214 (let* ((labels (org-ref-get-labels))
1215 (bs (buffer-string))
1216 (contexts (with-temp-buffer
1218 (mapcar 'org-ref-get-label-context labels)))
1219 (cb (current-buffer)))
1221 (helm :input (thing-at-point 'word)
1222 :sources `(((name . "Available labels to ref")
1223 (candidates . ,(loop for label in labels
1224 for context in contexts
1225 ;; we do some kludgy adding spaces
1226 ;; and bars to make it "easier" to
1228 collect (cons (concat
1233 (split-string context "\n")
1236 ;; default action to replace or insert ref link.
1237 (action . (lambda (label)
1238 (switch-to-buffer ,cb)
1241 ;; no prefix or on a link
1242 ((equal helm-current-prefix-arg nil)
1243 (let* ((object (org-element-context))
1244 (last-char (save-excursion
1245 (goto-char (org-element-property :end object))
1247 (if (looking-at " ")
1250 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1251 (org-element-property :type object))
1252 ;; we are on a link, so replace it.
1255 (org-element-property :begin object)
1256 (org-element-property :end object))
1258 (replace-regexp-in-string
1259 (org-element-property :path object)
1261 (org-element-property :raw-link object))
1263 ;; insert a new link
1268 ;; one prefix, alternate ref link
1269 ((equal helm-current-prefix-arg '(4))
1272 (helm :sources '((name . "Ref link types")
1273 (candidates . ("ref" "eqref" "pageref" "nameref"))
1274 (action . (lambda (x) x))))
1276 ;; two prefixes, insert section custom-id link
1277 ((equal helm-current-prefix-arg '(16))
1279 (format "[[#%s]]" label)))
1287 "on clicking goto the label. Navigate back with C-c &"
1288 (org-mark-ring-push)
1289 ;; next search from beginning of the buffer
1295 (goto-char (point-min))
1296 (re-search-forward (format "label:%s\\b" label) nil t))
1300 (goto-char (point-min))
1301 (re-search-forward (format "\\label{%s}" label) nil t))
1303 ;; #+label: name org-definition
1305 (goto-char (point-min))
1307 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1311 (goto-char (point-min))
1313 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1314 ;; we did not find anything, so go back to where we came
1315 (org-mark-ring-goto)
1316 (error "%s not found" label))
1317 (message "go back with (org-mark-ring-goto) `C-c &`"))
1319 (lambda (keyword desc format)
1321 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1323 (format "\\pageref{%s}" keyword)))))
1326 (defun org-pageref-complete-link (&optional arg)
1327 "Completion function for ref links.
1328 Optional argument ARG Does nothing."
1330 (setq label (completing-read "label: " (org-ref-get-labels)))
1331 (format "ref:%s" label)))
1334 (defun org-pageref-insert-ref-link ()
1335 "Insert a pageref link with completion."
1337 (insert (org-pageref-complete-link)))
1344 "on clicking goto the label. Navigate back with C-c &"
1345 (org-mark-ring-push)
1346 ;; next search from beginning of the buffer
1352 (goto-char (point-min))
1353 (re-search-forward (format "\\label{%s}" label) nil t))
1355 ;; we did not find anything, so go back to where we came
1356 (org-mark-ring-goto)
1357 (error "%s not found" label))
1358 (message "go back with (org-mark-ring-goto) `C-c &`"))
1360 (lambda (keyword desc format)
1362 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1364 (format "\\nameref{%s}" keyword)))))
1371 "on clicking goto the label. Navigate back with C-c &"
1372 (org-mark-ring-push)
1373 ;; next search from beginning of the buffer
1375 (goto-char (point-min))
1378 ;; search forward for the first match
1380 (re-search-forward (format "label:%s" label) nil t)
1382 (re-search-forward (format "\\label{%s}" label) nil t)
1383 ;; #+label: name org-definition
1384 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1385 (org-mark-ring-goto)
1386 (error "%s not found" label))
1387 (message "go back with (org-mark-ring-goto) `C-c &`"))
1389 (lambda (keyword desc format)
1391 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1393 (format "\\eqref{%s}" keyword)))))
1397 (defun org-ref-get-bibtex-key-under-cursor ()
1398 "Return key under the bibtex cursor.
1399 We search forward from
1400 point to get a comma, or the end of the link, and then backwards
1401 to get a comma, or the beginning of the link. that delimits the
1402 keyword we clicked on. We also strip the text properties."
1403 (let* ((object (org-element-context))
1404 (link-string (org-element-property :path object)))
1405 ;; you may click on the part before the citations. here we make
1406 ;; sure to move to the beginning so you get the first citation.
1408 (goto-char (org-element-property :begin object))
1409 (search-forward link-string (org-element-property :end object))
1410 (goto-char (match-beginning 0))
1411 ;; check if we clicked before the path and move as needed.
1412 (unless (< cp (point))
1415 (if (not (org-element-property :contents-begin object))
1416 ;; this means no description in the link
1418 ;; we need the link path start and end
1420 (goto-char (org-element-property :begin object))
1421 (search-forward link-string nil nil 1)
1422 (setq link-string-beginning (match-beginning 0))
1423 (setq link-string-end (match-end 0)))
1425 ;; The key is the text between commas, or the link boundaries
1427 (if (search-forward "," link-string-end t 1)
1428 (setq key-end (- (match-end 0) 1)) ; we found a match
1429 (setq key-end link-string-end))) ; no comma found so take the end
1430 ;; and backward to previous comma from point which defines the start character
1432 (if (search-backward "," link-string-beginning 1 1)
1433 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1434 (setq key-beginning link-string-beginning))) ; no match found
1435 ;; save the key we clicked on.
1437 (org-ref-strip-string
1438 (buffer-substring key-beginning key-end)))
1439 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1441 ;; link with description. assume only one key
1444 (defun org-ref-find-bibliography ()
1445 "Find the bibliography in the buffer.
1446 This function sets and returns cite-bibliography-files, which is a list of files
1447 either from bibliography:f1.bib,f2.bib
1448 \bibliography{f1,f2}
1449 internal bibliographies
1451 falling back to what the user has set in `org-ref-default-bibliography'"
1454 (goto-char (point-min))
1455 ;; look for a bibliography link
1456 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1457 (setq org-ref-bibliography-files
1458 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1459 (throw 'result org-ref-bibliography-files))
1462 ;; we did not find a bibliography link. now look for \bibliography
1463 (goto-char (point-min))
1464 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1465 ;; split, and add .bib to each file
1466 (setq org-ref-bibliography-files
1467 (mapcar (lambda (x) (concat x ".bib"))
1468 (mapcar 'org-ref-strip-string
1469 (split-string (match-string 1) ","))))
1470 (throw 'result org-ref-bibliography-files))
1472 ;; no bibliography found. maybe we need a biblatex addbibresource
1473 (goto-char (point-min))
1474 ;; look for a bibliography link
1475 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1476 (setq org-ref-bibliography-files
1477 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1478 (throw 'result org-ref-bibliography-files))
1480 ;; we did not find anything. use defaults
1481 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1483 ;; set reftex-default-bibliography so we can search
1484 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1485 org-ref-bibliography-files)
1487 (defun org-ref-key-in-file-p (key filename)
1488 "Determine if the KEY is in the FILENAME."
1489 (save-current-buffer
1490 (let ((bibtex-files (list filename)))
1491 ;; This is something I am trying because when the bibtex file is open, and
1492 ;; you have added to it, the only way I find to get the update to update
1493 ;; is to close it and reopen it. or to save it and revert it.
1494 (when (get-file-buffer filename)
1495 (set-buffer (get-file-buffer filename))
1497 (revert-buffer t t))
1498 (bibtex-search-entry key t))))
1500 (defun org-ref-get-bibtex-key-and-file (&optional key)
1501 "Return the bibtex KEY and file that it is in. If no key is provided, get one under point."
1502 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1505 (setq key (org-ref-get-bibtex-key-under-cursor)))
1506 (setq file (catch 'result
1507 (loop for file in org-ref-bibliography-files do
1508 (if (org-ref-key-in-file-p key (file-truename file))
1509 (throw 'result file)))))
1512 ;; *** key at point functions
1514 (defun org-ref-open-pdf-at-point ()
1515 "Open the pdf for bibtex key under point if it exists."
1517 (let* ((results (org-ref-get-bibtex-key-and-file))
1519 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1520 (if (file-exists-p pdf-file)
1521 (org-open-file pdf-file)
1522 (message "no pdf found for %s" key))))
1525 (defun org-ref-open-url-at-point ()
1526 "Open the url for bibtex key under point."
1528 (let* ((results (org-ref-get-bibtex-key-and-file))
1530 (bibfile (cdr results)))
1533 (insert-file-contents bibfile)
1534 (bibtex-search-entry key)
1535 ;; I like this better than bibtex-url which does not always find
1538 (let ((url (bibtex-autokey-get-field "url")))
1540 (browse-url (s-trim url))
1543 (let ((doi (bibtex-autokey-get-field "doi")))
1545 (if (string-match "^http" doi)
1547 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1548 (throw 'done nil))))))))
1551 (defun org-ref-open-notes-at-point ()
1552 "Open the notes for bibtex key under point."
1554 (let* ((results (org-ref-get-bibtex-key-and-file))
1556 (bibfile (cdr results)))
1559 (insert-file-contents bibfile)
1560 (bibtex-search-entry key)
1561 (org-ref-open-bibtex-notes)))))
1564 (defun org-ref-citation-at-point ()
1565 "Give message of current citation at point."
1567 (let* ((cb (current-buffer))
1568 (results (org-ref-get-bibtex-key-and-file))
1570 (bibfile (cdr results)))
1571 (message "%s" (progn
1573 (insert-file-contents bibfile)
1574 (bibtex-search-entry key)
1575 (org-ref-bib-citation))))))
1578 (defun org-ref-open-citation-at-point ()
1579 "Open bibtex file to key at point."
1581 (let* ((cb (current-buffer))
1582 (results (org-ref-get-bibtex-key-and-file))
1584 (bibfile (cdr results)))
1586 (bibtex-search-entry key)))
1590 (defvar org-ref-cite-menu-funcs '()
1591 "Functions to run on cite click menu.
1592 Each entry is a list of (key menu-name function).
1593 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.")
1596 (defvar org-ref-user-cite-menu-funcs
1597 '(("C" "rossref" org-ref-crossref-at-point)
1598 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1599 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1600 "User-defined functions to run on bibtex key at point.")
1603 (defun org-ref-copy-entry-as-summary ()
1604 "Copy the bibtex entry for the citation at point as a summary."
1606 (save-window-excursion
1607 (org-ref-open-citation-at-point)
1608 (kill-new (org-ref-bib-citation))))
1611 (defun org-ref-copy-entry-at-point-to-file ()
1612 "Copy the bibtex entry for the citation at point to NEW-FILE.
1613 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."
1615 (let ((new-file (ido-completing-read
1617 (append org-ref-default-bibliography
1618 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1619 (key (org-ref-get-bibtex-key-under-cursor)))
1620 (save-window-excursion
1621 (org-ref-open-citation-at-point)
1622 (bibtex-copy-entry-as-kill))
1624 (let ((bibtex-files (list (file-truename new-file))))
1625 (if (assoc key (bibtex-global-key-alist))
1626 (message "That key already exists in %s" new-file)
1628 (save-window-excursion
1629 (find-file new-file)
1630 (goto-char (point-max))
1631 ;; make sure we are at the beginning of a line.
1632 (unless (looking-at "^") (insert "\n\n"))
1637 (defun org-ref-get-doi-at-point ()
1638 "Get doi for key at point."
1639 (let* ((results (org-ref-get-bibtex-key-and-file))
1641 (bibfile (cdr results))
1645 (insert-file-contents bibfile)
1646 (bibtex-search-entry key)
1647 (setq doi (bibtex-autokey-get-field "doi"))
1648 ;; in case doi is a url, remove the url part.
1649 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1652 ;; **** functions that operate on key at point for click menu
1653 (defun org-ref-wos-at-point ()
1654 "Open the doi in wos for bibtex key under point."
1656 (doi-utils-wos (org-ref-get-doi-at-point)))
1659 (defun org-ref-wos-citing-at-point ()
1660 "Open the doi in wos citing articles for bibtex key under point."
1662 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1665 (defun org-ref-wos-related-at-point ()
1666 "Open the doi in wos related articles for bibtex key under point."
1668 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1671 (defun org-ref-google-scholar-at-point ()
1672 "Open the doi in google scholar for bibtex key under point."
1674 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1677 (defun org-ref-pubmed-at-point ()
1678 "Open the doi in pubmed for bibtex key under point."
1680 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1683 (defun org-ref-crossref-at-point ()
1684 "Open the doi in crossref for bibtex key under point."
1686 (doi-utils-crossref (org-ref-get-doi-at-point)))
1688 ;; *** Minibuffer menu
1690 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1691 "Action when a cite link is clicked on.
1692 Provides a menu of context sensitive actions. If the bibtex entry
1693 has a pdf, you get an option to open it. If there is a doi, you
1694 get a lot of options. LINK-STRING is used by the link function."
1696 (let* ((results (org-ref-get-bibtex-key-and-file))
1698 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1699 (bibfile (cdr results))
1700 (url (save-excursion
1702 (insert-file-contents bibfile)
1703 (bibtex-search-entry key)
1704 (bibtex-autokey-get-field "url"))))
1705 (doi (save-excursion
1707 (insert-file-contents bibfile)
1708 (bibtex-search-entry key)
1709 ;; I like this better than bibtex-url which does not always find
1711 (bibtex-autokey-get-field "doi")))))
1713 (when (string= "" doi) (setq doi nil))
1714 (when (string= "" url) (setq url nil))
1715 (setq org-ref-cite-menu-funcs '())
1721 'org-ref-cite-menu-funcs
1722 '("o" "pen" org-ref-open-citation-at-point)))
1725 (when (file-exists-p pdf-file)
1727 'org-ref-cite-menu-funcs
1728 `("p" "df" ,org-ref-open-pdf-function) t))
1732 'org-ref-cite-menu-funcs
1733 '("n" "otes" org-ref-open-notes-at-point) t)
1738 'org-ref-cite-menu-funcs
1739 '("u" "rl" org-ref-open-url-at-point) t))
1744 'org-ref-cite-menu-funcs
1745 '("w" "os" org-ref-wos-at-point) t)
1748 'org-ref-cite-menu-funcs
1749 '("c" "iting" org-ref-wos-citing-at-point) t)
1752 'org-ref-cite-menu-funcs
1753 '("r" "elated" org-ref-wos-related-at-point) t)
1756 'org-ref-cite-menu-funcs
1757 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1760 'org-ref-cite-menu-funcs
1761 '("P" "ubmed" org-ref-pubmed-at-point) t))
1763 ;; add user functions
1764 (dolist (tup org-ref-user-cite-menu-funcs)
1766 'org-ref-cite-menu-funcs
1771 'org-ref-cite-menu-funcs
1772 '("q" "uit" (lambda ())) t)
1774 ;; now we make a menu
1775 ;; construct menu string as a message
1778 (let* ((results (org-ref-get-bibtex-key-and-file))
1780 (bibfile (cdr results)))
1783 (insert-file-contents bibfile)
1784 (bibtex-search-entry key)
1785 (org-ref-bib-citation))))
1789 (concat "[" (elt tup 0) "]"
1791 org-ref-cite-menu-funcs "")))
1793 (let* ((input (read-char-exclusive))
1795 (char-to-string input) org-ref-cite-menu-funcs)))
1796 ;; now run the function (2nd element in choice)
1803 ;; *** Generation of the cite links
1804 (defmacro org-ref-make-completion-function (type)
1805 "Macro to make a link completion function for a link of TYPE."
1806 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1812 (let ((bibtex-files (org-ref-find-bibliography)))
1813 (bibtex-global-key-alist))))))
1815 (defmacro org-ref-make-format-function (type)
1816 "Macro to make a format function for a link of TYPE."
1817 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1822 (format "[[#%s][%s]]" key key))
1823 (org-ref-split-and-strip-string keyword) ","))
1830 (org-ref-split-and-strip-string keyword) ",") "]"))
1835 (format "<a href=\"#%s\">%s</a>" key key))
1836 (org-ref-split-and-strip-string keyword) ","))
1839 (if (string= (substring type -1) "s")
1840 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1841 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1842 (org-ref-split-and-strip-string keyword) ""))
1844 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1845 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1847 ;; for markdown we generate pandoc citations
1850 (desc ;; pre and or post text
1851 (let* ((text (split-string desc "::"))
1855 (format "[@%s," keyword)
1856 (when pre (format " %s" pre))
1857 (when post (format ", %s" post))
1862 (lambda (key) (concat "@" key))
1863 (org-ref-split-and-strip-string keyword)
1866 (defun org-ref-format-citation-description (desc)
1867 "Return formatted citation description.
1868 If the cite link has a DESC (description), it is optional text
1869 for the citation command. You can specify pre and post text by
1870 separating these with ::, for example [[cite:key][pre text::post
1873 ((string-match "::" desc)
1874 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1875 (t (format "[%s]" desc))))
1877 (defun org-ref-define-citation-link (type &optional key)
1878 "Add a citation link of TYPE for org-ref.
1879 With optional KEY, set the reftex binding. For example:
1880 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1881 citez link, with reftex key of z, and the completion function."
1882 (interactive "sCitation Type: \ncKey: ")
1884 ;; create the formatting function
1885 (eval `(org-ref-make-format-function ,type))
1890 org-ref-cite-onclick-function
1891 (quote ,(intern (format "org-ref-format-%s" type)))))
1893 ;; create the completion function
1894 (eval `(org-ref-make-completion-function ,type))
1896 ;; store new type so it works with adding citations, which checks
1897 ;; for existence in this list
1898 (add-to-list 'org-ref-cite-types type)
1900 ;; and finally if a key is specified, we modify the reftex menu
1902 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1903 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1904 `((,key . ,(concat type ":%l")))))))
1906 ;; create all the link types and their completion functions
1907 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1909 (defun org-ref-insert-cite-link (alternative-cite)
1910 "Insert a default citation link using reftex.
1911 If you are on a link, it appends to the end of the link,
1912 otherwise, a new link is inserted. Use a prefix
1913 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1915 (org-ref-find-bibliography)
1916 (let* ((object (org-element-context))
1917 (link-string-beginning (org-element-property :begin object))
1918 (link-string-end (org-element-property :end object))
1919 (path (org-element-property :path object)))
1921 (if (not alternative-cite)
1924 ;; case where we are in a link
1925 ((and (equal (org-element-type object) 'link)
1926 (-contains? org-ref-cite-types (org-element-property :type object)))
1927 (goto-char link-string-end)
1928 ;; sometimes there are spaces at the end of the link
1929 ;; this code moves point pack until no spaces are there
1930 (while (looking-back " ") (backward-char))
1931 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1933 ;; We are next to a link, and we want to append
1936 (and (equal (org-element-type (org-element-context)) 'link)
1937 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1938 (while (looking-back " ") (backward-char))
1939 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1941 ;; insert fresh link
1944 (concat org-ref-default-citation-link
1946 (mapconcat 'identity (reftex-citation t) ",")))))
1948 ;; you pressed a C-u so we run this code
1949 (reftex-citation))))
1951 (defun org-ref-insert-cite-with-completion (type)
1952 "Insert a cite link of TYPE with completion."
1953 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1954 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1956 (defun org-ref-store-bibtex-entry-link ()
1957 "Save a citation link to the current bibtex entry. Save in the default link type."
1959 (let ((link (concat org-ref-default-citation-link
1962 (bibtex-beginning-of-entry)
1963 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1964 (message "saved %s" link)
1965 (push (list link) org-stored-links)
1966 (car org-stored-links)))
1974 (lambda (path desc format)
1977 (format "\\index{%s}" path)))))
1979 ;; this will generate a temporary index of entries in the file.
1983 (let ((*index-links* '())
1984 (*initial-letters* '()))
1987 (org-element-map (org-element-parse-buffer) 'link
1989 (let ((type (nth 0 link))
1990 (plist (nth 1 link)))
1992 (when (equal (plist-get plist ':type) "index")
1995 (cons (plist-get plist :path)
1997 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
1999 (plist-get plist :begin) ;; position of link
2000 ;; grab a description
2002 (goto-char (plist-get plist :begin))
2003 (if (thing-at-point 'sentence)
2005 (replace-regexp-in-string
2006 "\n" "" (thing-at-point 'sentence))
2007 ;; or call it a link
2011 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2013 ;; now first letters
2014 (dolist (link *index-links*)
2015 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2017 ;; now create the index
2018 (switch-to-buffer (get-buffer-create "*index*"))
2021 (insert "#+TITLE: Index\n\n")
2022 (dolist (letter *initial-letters*)
2023 (insert (format "* %s\n" (upcase letter)))
2024 ;; now process the links
2027 (string= letter (substring (car (car *index-links*)) 0 1)))
2028 (let ((link (pop *index-links*)))
2029 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2030 (switch-to-buffer "*index*")))
2032 (lambda (path desc format)
2035 (format "\\printindex")))))
2040 nil ;; no follow action
2041 (lambda (path desc format)
2044 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2050 nil ;; no follow action
2051 (lambda (path desc format)
2054 (format "\\gls{%s}" path)))))
2059 nil ;; no follow action
2060 (lambda (path desc format)
2063 (format "\\glspl{%s}" path)))))
2068 nil ;; no follow action
2069 (lambda (path desc format)
2072 (format "\\Gls{%s}" path)))))
2077 nil ;; no follow action
2078 (lambda (path desc format)
2081 (format "\\Glspl{%s}" path)))))
2084 ;; ** create text citations from a bibtex entry
2085 (defun org-ref-bib-citation ()
2086 "From a bibtex entry, create and return a simple citation string.
2087 This assumes you are in an article."
2089 (bibtex-beginning-of-entry)
2090 (let* ((cb (current-buffer))
2091 (bibtex-expand-strings t)
2092 (entry (loop for (key . value) in (bibtex-parse-entry t)
2093 collect (cons (downcase key) value)))
2094 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2095 (year (reftex-get-bib-field "year" entry))
2096 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2097 (key (reftex-get-bib-field "=key=" entry))
2098 (journal (reftex-get-bib-field "journal" entry))
2099 (volume (reftex-get-bib-field "volume" entry))
2100 (pages (reftex-get-bib-field "pages" entry))
2101 (doi (reftex-get-bib-field "doi" entry))
2102 (url (reftex-get-bib-field "url" entry))
2104 ;;authors, "title", Journal, vol(iss):pages (year).
2105 (format "%s, \"%s\", %s, %s:%s (%s)"
2106 author title journal volume pages year)))
2108 (defun org-ref-bib-html-citation ()
2109 "From a bibtex entry, create and return a simple citation with html links."
2110 (bibtex-beginning-of-entry)
2111 (let* ((cb (current-buffer))
2112 (bibtex-expand-strings t)
2113 (entry (loop for (key . value) in (bibtex-parse-entry t)
2114 collect (cons (downcase key) value)))
2115 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2116 (year (reftex-get-bib-field "year" entry))
2117 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2118 (key (reftex-get-bib-field "=key=" entry))
2119 (journal (reftex-get-bib-field "journal" entry))
2120 (volume (reftex-get-bib-field "volume" entry))
2121 (pages (reftex-get-bib-field "pages" entry))
2122 (doi (reftex-get-bib-field "doi" entry))
2123 (url (reftex-get-bib-field "url" entry)))
2124 ;;authors, "title", Journal, vol(iss):pages (year).
2125 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2126 author title journal volume pages year)
2127 (when url (format " <a href=\"%s\">link</a>" url))
2129 (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
2131 ;; ** Open pdf in bibtex entry
2132 (defun org-ref-open-bibtex-pdf ()
2133 "Open pdf for a bibtex entry, if it exists.
2135 the entry of interest in the bibfile. but does not check that."
2138 (bibtex-beginning-of-entry)
2139 (let* ((bibtex-expand-strings t)
2140 (entry (bibtex-parse-entry t))
2141 (key (reftex-get-bib-field "=key=" entry))
2142 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2144 (if (file-exists-p pdf)
2145 (org-open-link-from-string (format "[[file:%s]]" pdf))
2148 ;; ** Open notes from bibtex entry
2150 (defun org-ref-open-bibtex-notes ()
2151 "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2153 I never did figure out how to use reftex to make this happen
2154 non-interactively. the reftex-format-citation function did not
2155 work perfectly; there were carriage returns in the strings, and
2156 it did not put the key where it needed to be. so, below I replace
2157 the carriage returns and extra spaces with a single space and
2158 construct the heading by hand."
2161 (bibtex-beginning-of-entry)
2162 (let* ((cb (current-buffer))
2163 (bibtex-expand-strings t)
2164 (entry (loop for (key . value) in (bibtex-parse-entry t)
2165 collect (cons (downcase key) value)))
2166 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2167 (year (reftex-get-bib-field "year" entry))
2168 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2169 (key (reftex-get-bib-field "=key=" entry))
2170 (journal (reftex-get-bib-field "journal" entry))
2171 (volume (reftex-get-bib-field "volume" entry))
2172 (pages (reftex-get-bib-field "pages" entry))
2173 (doi (reftex-get-bib-field "doi" entry))
2174 (url (reftex-get-bib-field "url" entry))
2177 ;; save key to clipboard to make saving pdf later easier by pasting.
2180 (kill-ring-save (point-min) (point-max)))
2182 ;; now look for entry in the notes file
2183 (if org-ref-bibliography-notes
2184 (find-file-other-window org-ref-bibliography-notes)
2185 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2187 (goto-char (point-min))
2188 ;; put new entry in notes if we don't find it.
2189 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2190 (funcall org-ref-open-notes-function)
2191 ;; no entry found, so add one
2192 (insert (format "\n** TODO %s - %s" year title))
2204 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2205 key author journal year volume pages doi url key org-ref-pdf-directory key))
2208 (defun org-ref-open-notes-from-reftex ()
2209 "Call reftex, and open notes for selected entry."
2211 (let ((bibtex-key )))
2213 ;; now look for entry in the notes file
2214 (if org-ref-bibliography-notes
2215 (find-file-other-window org-ref-bibliography-notes)
2216 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2218 (goto-char (point-min))
2220 (re-search-forward (format
2222 (first (reftex-citation t)) nil 'end))
2223 (funcall org-ref-open-notes-function))
2225 ;; ** Open bibtex entry in browser
2226 (defun org-ref-open-in-browser ()
2227 "Open the bibtex entry at point in a browser using the url field or doi field."
2230 (bibtex-beginning-of-entry)
2232 (let ((url (bibtex-autokey-get-field "url")))
2237 (let ((doi (bibtex-autokey-get-field "doi")))
2239 (if (string-match "^http" doi)
2241 (browse-url (format "http://dx.doi.org/%s" doi)))
2243 (message "No url or doi found"))))
2245 ;; ** upload entry to citeulike
2247 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2248 "With point in a bibtex entry get bibtex string and submit to citeulike.
2250 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2252 (message "uploading to citeulike")
2254 (bibtex-narrow-to-entry)
2255 (let ((startpos (point-min))
2256 (endpos (point-max))
2257 (bibtex-string (buffer-string))
2258 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2259 (with-temp-buffer (insert bibtex-string)
2260 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2262 ;; ** Build a pdf of the bibtex file
2263 (defun org-ref-build-full-bibliography ()
2264 "Build pdf of all bibtex entries, and open it."
2266 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2267 (bib-base (file-name-sans-extension bibfile))
2268 (texfile (concat bib-base ".tex"))
2269 (pdffile (concat bib-base ".pdf")))
2272 (insert (format "\\documentclass[12pt]{article}
2273 \\usepackage[version=3]{mhchem}
2275 \\usepackage[numbers]{natbib}
2276 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2280 \\bibliographystyle{unsrtnat}
2282 \\end{document}" bib-base))
2284 (shell-command (concat "pdflatex " bib-base))
2285 (shell-command (concat "bibtex " bib-base))
2286 (shell-command (concat "pdflatex " bib-base))
2287 (shell-command (concat "pdflatex " bib-base))
2288 (kill-buffer texfile)
2289 (org-open-file pdffile)
2292 ;; ** Extract bibtex entries in org-file
2294 (defun org-ref-extract-bibtex-entries ()
2295 "Extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2297 If no bibliography is in the buffer the variable
2298 `reftex-default-bibliography' is used."
2300 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2301 (tempname (make-temp-file "extract-bib"))
2302 (contents (buffer-string))
2303 (cb (current-buffer))
2304 basename texfile bibfile results)
2306 ;; open tempfile and insert org-buffer contents
2307 (find-file tempname)
2309 (setq basename (file-name-sans-extension
2310 (file-name-nondirectory buffer-file-name))
2311 texfile (concat tempname ".tex")
2312 bibfile (concat tempname ".bib"))
2314 ;; see if we have a bibliography, and insert the default one if not.
2316 (goto-char (point-min))
2317 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2318 (insert (format "\nbibliography:%s"
2319 (mapconcat 'identity reftex-default-bibliography ",")))))
2322 ;; get a latex file and extract the references
2323 (org-latex-export-to-latex)
2326 (reftex-create-bibtex-file bibfile)
2328 ;; save results of the references
2329 (setq results (buffer-string))
2331 ;; kill buffers. these are named by basename, not full path
2332 (kill-buffer (concat basename ".bib"))
2333 (kill-buffer (concat basename ".tex"))
2334 (kill-buffer basename)
2336 (delete-file bibfile)
2337 (delete-file texfile)
2338 (delete-file tempname)
2340 ;; Now back to the original org buffer and insert the results
2341 (switch-to-buffer cb)
2342 (when (not (string= "" results))
2344 (goto-char (point-max))
2346 (org-insert-heading)
2347 (insert (format " Bibtex entries
2349 #+BEGIN_SRC text :tangle %s
2351 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2353 ;; ** Find bad citations
2356 (defun index (substring list)
2357 "Return the index of SUBSTRING in a LIST of strings."
2360 (dolist (arg list i)
2361 (if (string-match (concat "^" substring "$") arg)
2366 ;; return counter if found, otherwise return nil
2370 (defun org-ref-find-bad-citations ()
2371 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2373 Makes a new buffer with clickable links."
2375 ;; generate the list of bibtex-keys and cited keys
2376 (let* ((bibtex-files (org-ref-find-bibliography))
2377 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2378 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2379 (bad-citations '()))
2381 (org-element-map (org-element-parse-buffer) 'link
2383 (let ((plist (nth 1 link)))
2384 (when (-contains? org-ref-cite-types (plist-get plist :type))
2385 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2386 (when (not (index key bibtex-keys))
2391 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2394 (plist-get plist :begin)))))
2396 ;; set with-affilates to t to get citations in a caption
2401 (switch-to-buffer-other-window "*Missing citations*")
2404 (insert "* List of bad cite links\n")
2405 (insert (mapconcat 'identity bad-citations ""))
2406 ;(setq buffer-read-only t)
2407 (use-local-map (copy-keymap org-mode-map))
2408 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2410 (when (get-buffer "*Missing citations*")
2411 (kill-buffer "*Missing citations*"))
2412 (message "No bad cite links found"))))
2414 ;; ** helm interface to bad citations, labels, refs and files in orgfile
2415 (defun org-ref-bad-cite-candidates ()
2416 "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2417 (let* ((cp (point)) ; save to return to later
2418 (bibtex-files (org-ref-find-bibliography))
2419 (bibtex-file-path (mapconcat
2421 (file-name-directory (file-truename x)))
2423 (bibtex-keys (mapcar (lambda (x) (car x))
2424 (bibtex-global-key-alist)))
2425 (bad-citations '()))
2427 (org-element-map (org-element-parse-buffer) 'link
2429 (let ((plist (nth 1 link)))
2430 (when (-contains? org-ref-cite-types (plist-get plist :type))
2431 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2432 (when (not (index key bibtex-keys))
2433 (goto-char (plist-get plist :begin))
2434 (re-search-forward key)
2435 (push (cons key (point-marker)) bad-citations)))
2437 ;; add with-affiliates to get cites in caption
2443 (defun org-ref-bad-ref-candidates ()
2444 "Return a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2445 ;; first get a list of legitimate labels
2447 (labels (org-ref-get-labels))
2449 ;; now loop over ref links
2450 (goto-char (point-min))
2451 (org-element-map (org-element-parse-buffer) 'link
2453 (let ((plist (nth 1 link)))
2454 (when (or (equal (plist-get plist ':type) "ref")
2455 (equal (plist-get plist ':type) "eqref")
2456 (equal (plist-get plist ':type) "pageref")
2457 (equal (plist-get plist ':type) "nameref"))
2458 (unless (-contains? labels (plist-get plist :path))
2459 (goto-char (plist-get plist :begin))
2462 (cons (plist-get plist :path)
2463 (point-marker))))))))
2468 (defun org-ref-bad-label-candidates ()
2469 "Return a list of labels where label is multiply defined."
2470 (let ((labels (org-ref-get-labels))
2471 (multiple-labels '()))
2472 (when (not (= (length labels)
2473 (length (-uniq labels))))
2474 (dolist (label labels)
2475 (when (> (-count (lambda (a)
2478 ;; this is a multiply defined label.
2480 (goto-char (point-min))
2481 (while (re-search-forward
2482 (format "[^#+]label:%s\\s-" label) nil t)
2483 (push (cons label (point-marker)) multiple-labels))
2484 (goto-char (point-min))
2485 (while (re-search-forward
2486 (format "\\label{%s}\\s-?" label) nil t)
2487 (push (cons label (point-marker)) multiple-labels))
2489 (goto-char (point-min))
2490 (while (re-search-forward
2491 (format "^#\\+label:\\s-*%s" label) nil t)
2492 (push (cons label (point-marker)) multiple-labels))
2494 (goto-char (point-min))
2495 (while (re-search-forward
2496 (format "^#\\+tblname:\\s-*%s" label) nil t)
2497 (push (cons label (point-marker)) multiple-labels))
2501 (defun org-ref-bad-file-link-candidates ()
2502 "Return list of conses (link . marker) wehre the file in the link does not exist."
2503 (let* ((bad-files '()))
2504 (org-element-map (org-element-parse-buffer) 'link
2506 (let ((type (org-element-property :type link)))
2507 (when (or (string= "file" type)
2508 (string= "attachfile" type))
2509 (unless (file-exists-p (org-element-property :path link))
2510 (add-to-list 'bad-files
2511 (cons (org-element-property :path link)
2514 (org-element-property :begin link))
2515 (point-marker)))))))))
2516 ;; Let us also check \attachfile{fname}
2518 (goto-char (point-min))
2519 (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
2520 (unless (file-exists-p (match-string 1))
2521 (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
2526 "Opens a helm interface to actions for org-ref.
2527 Shows bad citations, ref links and labels"
2529 (let ((cb (current-buffer))
2530 (bad-citations (org-ref-bad-cite-candidates))
2531 (bad-refs (org-ref-bad-ref-candidates))
2532 (bad-labels (org-ref-bad-label-candidates))
2533 (bad-files (org-ref-bad-file-link-candidates)))
2535 (helm :sources `(((name . "Bad citations")
2536 (candidates . ,bad-citations)
2537 (action . (lambda (marker)
2538 (switch-to-buffer (marker-buffer marker))
2539 (goto-char marker))))
2541 ((name . "Bad Labels")
2542 (candidates . ,bad-labels)
2543 (action . (lambda (marker)
2544 (switch-to-buffer (marker-buffer marker))
2545 (goto-char marker))))
2547 ((name . "Bad ref links")
2548 (candidates . ,bad-refs)
2549 (action . (lambda (marker)
2550 (switch-to-buffer (marker-buffer marker))
2551 (goto-char marker))))
2553 ((name . "Bad file links")
2554 (candidates . ,bad-files)
2556 (switch-to-buffer (marker-buffer marker))
2557 (goto-char marker)))
2559 ((name . "Utilities")
2560 (candidates . (("Check buffer again" . org-ref)
2561 ("Insert citation" . helm-bibtex)
2562 ("Insert label link" . org-ref-helm-insert-label-link)
2563 ("Insert ref link" . org-ref-helm-insert-ref-link)
2564 ("List of figures" . org-ref-list-of-figures)
2565 ("List of tables" . org-ref-list-of-tables)
2566 ("Table of contents" . nil)
2568 (action . (lambda (x)
2569 (switch-to-buffer ,cb)
2572 ((name . "Export functions")
2573 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2574 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2575 ("Export to pdf and open" . (lambda ()
2576 (org-open-file (org-latex-export-to-pdf))))
2577 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2578 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2581 (action . (lambda (x)
2582 (switch-to-buffer ,cb)
2585 ;; ** Find non-ascii charaters
2586 (defun org-ref-find-non-ascii-characters ()
2587 "Find non-ascii characters in the buffer. Useful for cleaning up bibtex files."
2589 (occur "[^[:ascii:]]"))
2591 ;; ** Sort fields in a bibtex entry
2593 (defun org-ref-sort-bibtex-entry ()
2594 "Sort fields of entry in standard order and downcase them."
2596 (bibtex-beginning-of-entry)
2597 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2598 (entry (bibtex-parse-entry))
2601 (type (cdr (assoc "=type=" entry)))
2602 (key (cdr (assoc "=key=" entry))))
2604 ;; these are the fields we want to order that are in this entry
2605 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2606 ;; we do not want to reenter these fields
2607 (setq entry-fields (remove "=key=" entry-fields))
2608 (setq entry-fields (remove "=type=" entry-fields))
2610 ;;these are the other fields in the entry
2611 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2614 ;; right now we only resort articles
2615 ((string= (downcase type) "article")
2618 (concat "@article{" key ",\n"
2621 (when (member field entry-fields)
2622 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2625 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2627 (bibtex-find-entry key)
2629 (bibtex-clean-entry)
2632 ;; ** Clean a bibtex entry
2633 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2634 "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"
2636 (bibtex-beginning-of-entry)
2638 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2639 (unless (string-match ",$" (thing-at-point 'line))
2643 ;; check for empty pages, and put eid or article id in its place
2644 (let ((entry (bibtex-parse-entry))
2645 (pages (bibtex-autokey-get-field "pages"))
2646 (year (bibtex-autokey-get-field "year"))
2647 (doi (bibtex-autokey-get-field "doi"))
2648 ;; The Journal of Chemical Physics uses eid
2649 (eid (bibtex-autokey-get-field "eid")))
2651 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2652 ;; but we only want the doi.
2653 (when (string-match "^http://dx.doi.org/" doi)
2654 (bibtex-beginning-of-entry)
2655 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2657 (bibtex-make-field "doi")
2659 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2661 ;; asap articles often set year to 0, which messes up key
2662 ;; generation. fix that.
2663 (when (string= "0" year)
2664 (bibtex-beginning-of-entry)
2665 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2667 (bibtex-make-field "year")
2669 (insert (read-string "Enter year: ")))
2671 ;; fix pages if they are empty if there is an eid to put there.
2672 (when (string= "-" pages)
2674 (bibtex-beginning-of-entry)
2675 ;; this seems like a clunky way to set the pages field.But I
2676 ;; cannot find a better way.
2677 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2679 (bibtex-make-field "pages")
2683 ;; replace naked & with \&
2685 (bibtex-narrow-to-entry)
2686 (bibtex-beginning-of-entry)
2687 (message "checking &")
2688 (replace-regexp " & " " \\\\& ")
2691 ;; generate a key, and if it duplicates an existing key, edit it.
2693 (let ((key (bibtex-generate-autokey)))
2695 ;; first we delete the existing key
2696 (bibtex-beginning-of-entry)
2697 (re-search-forward bibtex-entry-maybe-empty-head)
2698 (if (match-beginning bibtex-key-in-head)
2699 (delete-region (match-beginning bibtex-key-in-head)
2700 (match-end bibtex-key-in-head)))
2701 ;; check if the key is in the buffer
2702 (when (save-excursion
2703 (bibtex-search-entry key))
2705 (bibtex-search-entry key)
2706 (bibtex-copy-entry-as-kill)
2707 (switch-to-buffer-other-window "*duplicate entry*")
2709 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2712 (kill-new key))) ;; save key for pasting
2714 ;; run hooks. each of these operates on the entry with no arguments.
2715 ;; this did not work like i thought, it gives a symbolp error.
2716 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2721 org-ref-clean-bibtex-entry-hook)
2723 ;; sort fields within entry
2724 (org-ref-sort-bibtex-entry)
2725 ;; check for non-ascii characters
2726 (occur "[^[:ascii:]]")
2729 (defun org-ref-get-citation-year (key)
2730 "Get the year of an entry with KEY. Return year as a string."
2731 (let* ((results (org-ref-get-bibtex-key-and-file key))
2732 (bibfile (cdr results)))
2734 (insert-file-contents bibfile)
2735 (bibtex-search-entry key nil 0)
2736 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2739 ;; ** Sort cite in cite link
2740 (defun org-ref-sort-citation-link ()
2741 "Replace link at point with sorted link by year."
2743 (let* ((object (org-element-context))
2744 (type (org-element-property :type object))
2745 (begin (org-element-property :begin object))
2746 (end (org-element-property :end object))
2747 (link-string (org-element-property :path object))
2749 (setq keys (org-ref-split-and-strip-string link-string))
2750 (setq years (mapcar 'org-ref-get-citation-year keys))
2751 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2752 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2753 ;; now get the keys separated by commas
2754 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2755 ;; and replace the link with the sorted keys
2756 (cl--set-buffer-substring begin end (concat type ":" keys))))
2758 ;; ** Shift-arrow sorting of keys in a cite link
2760 (defun org-ref-swap-keys (i j keys)
2761 "Swap the KEYS in a list with index I and J."
2762 (let ((tempi (nth i keys)))
2763 (setf (nth i keys) (nth j keys))
2764 (setf (nth j keys) tempi))
2768 (defun org-ref-swap-citation-link (direction)
2769 "Move citation at point in DIRECTION +1 is to the right, -1 to the left."
2771 (let* ((object (org-element-context))
2772 (type (org-element-property :type object))
2773 (begin (org-element-property :begin object))
2774 (end (org-element-property :end object))
2775 (link-string (org-element-property :path object))
2777 ;; We only want this to work on citation links
2778 (when (-contains? org-ref-cite-types type)
2779 (setq key (org-ref-get-bibtex-key-under-cursor))
2780 (setq keys (org-ref-split-and-strip-string link-string))
2781 (setq i (index key keys)) ;; defined in org-ref
2782 (if (> direction 0) ;; shift right
2783 (org-ref-swap-keys i (+ i 1) keys)
2784 (org-ref-swap-keys i (- i 1) keys))
2785 (setq keys (mapconcat 'identity keys ","))
2786 ;; and replace the link with the sorted keys
2787 (cl--set-buffer-substring
2791 ;; It seems the space at the end can get consumed, so we see if there
2792 ;; is a space, and add it if so. Sometimes there is a comma or period,
2793 ;; then we do not want a space.
2797 (looking-back " ")) " ")))
2798 ;; now go forward to key so we can move with the key
2799 (re-search-forward key)
2800 (goto-char (match-beginning 0)))))
2802 ;; add hooks to make it work
2803 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2804 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2806 ;; ** context around org-ref links
2807 (defun org-ref-get-label-context (label)
2808 "Return a string of context around a LABEL."
2811 (goto-char (point-min))
2812 (when (re-search-forward
2813 (format "label:%s\\b" label) nil t)
2814 (throw 'result (buffer-substring
2823 (goto-char (point-min))
2824 (when (re-search-forward
2825 (format "\\label{%s}" label) nil t)
2826 (throw 'result (buffer-substring
2835 (goto-char (point-min))
2836 (when (re-search-forward
2837 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2838 (throw 'result (buffer-substring
2847 (goto-char (point-min))
2848 (when (re-search-forward
2849 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2850 (throw 'result (buffer-substring
2858 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2861 (defun org-ref-link-message ()
2862 "Print a minibuffer message about the link that point is on."
2866 (when (eq major-mode 'org-mode)
2867 (let* ((object (org-element-context))
2868 (type (org-element-property :type object)))
2872 ((-contains? org-ref-cite-types type)
2873 (message (org-ref-get-citation-string-at-point)))
2875 ;; message some context about the label we are referring to
2876 ((string= type "ref")
2877 (message "%scount: %s"
2878 (org-ref-get-label-context
2879 (org-element-property :path object))
2880 (org-ref-count-labels
2881 (org-element-property :path object))))
2883 ((string= type "eqref")
2884 (message "%scount: %s"
2885 (org-ref-get-label-context
2886 (org-element-property :path object))
2887 (org-ref-count-labels
2888 (org-element-property :path object))))
2890 ;; message the count
2891 ((string= type "label")
2892 (let ((count (org-ref-count-labels
2893 (org-element-property :path object))))
2894 ;; get plurality on occurrence correct
2896 (number-to-string count)
2898 (when (or (= count 0)
2902 ((string= type "custom-id")
2904 (org-open-link-from-string
2905 (format "[[#%s]]" (org-element-property :path object)))
2906 (message "%s" (org-get-heading))))
2908 ;; check if the bibliography files exist.
2909 ((string= type "bibliography")
2911 ;; object is the link you clicked on
2912 (object (org-element-context))
2913 (link-string (org-element-property :path object))
2914 (link-string-beginning)
2917 (goto-char (org-element-property :begin object))
2918 (search-forward link-string nil nil 1)
2919 (setq link-string-beginning (match-beginning 0))
2920 (setq link-string-end (match-end 0)))
2922 ;; make sure we are in link and not before the :
2923 (when (> link-string-beginning (point))
2924 (goto-char link-string-beginning))
2926 ;; now if we have comma separated bibliographies
2927 ;; we find the one clicked on. we want to
2928 ;; search forward to next comma from point
2930 (if (search-forward "," link-string-end 1 1)
2931 (setq key-end (- (match-end 0) 1)) ; we found a match
2932 (setq key-end (point)))) ; no comma found so take the point
2934 ;; and backward to previous comma from point
2936 (if (search-backward "," link-string-beginning 1 1)
2937 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2938 (setq key-beginning (point)))) ; no match found
2939 ;; save the key we clicked on.
2941 (org-ref-strip-string
2942 (buffer-substring key-beginning key-end)))
2943 (if (file-exists-p bibfile)
2944 (message "%s exists." bibfile)
2945 (message "!!! %s NOT FOUND !!!" bibfile))))))))))
2948 (defalias 'oro 'org-ref-open-citation-at-point)
2949 (defalias 'orc 'org-ref-citation-at-point)
2950 (defalias 'orp 'org-ref-open-pdf-at-point)
2951 (defalias 'oru 'org-ref-open-url-at-point)
2952 (defalias 'orn 'org-ref-open-notes-at-point)
2953 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2955 (defalias 'orib 'org-ref-insert-bibliography-link)
2956 (defalias 'oric 'org-ref-insert-cite-link)
2957 (defalias 'orir 'org-ref-insert-ref-link)
2958 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2960 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2962 ;; * Helm bibtex setup
2964 (setq helm-bibtex-additional-search-fields '(keywords))
2966 (defun helm-bibtex-candidates-formatter (candidates source)
2967 "Formats BibTeX entries for display in results list.
2968 Argument CANDIDATES helm candidates.
2969 Argument SOURCE the helm source."
2971 with width = (with-helm-window (helm-bibtex-window-width))
2972 for entry in candidates
2973 for entry = (cdr entry)
2974 for entry-key = (helm-bibtex-get-value "=key=" entry)
2975 if (assoc-string "author" entry 'case-fold)
2976 for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2978 for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2979 for fields = (--map (helm-bibtex-clean-string
2980 (helm-bibtex-get-value it entry " "))
2982 for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
2983 for fields = (append fields
2984 (list (or (helm-bibtex-get-value "keywords" entry)
2987 (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
2988 (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
2989 fields (list 36 (- width 85) 4 1 1 7 7)))
2992 ;; * org-ref bibtex keywords
2993 ;; adapted from bibtex-utils.el
2994 ;; these are candidates for selecting keywords/tags
2995 (defun org-ref-bibtex-keywords ()
2996 "Get keywords defined in current bibtex file.
2997 These are in the keywords field, and are comma or semicolon separated."
2999 (goto-char (point-min))
3000 (let (keywords kstring)
3001 (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
3002 ;; TWS - remove newlines/multiple spaces:
3003 (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
3006 (add-to-list 'keywords v t))
3007 (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
3011 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
3012 "Add KEYWORDS to a bibtex entry.
3013 If KEYWORDS is a list, it is converted to a comma-separated
3014 string. The KEYWORDS are added to the beginning of the
3015 field. Otherwise KEYWORDS should be a string of comma-separate
3016 keywords. Optional argument ARG prefix arg to replace keywords."
3017 (interactive "sKeywords: \nP")
3022 (if (listp keywords)
3023 (mapconcat 'identity keywords ", ")
3025 ;; else concatentate
3027 (if (listp keywords)
3028 (mapconcat 'identity keywords ", ")
3030 (when (not (string= "" (bibtex-autokey-get-field "keywords")))
3031 (concat ", " (bibtex-autokey-get-field "keywords"))))))
3035 (defun helm-tag-bibtex-entry ()
3036 "Helm interface to add keywords to a bibtex entry.
3037 Run this with the point in a bibtex entry."
3039 (let ((keyword-source `((name . "Existing keywords")
3040 (candidates . ,(org-ref-bibtex-keywords))
3041 (action . (lambda (candidate)
3042 (org-ref-set-bibtex-keywords
3045 (helm-marked-candidates)
3047 (fallback-source `((name . "Add new keywords")
3049 (action . (lambda (candidate)
3050 (org-ref-set-bibtex-keywords helm-pattern)
3052 (helm :sources '(keyword-source fallback-source))))
3054 (defun helm-bibtex-show-entry (key)
3055 "Show the entry for KEY in the BibTeX file.
3056 The original function in `helm-bibtex' has a bug where it finds the
3057 first key that partially matches. This version avoids that."
3059 (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
3060 helm-bibtex-bibliography
3061 (list helm-bibtex-bibliography)))
3062 (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
3064 (find-file bibtex-file)
3066 (lambda (key start end)
3067 (add-to-list 'entries (cons key start))))
3068 (if (assoc key entries)
3070 (goto-char (cdr (assoc key entries)))
3075 (defun org-ref-helm-tag-entries (candidates)
3076 "Set tags on selected bibtex entries from `helm-bibtex'.
3077 User is prompted for tags. This function is called from `helm-bibtex'.
3078 Argument CANDIDATES helm candidates."
3080 (let ((keywords (read-string "Keywords (comma separated): ")))
3081 (loop for key in (helm-marked-candidates)
3083 (save-window-excursion
3084 (helm-bibtex-show-entry key)
3089 ", " (bibtex-autokey-get-field "keywords")))
3092 (setq helm-source-bibtex
3093 '((name . "BibTeX entries")
3094 (init . helm-bibtex-init)
3095 (candidates . helm-bibtex-candidates)
3096 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3097 (action . (("Insert citation" . helm-bibtex-insert-citation)
3098 ("Show entry" . helm-bibtex-show-entry)
3099 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3100 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3101 ("Insert formatted reference" . helm-bibtex-insert-reference)
3102 ("Insert BibTeX key" . helm-bibtex-insert-key)
3103 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3104 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3105 ("Edit notes" . helm-bibtex-edit-notes)
3106 ("Add keywords to entries" . org-ref-helm-tag-entries)
3109 (defun helm-bibtex-format-org-ref (keys)
3110 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3111 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.
3113 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3115 C-u C-u will change the key at point to the selected keys."
3116 (let* ((object (org-element-context))
3117 (last-char (save-excursion
3118 (when (org-element-property :end object)
3119 (goto-char (org-element-property :end object))
3122 (if (looking-at " ")
3126 ;; case where we are in a link
3127 ((and (equal (org-element-type object) 'link)
3130 (org-element-property :type object)))
3132 ;; no prefix. append keys
3133 ((equal helm-current-prefix-arg nil)
3134 (goto-char (org-element-property :end object))
3135 (while (looking-back " ") (backward-char))
3136 (insert (concat "," (mapconcat 'identity keys ","))))
3137 ;; double prefix, replace key at point
3138 ((equal helm-current-prefix-arg '(16))
3139 (setf (buffer-substring
3140 (org-element-property :begin object)
3141 (org-element-property :end object))
3143 (replace-regexp-in-string
3144 (car (org-ref-get-bibtex-key-and-file)) ; key
3145 (mapconcat 'identity keys ",") ; new keys
3146 (org-element-property :raw-link object))
3147 ;; replace space at end to avoid collapsing into next word.
3149 ;; and we want to go to the end of the new link
3151 (org-element-property :end (org-element-context))))
3153 (message "Not found"))))
3155 ;; We are next to a link, and we want to append
3156 ;; next to a link means one character back is on a link.
3158 (unless (bobp) (backward-char))
3159 (and (equal (org-element-type (org-element-context)) 'link)
3162 (org-element-property :type (org-element-context)))))
3163 (while (looking-back " ") (backward-char))
3164 (insert (concat "," (mapconcat 'identity keys ","))))
3166 ;; insert fresh link
3168 ;;(message-box "fresh link")
3170 (concat (if (equal helm-current-prefix-arg '(4))
3171 (helm :sources `((name . "link types")
3172 (candidates . ,org-ref-cite-types)
3173 (action . (lambda (x) x))))
3174 org-ref-default-citation-link)
3176 (s-join "," keys))))))
3177 ;; return empty string for helm
3180 (setq helm-bibtex-format-citation-functions
3181 '((org-mode . helm-bibtex-format-org-ref)))
3184 (defun org-ref-helm-insert-cite-link (arg)
3185 "org-ref function to use helm-bibtex to insert a citation link.
3186 With one prefix arg, insert a ref link.
3187 With two prefix args, insert a label link."
3191 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3194 (org-ref-helm-insert-ref-link))
3196 (org-ref-helm-insert-label-link))))
3199 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3200 (setq helm-bibtex-fallback-options
3201 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3203 (setq helm-bibtex-fallback-options
3206 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3207 helm-bibtex-fallback-options))
3209 (setq helm-bibtex-fallback-options
3210 (-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))
3212 (defun org-ref-get-citation-string-at-point ()
3213 "Get a string of a formatted citation."
3214 (let* ((results (org-ref-get-bibtex-key-and-file))
3216 (bibfile (cdr results)))
3220 (insert-file-contents bibfile)
3221 (bibtex-search-entry key)
3222 (org-ref-bib-citation)))
3223 "!!! No entry found !!!" )))
3226 (defun org-ref-cite-candidates ()
3227 "Generate the list of possible candidates for click actions on a cite link.
3228 Checks for pdf and doi, and add appropriate functions."
3229 (let* ((results (org-ref-get-bibtex-key-and-file))
3231 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3232 (bibfile (cdr results))
3233 (url (save-excursion
3235 (insert-file-contents bibfile)
3236 (bibtex-search-entry key)
3237 (bibtex-autokey-get-field "url"))))
3238 (doi (save-excursion
3240 (insert-file-contents bibfile)
3241 (bibtex-search-entry key)
3242 ;; I like this better than bibtex-url which does not always find
3244 (bibtex-autokey-get-field "doi"))))
3245 (candidates `(("Quit" . org-ref-citation-at-point)
3246 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3247 ;; for some reason, when there is no doi or url, they are returned as "". I
3248 ;; prefer nil so we correct this here.
3249 (when (string= doi "") (setq doi nil))
3250 (when (string= url "") (setq url nil))
3252 ;; Conditional pdf functions
3253 (if (file-exists-p pdf-file)
3256 '("Open pdf" . org-ref-open-pdf-at-point)
3260 '("Try to get pdf" . (lambda ()
3261 (save-window-excursion
3262 (org-ref-open-citation-at-point)
3263 (bibtex-beginning-of-entry)
3264 (doi-utils-get-bibtex-entry-pdf))))
3270 '("Open notes" . org-ref-open-notes-at-point)
3273 ;; conditional url and doi functions
3277 '("Open in browser" . org-ref-open-url-at-point)
3282 (add-to-list 'candidates x t))
3283 `(("WOS" . org-ref-wos-at-point)
3284 ("Related articles in WOS" . org-ref-wos-related-at-point)
3285 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3286 ("Google Scholar" . org-ref-google-scholar-at-point)
3287 ("Pubmed" . org-ref-pubmed-at-point)
3288 ("Crossref" . org-ref-crossref-at-point)
3293 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3298 '("Copy key to clipboard" . (lambda ()
3300 (car (org-ref-get-bibtex-key-and-file)))))
3305 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3310 '("Email bibtex entry and pdf" . (lambda ()
3312 (org-ref-open-citation-at-point)
3313 (email-bibtex-entry))))
3315 ;; finally return a numbered list of the candidates
3317 for cell in candidates
3318 collect (cons (format "%2s. %s" i (car cell))
3322 (defvar org-ref-helm-user-candidates '()
3323 "List of user-defined candidates to act when clicking on a cite link.
3324 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.")
3326 ;; example of adding your own function
3328 'org-ref-helm-user-candidates
3329 '("Example" . (lambda () (message-box "You did it!")))
3333 (defun org-ref-cite-click-helm (key)
3334 "Open helm for actions on a cite link.
3337 1. get name and candidates before entering helm because we need
3340 2. switch back to the org buffer before evaluating the
3341 action. most of them need the point and buffer.
3343 KEY is returned for the selected item(s) in helm."
3345 (let ((name (org-ref-get-citation-string-at-point))
3346 (candidates (org-ref-cite-candidates))
3347 (cb (current-buffer)))
3349 (helm :sources `(((name . ,name)
3350 (candidates . ,candidates)
3351 (action . (lambda (f)
3352 (switch-to-buffer cb)
3354 ((name . "User functions")
3355 (candidates . ,org-ref-helm-user-candidates)
3356 (action . (lambda (f)
3357 (switch-to-buffer cb)
3361 ;; * Hydra menus in org-ref
3363 (when (featurep 'hydra)
3365 (setq hydra-is-helpful t)
3367 (defhydra org-ref-cite-hydra (:color blue)
3369 _p_: Open pdf _w_: WOS _g_: Google Scholar _K_: Copy citation to clipboard
3370 _u_: Open url _r_: WOS related _P_: Pubmed _k_: Copy key to clipboard
3371 _n_: Open notes _c_: WOS citing _C_: Crossref _f_: Copy bibtex entry to file
3372 _o_: Open entry _e_: Email entry and pdf
3374 ("o" org-ref-open-citation-at-point nil)
3375 ("p" org-ref-open-pdf-at-point nil)
3376 ("n" org-ref-open-notes-at-point nil)
3377 ("u" org-ref-open-url-at-point nil)
3378 ("w" org-ref-wos-at-point nil)
3379 ("r" org-ref-wos-related-at-point nil)
3380 ("c" org-ref-wos-citing-at-point nil)
3381 ("g" org-ref-google-scholar-at-point nil)
3382 ("P" org-ref-pubmed-at-point nil)
3383 ("C" org-ref-crossref-at-point nil)
3384 ("K" org-ref-copy-entry-as-summary nil)
3387 (car (org-ref-get-bibtex-key-and-file)))) nil)
3388 ("f" org-ref-copy-entry-at-point-to-file nil)
3390 ("e" (save-excursion
3391 (org-ref-open-citation-at-point)
3392 (email-bibtex-entry)) nil)))
3395 (defun org-ref-help ()
3396 "Open the org-ref manual."
3398 (find-file (expand-file-name
3400 (file-name-directory
3401 (find-library-name "org-ref")))))
3404 (defun org-ref-org-menu ()
3405 "Add org-ref menu to the Org menu."
3409 '( ["Insert citation" org-ref-helm-insert-cite-link]
3410 ["Insert ref" org-ref-helm-insert-ref-link]
3411 ["Insert label" org-ref-helm-insert-label-link]
3413 ["List of figures" org-ref-list-of-figures]
3414 ["List of tables" org-ref-list-of-tables]
3415 ["Extract bibtex entries" org-ref-extract-bibtex-entries]
3416 ["Check org-file" org-ref]
3418 ["Help" org-ref-help]
3419 ["Customize org-ref" (customize-group 'org-ref)])
3422 (easy-menu-change '("Org") "--" nil "Show/Hide"))
3424 (add-hook 'org-mode-hook 'org-ref-org-menu)
3429 ;;; org-ref.el ends here