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, %i, %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 ;; change double dash to single dash
556 (setq output (replace-regexp-in-string "--" "-" output))
557 (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
558 (format "<li><a id=\"%s\">[%s] %s</a></li>"
561 (defun org-ref-get-html-bibliography ()
562 "Create an html bibliography when there are keys."
563 (let ((keys (org-ref-get-bibtex-keys)))
565 (concat "<h1>Bibliography</h1>
567 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
570 (defun org-ref-get-bibtex-entry-org (key)
571 "Return an org string for the bibliography entry corresponding to KEY."
572 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
573 (file) (entry) (bibtex-entry) (entry-type) (format))
575 (setq file (catch 'result
576 (loop for file in org-ref-bibliography-files do
577 (if (org-ref-key-in-file-p key (file-truename file))
579 (message "%s not found in %s" key (file-truename file))))))
582 (insert-file-contents file)
583 (bibtex-search-entry key nil 0)
584 (setq entry (bibtex-parse-entry))
589 " (org-ref-reftex-get-bib-field "author" entry)
590 (org-ref-reftex-get-bib-field "title" entry)
591 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
592 (mapconcat (lambda (element) (format " :%s: %s"
593 (upcase (car element))
598 (defun org-ref-get-org-bibliography ()
599 "Create an org bibliography when there are keys."
600 (let ((keys (org-ref-get-bibtex-keys)))
602 (concat "* Bibliography
604 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
607 (defun org-ref-get-bibtex-entry-ascii (key)
608 "Return an ascii string for the bibliography entry corresponding to KEY."
610 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
612 (defun org-ref-get-ascii-bibliography ()
613 "Create an html bibliography when there are keys."
614 (let ((keys (org-ref-get-bibtex-keys)))
620 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
624 ;; ** bibliography and bibliographystyle
625 (org-add-link-type "bibliography"
626 ;; this code is run on clicking. The bibliography
627 ;; may contain multiple files. this code finds the
628 ;; one you clicked on and opens it.
629 (lambda (link-string)
630 ;; get link-string boundaries we have to go to the
631 ;; beginning of the line, and then search forward
633 ;; object is the link you clicked on
634 (object (org-element-context))
635 (link-string-beginning)
639 (goto-char (org-element-property :begin object))
640 (search-forward link-string nil nil 1)
641 (setq link-string-beginning (match-beginning 0))
642 (setq link-string-end (match-end 0)))
644 ;; Make sure point is in the link-path.
645 (if (< cp link-string-beginning)
646 (goto-char link-string-beginning))
647 ;; We set the reftex-default-bibliography
648 ;; here. it should be a local variable only in
649 ;; the current buffer. We need this for using
650 ;; reftex to do citations.
651 (set (make-local-variable 'reftex-default-bibliography)
653 (org-element-property :path object) ","))
655 ;; now if we have comma separated bibliographies
656 ;; we find the one clicked on. we want to
657 ;; search forward to next comma from point
659 (if (search-forward "," link-string-end 1 1)
661 (setq key-end (- (match-end 0) 1))
662 ;; no comma found so take the point
663 (setq key-end (point))))
664 ;; and backward to previous comma from point
666 (if (search-backward "," link-string-beginning 1 1)
668 (setq key-beginning (+ (match-beginning 0) 1))
669 (setq key-beginning (point)))) ; no match found
670 ;; save the key we clicked on.
671 (setq bibfile (org-ref-strip-string
672 (buffer-substring key-beginning key-end)))
673 ;; open file on click
674 (find-file bibfile)))
677 (lambda (keyword desc format)
679 ((eq format 'org) (org-ref-get-org-bibliography))
680 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
681 ((eq format 'html) (org-ref-get-html-bibliography))
683 ;; write out the latex bibliography command
684 (format "\\bibliography{%s}"
685 (replace-regexp-in-string
689 (mapcar 'expand-file-name
690 (split-string keyword ","))
693 (org-add-link-type "nobibliography"
694 ;; this code is run on clicking. The bibliography
695 ;; may contain multiple files. this code finds the
696 ;; one you clicked on and opens it.
697 (lambda (link-string)
698 ;; get link-string boundaries
699 ;; we have to go to the beginning of the line, and then search forward
702 ;; object is the link you clicked on
703 (object (org-element-context))
705 (link-string-beginning)
709 (goto-char (org-element-property :begin object))
710 (search-forward link-string nil nil 1)
711 (setq link-string-beginning (match-beginning 0))
712 (setq link-string-end (match-end 0)))
714 ;; We set the reftex-default-bibliography
715 ;; here. it should be a local variable only in
716 ;; the current buffer. We need this for using
717 ;; reftex to do citations.
718 (set (make-local-variable 'reftex-default-bibliography)
719 (split-string (org-element-property :path object) ","))
721 ;; now if we have comma separated bibliographies
722 ;; we find the one clicked on. we want to
723 ;; search forward to next comma from point
725 (if (search-forward "," link-string-end 1 1)
726 (setq key-end (- (match-end 0) 1)) ; we found a match
727 (setq key-end (point)))) ; no comma found so take the point
728 ;; and backward to previous comma from point
730 (if (search-backward "," link-string-beginning 1 1)
731 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
732 (setq key-beginning (point)))) ; no match found
733 ;; save the key we clicked on.
734 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
735 (find-file bibfile))) ; open file on click
738 (lambda (keyword desc format)
740 ((eq format 'org) (org-ref-get-org-bibliography))
741 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
742 ((eq format 'html) (org-ref-get-html-bibliography))
744 ;; write out the latex bibliography command
745 (format "\\nobibliography{%s}"
746 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
747 (mapcar 'expand-file-name
748 (split-string keyword ","))
751 (org-add-link-type "printbibliography"
752 (lambda (arg) (message "Nothing implemented for clicking here."))
753 (lambda (keyword desc format)
755 ((eq format 'org) (org-ref-get-org-bibliography))
756 ((eq format 'html) (org-ref-get-html-bibliography))
758 ;; write out the biblatex bibliography command
759 "\\printbibliography"))))
761 (org-add-link-type "bibliographystyle"
762 (lambda (arg) (message "Nothing implemented for clicking here."))
763 (lambda (keyword desc format)
766 ;; write out the latex bibliography command
767 (format "\\bibliographystyle{%s}" keyword))
768 ;; Other styles should not have an output for this
773 (defun org-bibliographystyle-complete-link (&optional arg)
774 "Completion function for bibliographystyle link.
776 (format "bibliographystyle:%s" (ido-completing-read
778 '("unsrt" "plain" "alpha"
780 ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
781 "dinat" "humannat" "plainnat"
782 "abbrnat" "unsrtnat" "rusnat"
786 (defun org-bibliography-complete-link (&optional arg)
787 "Completion function for bibliography link.
789 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
792 (defun org-ref-insert-bibliography-link ()
793 "Insert a bibliography with completion."
795 (insert (org-bibliography-complete-link)))
799 (org-add-link-type "addbibresource"
800 ;; this code is run on clicking. The addbibresource
801 ;; may contain multiple files. this code finds the
802 ;; one you clicked on and opens it.
803 (lambda (link-string)
804 ;; get link-string boundaries
805 ;; we have to go to the beginning of the line, and then search forward
808 ;; object is the link you clicked on
809 (object (org-element-context))
811 (link-string-beginning)
815 (goto-char (org-element-property :begin object))
816 (search-forward link-string nil nil 1)
817 (setq link-string-beginning (match-beginning 0))
818 (setq link-string-end (match-end 0)))
820 ;; We set the reftex-default-addbibresource
821 ;; here. it should be a local variable only in
822 ;; the current buffer. We need this for using
823 ;; reftex to do citations.
824 (set (make-local-variable 'reftex-default-addbibresource)
825 (split-string (org-element-property :path object) ","))
827 ;; now if we have comma separated bibliographies
828 ;; we find the one clicked on. we want to
829 ;; search forward to next comma from point
831 (if (search-forward "," link-string-end 1 1)
832 (setq key-end (- (match-end 0) 1)) ; we found a match
833 (setq key-end (point)))) ; no comma found so take the point
834 ;; and backward to previous comma from point
836 (if (search-backward "," link-string-beginning 1 1)
837 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
838 (setq key-beginning (point)))) ; no match found
839 ;; save the key we clicked on.
840 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
841 (find-file bibfile))) ; open file on click
844 (lambda (keyword desc format)
846 ((eq format 'html) (format "")); no output for html
848 ;; write out the latex addbibresource command
849 (format "\\addbibresource{%s}" keyword)))))
851 ;; ** List of figures
852 (defun org-ref-list-of-figures (&optional arg)
853 "Generate buffer with list of figures in them.
856 (save-excursion (widen)
857 (let* ((c-b (buffer-name))
860 (org-element-map (org-element-parse-buffer) 'link
862 "create a link for to the figure"
864 (and (string= (org-element-property :type link) "file")
866 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
867 (org-element-property :path link)))
870 (let* ((start (org-element-property :begin link))
871 (parent (car (cdr (org-element-property :parent link))))
872 (caption (caaar (plist-get parent :caption)))
873 (name (plist-get parent :name)))
876 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
877 c-b start counter (or name "") caption)
879 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
880 c-b start counter (or name "")))))))))
881 (switch-to-buffer "*List of Figures*")
882 (setq buffer-read-only nil)
885 (insert (mapconcat 'identity list-of-figures ""))
886 (setq buffer-read-only t)
887 (use-local-map (copy-keymap org-mode-map))
888 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
892 'org-ref-list-of-figures ; on click
893 (lambda (keyword desc format)
896 (format "\\listoffigures")))))
899 (defun org-ref-list-of-tables (&optional arg)
900 "Generate a buffer with a list of tables.
905 (let* ((c-b (buffer-name))
908 (org-element-map (org-element-parse-buffer 'element) 'table
910 "create a link for to the table"
912 (let ((start (org-element-property :begin table))
913 (name (org-element-property :name table))
914 (caption (caaar (org-element-property :caption table))))
917 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
918 c-b start counter (or name "") caption)
920 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
921 c-b start counter (or name ""))))))))
922 (switch-to-buffer "*List of Tables*")
923 (setq buffer-read-only nil)
926 (insert (mapconcat 'identity list-of-tables ""))
927 (setq buffer-read-only t)
928 (use-local-map (copy-keymap org-mode-map))
929 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
933 'org-ref-list-of-tables
934 (lambda (keyword desc format)
937 (format "\\listoftables")))))
941 (defun org-ref-count-labels (label)
942 "Counts number of matches for LABEL in the document."
943 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
944 ;; for tblname, it is not enough to get word boundary
945 ;; tab-little and tab-little-2 match then.
946 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
947 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
948 ;; this is the org-format #+label:
949 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
950 (let ((custom-id-count 0))
953 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
954 (setq custom-id-count (+ 1 custom-id-count)))))
960 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
961 (let ((count (org-ref-count-labels label)))
962 (message (format "%s occurence%s"
968 (org-ref-count-labels label))))
969 (lambda (keyword desc format)
971 ((eq format 'html) (format "(<label>%s</label>)" path))
973 (format "\\label{%s}" keyword)))))
975 (defun org-label-store-link ()
976 "Store a link to a label. The output will be a ref to that label."
977 ;; First we have to make sure we are on a label link.
978 (let* ((object (org-element-context)))
979 (when (and (equal (org-element-type object) 'link)
980 (equal (org-element-property :type object) "label"))
981 (org-store-link-props
983 :link (concat "ref:" (org-element-property :path object))))
985 ;; Store link on table
986 (when (equal (org-element-type object) 'table)
987 (org-store-link-props
989 :link (concat "ref:" (org-element-property :name object))))
991 ;; store link on heading with custom_id
992 ;; this is not a ref link, but it is still what you want
993 (when (and (equal (org-element-type object) 'headline)
994 (org-entry-get (point) "CUSTOM_ID"))
995 (org-store-link-props
997 :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
999 ;; and to #+label: lines
1001 (when (and (equal (org-element-type object) 'paragraph)
1002 (org-element-property :name object))
1003 (org-store-link-props
1005 :link (concat "ref:" (org-element-property :name object))))))
1007 (add-hook 'org-store-link-functions 'org-label-store-link)
1013 "on clicking goto the label. Navigate back with C-c &"
1014 (org-mark-ring-push)
1015 ;; next search from beginning of the buffer
1016 ;; it is possible you would not find the label if narrowing is in effect
1022 (goto-char (point-min))
1023 (re-search-forward (format "label:%s\\b" label) nil t))
1027 (goto-char (point-min))
1028 (re-search-forward (format "\\label{%s}" label) nil t))
1030 ;; #+label: name org-definition
1032 (goto-char (point-min))
1034 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1038 (goto-char (point-min))
1040 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1042 ;; we did not find anything, so go back to where we came
1043 (org-mark-ring-goto)
1044 (error "%s not found" label))
1046 (message "go back with (org-mark-ring-goto) `C-c &`"))
1048 (lambda (keyword desc format)
1050 ((eq format 'html) (format "(<ref>%s</ref>)" path))
1052 (format "\\ref{%s}" keyword)))))
1055 (defun org-ref-get-org-labels ()
1056 "Return a list of #+LABEL: labels."
1058 (goto-char (point-min))
1059 (let ((matches '()))
1060 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1061 ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1062 ;; who would have thought you have save match data here? Trust me. When
1063 ;; I wrote this, you did.
1064 (unless (save-match-data (equal (car (org-element-at-point)) 'table))
1065 (add-to-list 'matches (match-string-no-properties 1) t)))
1069 (defun org-ref-get-custom-ids ()
1070 "Return a list of custom_id properties in the buffer."
1071 (let ((results '()) custom_id)
1074 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1075 (when (not (null custom_id))
1076 (setq results (append results (list custom_id)))))))
1080 (defun org-ref-get-latex-labels ()
1081 "Return list of matchin LaTeX defined labels in buffer."
1083 (goto-char (point-min))
1084 (let ((matches '()))
1085 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1086 (add-to-list 'matches (match-string-no-properties 1) t))
1090 (defun org-ref-get-tblnames ()
1091 "Return list of table names in the buffer."
1092 (org-element-map (org-element-parse-buffer 'element) 'table
1094 (org-element-property :name table))))
1097 (defun org-ref-get-labels ()
1098 "Return a list of labels in the buffer that you can make a ref link to.
1099 This is used to complete ref links and in helm menus."
1103 (goto-char (point-min))
1104 (let ((matches '()))
1105 ;; these are the org-ref label:stuff kinds
1106 (while (re-search-forward
1107 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1108 (add-to-list 'matches (match-string-no-properties 1) t))
1109 ;; now add all the other kinds of labels.
1112 (org-ref-get-org-labels)
1114 (org-ref-get-latex-labels)
1115 ;; #+tblname: and actually #+label
1116 (org-ref-get-tblnames)
1118 (org-ref-get-custom-ids))))))
1121 (defun org-ref-helm-insert-label-link ()
1122 "Insert a label link. helm just shows you what labels already exist.
1123 If you are on a label link, replace it."
1125 (let* ((labels (org-ref-get-labels))
1126 (cb (current-buffer)))
1127 (helm :sources `(((name . "Existing labels")
1128 (candidates . ,labels)
1129 ;; default action is to open to the label
1130 (action . (lambda (label)
1131 ;; unfortunately I do not have markers here
1132 (org-open-link-from-string
1133 (format "ref:%s" label))))
1134 ;; if you select a label, replace current one
1135 (action . (lambda (label)
1136 (switch-to-buffer ,cb)
1138 ;; no prefix or on a link
1139 ((equal helm-current-prefix-arg nil)
1140 (let* ((object (org-element-context))
1141 (last-char (save-excursion
1142 (goto-char (org-element-property :end object))
1144 (if (looking-at " ")
1147 (when (-contains? '("label")
1148 (org-element-property :type object))
1149 ;; we are on a link, so replace it.
1152 (org-element-property :begin object)
1153 (org-element-property :end object))
1155 (replace-regexp-in-string
1156 (org-element-property :path object)
1158 (org-element-property :raw-link object))
1160 ;; no prefix options defined
1162 ;; no matching selection creates a new label
1163 ((name . "Create new label")
1165 ;; default action creates a new label, or replaces old one
1166 (action . (lambda (label)
1167 (switch-to-buffer ,cb)
1168 (let* ((object (org-element-context))
1169 (last-char (save-excursion
1170 (goto-char (org-element-property :end object))
1172 (if (looking-at " ")
1175 (if (-contains? '("label")
1176 (org-element-property :type object))
1177 ;; we are on a link, so replace it.
1180 (org-element-property :begin object)
1181 (org-element-property :end object))
1183 (replace-regexp-in-string
1184 (org-element-property :path object)
1186 (org-element-property :raw-link object))
1193 helm-pattern))))))))))))
1196 (defun org-ref-complete-link (&optional arg)
1197 "Completion function for ref links.
1198 Optional argument ARG Does nothing."
1200 (setq label (completing-read "label: " (org-ref-get-labels)))
1201 (format "ref:%s" label)))
1204 (defun org-ref-insert-ref-link ()
1205 "Completion function for a ref link."
1207 (insert (org-ref-complete-link)))
1210 (defun org-ref-helm-insert-ref-link ()
1211 "Helm menu to insert ref links to labels in the document.
1212 If you are on link, replace with newly selected label.
1213 Use C-u to insert a different kind of ref link.
1214 Use C-u C-u to insert a [[#custom-id]] link"
1216 (let* ((labels (org-ref-get-labels))
1217 (bs (buffer-string))
1218 (contexts (with-temp-buffer
1220 (mapcar 'org-ref-get-label-context labels)))
1221 (cb (current-buffer)))
1223 (helm :input (thing-at-point 'word)
1224 :sources `(((name . "Available labels to ref")
1225 (candidates . ,(loop for label in labels
1226 for context in contexts
1227 ;; we do some kludgy adding spaces
1228 ;; and bars to make it "easier" to
1230 collect (cons (concat
1235 (split-string context "\n")
1238 ;; default action to replace or insert ref link.
1239 (action . (lambda (label)
1240 (switch-to-buffer ,cb)
1243 ;; no prefix or on a link
1244 ((equal helm-current-prefix-arg nil)
1245 (let* ((object (org-element-context))
1246 (last-char (save-excursion
1247 (goto-char (org-element-property :end object))
1249 (if (looking-at " ")
1252 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1253 (org-element-property :type object))
1254 ;; we are on a link, so replace it.
1257 (org-element-property :begin object)
1258 (org-element-property :end object))
1260 (replace-regexp-in-string
1261 (org-element-property :path object)
1263 (org-element-property :raw-link object))
1265 ;; insert a new link
1270 ;; one prefix, alternate ref link
1271 ((equal helm-current-prefix-arg '(4))
1274 (helm :sources '((name . "Ref link types")
1275 (candidates . ("ref" "eqref" "pageref" "nameref"))
1276 (action . (lambda (x) x))))
1278 ;; two prefixes, insert section custom-id link
1279 ((equal helm-current-prefix-arg '(16))
1281 (format "[[#%s]]" label)))
1289 "on clicking goto the label. Navigate back with C-c &"
1290 (org-mark-ring-push)
1291 ;; next search from beginning of the buffer
1297 (goto-char (point-min))
1298 (re-search-forward (format "label:%s\\b" label) nil t))
1302 (goto-char (point-min))
1303 (re-search-forward (format "\\label{%s}" label) nil t))
1305 ;; #+label: name org-definition
1307 (goto-char (point-min))
1309 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1313 (goto-char (point-min))
1315 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1316 ;; we did not find anything, so go back to where we came
1317 (org-mark-ring-goto)
1318 (error "%s not found" label))
1319 (message "go back with (org-mark-ring-goto) `C-c &`"))
1321 (lambda (keyword desc format)
1323 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1325 (format "\\pageref{%s}" keyword)))))
1328 (defun org-pageref-complete-link (&optional arg)
1329 "Completion function for ref links.
1330 Optional argument ARG Does nothing."
1332 (setq label (completing-read "label: " (org-ref-get-labels)))
1333 (format "ref:%s" label)))
1336 (defun org-pageref-insert-ref-link ()
1337 "Insert a pageref link with completion."
1339 (insert (org-pageref-complete-link)))
1346 "on clicking goto the label. Navigate back with C-c &"
1347 (org-mark-ring-push)
1348 ;; next search from beginning of the buffer
1354 (goto-char (point-min))
1355 (re-search-forward (format "\\label{%s}" label) nil t))
1357 ;; we did not find anything, so go back to where we came
1358 (org-mark-ring-goto)
1359 (error "%s not found" label))
1360 (message "go back with (org-mark-ring-goto) `C-c &`"))
1362 (lambda (keyword desc format)
1364 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1366 (format "\\nameref{%s}" keyword)))))
1373 "on clicking goto the label. Navigate back with C-c &"
1374 (org-mark-ring-push)
1375 ;; next search from beginning of the buffer
1377 (goto-char (point-min))
1380 ;; search forward for the first match
1382 (re-search-forward (format "label:%s" label) nil t)
1384 (re-search-forward (format "\\label{%s}" label) nil t)
1385 ;; #+label: name org-definition
1386 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1387 (org-mark-ring-goto)
1388 (error "%s not found" label))
1389 (message "go back with (org-mark-ring-goto) `C-c &`"))
1391 (lambda (keyword desc format)
1393 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1395 (format "\\eqref{%s}" keyword)))))
1399 (defun org-ref-get-bibtex-key-under-cursor ()
1400 "Return key under the bibtex cursor.
1401 We search forward from
1402 point to get a comma, or the end of the link, and then backwards
1403 to get a comma, or the beginning of the link. that delimits the
1404 keyword we clicked on. We also strip the text properties."
1405 (let* ((object (org-element-context))
1406 (link-string (org-element-property :path object)))
1407 ;; you may click on the part before the citations. here we make
1408 ;; sure to move to the beginning so you get the first citation.
1410 (goto-char (org-element-property :begin object))
1411 (search-forward link-string (org-element-property :end object))
1412 (goto-char (match-beginning 0))
1413 ;; check if we clicked before the path and move as needed.
1414 (unless (< cp (point))
1417 (if (not (org-element-property :contents-begin object))
1418 ;; this means no description in the link
1420 ;; we need the link path start and end
1422 (goto-char (org-element-property :begin object))
1423 (search-forward link-string nil nil 1)
1424 (setq link-string-beginning (match-beginning 0))
1425 (setq link-string-end (match-end 0)))
1427 ;; The key is the text between commas, or the link boundaries
1429 (if (search-forward "," link-string-end t 1)
1430 (setq key-end (- (match-end 0) 1)) ; we found a match
1431 (setq key-end link-string-end))) ; no comma found so take the end
1432 ;; and backward to previous comma from point which defines the start character
1434 (if (search-backward "," link-string-beginning 1 1)
1435 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1436 (setq key-beginning link-string-beginning))) ; no match found
1437 ;; save the key we clicked on.
1439 (org-ref-strip-string
1440 (buffer-substring key-beginning key-end)))
1441 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1443 ;; link with description. assume only one key
1446 (defun org-ref-find-bibliography ()
1447 "Find the bibliography in the buffer.
1448 This function sets and returns cite-bibliography-files, which is a list of files
1449 either from bibliography:f1.bib,f2.bib
1450 \bibliography{f1,f2}
1451 internal bibliographies
1453 falling back to what the user has set in `org-ref-default-bibliography'"
1456 (goto-char (point-min))
1457 ;; look for a bibliography link
1458 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1459 (setq org-ref-bibliography-files
1460 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1461 (throw 'result org-ref-bibliography-files))
1464 ;; we did not find a bibliography link. now look for \bibliography
1465 (goto-char (point-min))
1466 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1467 ;; split, and add .bib to each file
1468 (setq org-ref-bibliography-files
1469 (mapcar (lambda (x) (concat x ".bib"))
1470 (mapcar 'org-ref-strip-string
1471 (split-string (match-string 1) ","))))
1472 (throw 'result org-ref-bibliography-files))
1474 ;; no bibliography found. maybe we need a biblatex addbibresource
1475 (goto-char (point-min))
1476 ;; look for a bibliography link
1477 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1478 (setq org-ref-bibliography-files
1479 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1480 (throw 'result org-ref-bibliography-files))
1482 ;; we did not find anything. use defaults
1483 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1485 ;; set reftex-default-bibliography so we can search
1486 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1487 org-ref-bibliography-files)
1489 (defun org-ref-key-in-file-p (key filename)
1490 "Determine if the KEY is in the FILENAME."
1491 (save-current-buffer
1492 (let ((bibtex-files (list filename)))
1493 ;; This is something I am trying because when the bibtex file is open, and
1494 ;; you have added to it, the only way I find to get the update to update
1495 ;; is to close it and reopen it. or to save it and revert it.
1496 (when (get-file-buffer filename)
1497 (set-buffer (get-file-buffer filename))
1499 (revert-buffer t t))
1500 (bibtex-search-entry key t))))
1502 (defun org-ref-get-bibtex-key-and-file (&optional key)
1503 "Return the bibtex KEY and file that it is in. If no key is provided, get one under point."
1504 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1507 (setq key (org-ref-get-bibtex-key-under-cursor)))
1508 (setq file (catch 'result
1509 (loop for file in org-ref-bibliography-files do
1510 (if (org-ref-key-in-file-p key (file-truename file))
1511 (throw 'result file)))))
1514 ;; *** key at point functions
1516 (defun org-ref-open-pdf-at-point ()
1517 "Open the pdf for bibtex key under point if it exists."
1519 (let* ((results (org-ref-get-bibtex-key-and-file))
1521 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1522 (if (file-exists-p pdf-file)
1523 (org-open-file pdf-file)
1524 (message "no pdf found for %s" key))))
1527 (defun org-ref-open-url-at-point ()
1528 "Open the url for bibtex key under point."
1530 (let* ((results (org-ref-get-bibtex-key-and-file))
1532 (bibfile (cdr results)))
1535 (insert-file-contents bibfile)
1536 (bibtex-search-entry key)
1537 ;; I like this better than bibtex-url which does not always find
1540 (let ((url (bibtex-autokey-get-field "url")))
1542 (browse-url (s-trim url))
1545 (let ((doi (bibtex-autokey-get-field "doi")))
1547 (if (string-match "^http" doi)
1549 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1550 (throw 'done nil))))))))
1553 (defun org-ref-open-notes-at-point ()
1554 "Open the notes for bibtex key under point."
1556 (let* ((results (org-ref-get-bibtex-key-and-file))
1558 (bibfile (cdr results)))
1561 (insert-file-contents bibfile)
1562 (bibtex-search-entry key)
1563 (org-ref-open-bibtex-notes)))))
1566 (defun org-ref-citation-at-point ()
1567 "Give message of current citation at point."
1569 (let* ((cb (current-buffer))
1570 (results (org-ref-get-bibtex-key-and-file))
1572 (bibfile (cdr results)))
1573 (message "%s" (progn
1575 (insert-file-contents bibfile)
1576 (bibtex-search-entry key)
1577 (org-ref-bib-citation))))))
1580 (defun org-ref-open-citation-at-point ()
1581 "Open bibtex file to key at point."
1583 (let* ((cb (current-buffer))
1584 (results (org-ref-get-bibtex-key-and-file))
1586 (bibfile (cdr results)))
1588 (bibtex-search-entry key)))
1592 (defvar org-ref-cite-menu-funcs '()
1593 "Functions to run on cite click menu.
1594 Each entry is a list of (key menu-name function).
1595 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.")
1598 (defvar org-ref-user-cite-menu-funcs
1599 '(("C" "rossref" org-ref-crossref-at-point)
1600 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1601 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1602 "User-defined functions to run on bibtex key at point.")
1605 (defun org-ref-copy-entry-as-summary ()
1606 "Copy the bibtex entry for the citation at point as a summary."
1608 (save-window-excursion
1609 (org-ref-open-citation-at-point)
1610 (kill-new (org-ref-bib-citation))))
1613 (defun org-ref-copy-entry-at-point-to-file ()
1614 "Copy the bibtex entry for the citation at point to NEW-FILE.
1615 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."
1617 (let ((new-file (ido-completing-read
1619 (append org-ref-default-bibliography
1620 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1621 (key (org-ref-get-bibtex-key-under-cursor)))
1622 (save-window-excursion
1623 (org-ref-open-citation-at-point)
1624 (bibtex-copy-entry-as-kill))
1626 (let ((bibtex-files (list (file-truename new-file))))
1627 (if (assoc key (bibtex-global-key-alist))
1628 (message "That key already exists in %s" new-file)
1630 (save-window-excursion
1631 (find-file new-file)
1632 (goto-char (point-max))
1633 ;; make sure we are at the beginning of a line.
1634 (unless (looking-at "^") (insert "\n\n"))
1639 (defun org-ref-get-doi-at-point ()
1640 "Get doi for key at point."
1641 (let* ((results (org-ref-get-bibtex-key-and-file))
1643 (bibfile (cdr results))
1647 (insert-file-contents bibfile)
1648 (bibtex-search-entry key)
1649 (setq doi (bibtex-autokey-get-field "doi"))
1650 ;; in case doi is a url, remove the url part.
1651 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1654 ;; **** functions that operate on key at point for click menu
1655 (defun org-ref-wos-at-point ()
1656 "Open the doi in wos for bibtex key under point."
1658 (doi-utils-wos (org-ref-get-doi-at-point)))
1661 (defun org-ref-wos-citing-at-point ()
1662 "Open the doi in wos citing articles for bibtex key under point."
1664 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1667 (defun org-ref-wos-related-at-point ()
1668 "Open the doi in wos related articles for bibtex key under point."
1670 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1673 (defun org-ref-google-scholar-at-point ()
1674 "Open the doi in google scholar for bibtex key under point."
1676 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1679 (defun org-ref-pubmed-at-point ()
1680 "Open the doi in pubmed for bibtex key under point."
1682 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1685 (defun org-ref-crossref-at-point ()
1686 "Open the doi in crossref for bibtex key under point."
1688 (doi-utils-crossref (org-ref-get-doi-at-point)))
1690 ;; *** Minibuffer menu
1692 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1693 "Action when a cite link is clicked on.
1694 Provides a menu of context sensitive actions. If the bibtex entry
1695 has a pdf, you get an option to open it. If there is a doi, you
1696 get a lot of options. LINK-STRING is used by the link function."
1698 (let* ((results (org-ref-get-bibtex-key-and-file))
1700 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1701 (bibfile (cdr results))
1702 (url (save-excursion
1704 (insert-file-contents bibfile)
1705 (bibtex-search-entry key)
1706 (bibtex-autokey-get-field "url"))))
1707 (doi (save-excursion
1709 (insert-file-contents bibfile)
1710 (bibtex-search-entry key)
1711 ;; I like this better than bibtex-url which does not always find
1713 (bibtex-autokey-get-field "doi")))))
1715 (when (string= "" doi) (setq doi nil))
1716 (when (string= "" url) (setq url nil))
1717 (setq org-ref-cite-menu-funcs '())
1723 'org-ref-cite-menu-funcs
1724 '("o" "pen" org-ref-open-citation-at-point)))
1727 (when (file-exists-p pdf-file)
1729 'org-ref-cite-menu-funcs
1730 `("p" "df" ,org-ref-open-pdf-function) t))
1734 'org-ref-cite-menu-funcs
1735 '("n" "otes" org-ref-open-notes-at-point) t)
1740 'org-ref-cite-menu-funcs
1741 '("u" "rl" org-ref-open-url-at-point) t))
1746 'org-ref-cite-menu-funcs
1747 '("w" "os" org-ref-wos-at-point) t)
1750 'org-ref-cite-menu-funcs
1751 '("c" "iting" org-ref-wos-citing-at-point) t)
1754 'org-ref-cite-menu-funcs
1755 '("r" "elated" org-ref-wos-related-at-point) t)
1758 'org-ref-cite-menu-funcs
1759 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1762 'org-ref-cite-menu-funcs
1763 '("P" "ubmed" org-ref-pubmed-at-point) t))
1765 ;; add user functions
1766 (dolist (tup org-ref-user-cite-menu-funcs)
1768 'org-ref-cite-menu-funcs
1773 'org-ref-cite-menu-funcs
1774 '("q" "uit" (lambda ())) t)
1776 ;; now we make a menu
1777 ;; construct menu string as a message
1780 (let* ((results (org-ref-get-bibtex-key-and-file))
1782 (bibfile (cdr results)))
1785 (insert-file-contents bibfile)
1786 (bibtex-search-entry key)
1787 (org-ref-bib-citation))))
1791 (concat "[" (elt tup 0) "]"
1793 org-ref-cite-menu-funcs "")))
1795 (let* ((input (read-char-exclusive))
1797 (char-to-string input) org-ref-cite-menu-funcs)))
1798 ;; now run the function (2nd element in choice)
1805 ;; *** Generation of the cite links
1806 (defmacro org-ref-make-completion-function (type)
1807 "Macro to make a link completion function for a link of TYPE."
1808 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1814 (let ((bibtex-files (org-ref-find-bibliography)))
1815 (bibtex-global-key-alist))))))
1817 (defmacro org-ref-make-format-function (type)
1818 "Macro to make a format function for a link of TYPE."
1819 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1824 (format "[[#%s][%s]]" key key))
1825 (org-ref-split-and-strip-string keyword) ","))
1832 (org-ref-split-and-strip-string keyword) ",") "]"))
1837 (format "<a href=\"#%s\">%s</a>" key key))
1838 (org-ref-split-and-strip-string keyword) ","))
1841 (if (string= (substring type -1) "s")
1842 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1843 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1844 (org-ref-split-and-strip-string keyword) ""))
1846 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1847 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1849 ;; for markdown we generate pandoc citations
1852 (desc ;; pre and or post text
1853 (let* ((text (split-string desc "::"))
1857 (format "[@%s," keyword)
1858 (when pre (format " %s" pre))
1859 (when post (format ", %s" post))
1864 (lambda (key) (concat "@" key))
1865 (org-ref-split-and-strip-string keyword)
1868 (defun org-ref-format-citation-description (desc)
1869 "Return formatted citation description.
1870 If the cite link has a DESC (description), it is optional text
1871 for the citation command. You can specify pre and post text by
1872 separating these with ::, for example [[cite:key][pre text::post
1875 ((string-match "::" desc)
1876 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1877 (t (format "[%s]" desc))))
1879 (defun org-ref-define-citation-link (type &optional key)
1880 "Add a citation link of TYPE for org-ref.
1881 With optional KEY, set the reftex binding. For example:
1882 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1883 citez link, with reftex key of z, and the completion function."
1884 (interactive "sCitation Type: \ncKey: ")
1886 ;; create the formatting function
1887 (eval `(org-ref-make-format-function ,type))
1892 org-ref-cite-onclick-function
1893 (quote ,(intern (format "org-ref-format-%s" type)))))
1895 ;; create the completion function
1896 (eval `(org-ref-make-completion-function ,type))
1898 ;; store new type so it works with adding citations, which checks
1899 ;; for existence in this list
1900 (add-to-list 'org-ref-cite-types type)
1902 ;; and finally if a key is specified, we modify the reftex menu
1904 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1905 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1906 `((,key . ,(concat type ":%l")))))))
1908 ;; create all the link types and their completion functions
1909 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1911 (defun org-ref-insert-cite-link (alternative-cite)
1912 "Insert a default citation link using reftex.
1913 If you are on a link, it appends to the end of the link,
1914 otherwise, a new link is inserted. Use a prefix
1915 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1917 (org-ref-find-bibliography)
1918 (let* ((object (org-element-context))
1919 (link-string-beginning (org-element-property :begin object))
1920 (link-string-end (org-element-property :end object))
1921 (path (org-element-property :path object)))
1923 (if (not alternative-cite)
1926 ;; case where we are in a link
1927 ((and (equal (org-element-type object) 'link)
1928 (-contains? org-ref-cite-types (org-element-property :type object)))
1929 (goto-char link-string-end)
1930 ;; sometimes there are spaces at the end of the link
1931 ;; this code moves point pack until no spaces are there
1932 (while (looking-back " ") (backward-char))
1933 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1935 ;; We are next to a link, and we want to append
1938 (and (equal (org-element-type (org-element-context)) 'link)
1939 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1940 (while (looking-back " ") (backward-char))
1941 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1943 ;; insert fresh link
1946 (concat org-ref-default-citation-link
1948 (mapconcat 'identity (reftex-citation t) ",")))))
1950 ;; you pressed a C-u so we run this code
1951 (reftex-citation))))
1953 (defun org-ref-insert-cite-with-completion (type)
1954 "Insert a cite link of TYPE with completion."
1955 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1956 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1958 (defun org-ref-store-bibtex-entry-link ()
1959 "Save a citation link to the current bibtex entry. Save in the default link type."
1961 (let ((link (concat org-ref-default-citation-link
1964 (bibtex-beginning-of-entry)
1965 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1966 (message "saved %s" link)
1967 (push (list link) org-stored-links)
1968 (car org-stored-links)))
1976 (lambda (path desc format)
1979 (format "\\index{%s}" path)))))
1981 ;; this will generate a temporary index of entries in the file.
1985 (let ((*index-links* '())
1986 (*initial-letters* '()))
1989 (org-element-map (org-element-parse-buffer) 'link
1991 (let ((type (nth 0 link))
1992 (plist (nth 1 link)))
1994 (when (equal (plist-get plist ':type) "index")
1997 (cons (plist-get plist :path)
1999 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2001 (plist-get plist :begin) ;; position of link
2002 ;; grab a description
2004 (goto-char (plist-get plist :begin))
2005 (if (thing-at-point 'sentence)
2007 (replace-regexp-in-string
2008 "\n" "" (thing-at-point 'sentence))
2009 ;; or call it a link
2013 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2015 ;; now first letters
2016 (dolist (link *index-links*)
2017 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2019 ;; now create the index
2020 (switch-to-buffer (get-buffer-create "*index*"))
2023 (insert "#+TITLE: Index\n\n")
2024 (dolist (letter *initial-letters*)
2025 (insert (format "* %s\n" (upcase letter)))
2026 ;; now process the links
2029 (string= letter (substring (car (car *index-links*)) 0 1)))
2030 (let ((link (pop *index-links*)))
2031 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2032 (switch-to-buffer "*index*")))
2034 (lambda (path desc format)
2037 (format "\\printindex")))))
2042 nil ;; no follow action
2043 (lambda (path desc format)
2046 (format "\\newglossaryentry{%s}{%s}" path desc)))))
2052 nil ;; no follow action
2053 (lambda (path desc format)
2056 (format "\\gls{%s}" path)))))
2061 nil ;; no follow action
2062 (lambda (path desc format)
2065 (format "\\glspl{%s}" path)))))
2070 nil ;; no follow action
2071 (lambda (path desc format)
2074 (format "\\Gls{%s}" path)))))
2079 nil ;; no follow action
2080 (lambda (path desc format)
2083 (format "\\Glspl{%s}" path)))))
2086 ;; ** create text citations from a bibtex entry
2087 (defun org-ref-bib-citation ()
2088 "From a bibtex entry, create and return a simple citation string.
2089 This assumes you are in an article."
2091 (bibtex-beginning-of-entry)
2092 (let* ((cb (current-buffer))
2093 (bibtex-expand-strings t)
2094 (entry (loop for (key . value) in (bibtex-parse-entry t)
2095 collect (cons (downcase key) value)))
2096 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2097 (year (reftex-get-bib-field "year" entry))
2098 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2099 (key (reftex-get-bib-field "=key=" entry))
2100 (journal (reftex-get-bib-field "journal" entry))
2101 (volume (reftex-get-bib-field "volume" entry))
2102 (pages (reftex-get-bib-field "pages" entry))
2103 (doi (reftex-get-bib-field "doi" entry))
2104 (url (reftex-get-bib-field "url" entry))
2106 ;;authors, "title", Journal, vol(iss):pages (year).
2107 (format "%s, \"%s\", %s, %s:%s (%s)"
2108 author title journal volume pages year)))
2110 (defun org-ref-bib-html-citation ()
2111 "From a bibtex entry, create and return a simple citation with html links."
2112 (bibtex-beginning-of-entry)
2113 (let* ((cb (current-buffer))
2114 (bibtex-expand-strings t)
2115 (entry (loop for (key . value) in (bibtex-parse-entry t)
2116 collect (cons (downcase key) value)))
2117 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2118 (year (reftex-get-bib-field "year" entry))
2119 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2120 (key (reftex-get-bib-field "=key=" entry))
2121 (journal (reftex-get-bib-field "journal" entry))
2122 (volume (reftex-get-bib-field "volume" entry))
2123 (pages (reftex-get-bib-field "pages" entry))
2124 (doi (reftex-get-bib-field "doi" entry))
2125 (url (reftex-get-bib-field "url" entry)))
2126 ;;authors, "title", Journal, vol(iss):pages (year).
2127 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2128 author title journal volume pages year)
2129 (when url (format " <a href=\"%s\">link</a>" url))
2131 (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
2133 ;; ** Open pdf in bibtex entry
2134 (defun org-ref-open-bibtex-pdf ()
2135 "Open pdf for a bibtex entry, if it exists.
2137 the entry of interest in the bibfile. but does not check that."
2140 (bibtex-beginning-of-entry)
2141 (let* ((bibtex-expand-strings t)
2142 (entry (bibtex-parse-entry t))
2143 (key (reftex-get-bib-field "=key=" entry))
2144 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2146 (if (file-exists-p pdf)
2147 (org-open-link-from-string (format "[[file:%s]]" pdf))
2150 ;; ** Open notes from bibtex entry
2152 (defun org-ref-open-bibtex-notes ()
2153 "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2155 I never did figure out how to use reftex to make this happen
2156 non-interactively. the reftex-format-citation function did not
2157 work perfectly; there were carriage returns in the strings, and
2158 it did not put the key where it needed to be. so, below I replace
2159 the carriage returns and extra spaces with a single space and
2160 construct the heading by hand."
2163 (bibtex-beginning-of-entry)
2164 (let* ((cb (current-buffer))
2165 (bibtex-expand-strings t)
2166 (entry (loop for (key . value) in (bibtex-parse-entry t)
2167 collect (cons (downcase key) value)))
2168 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2169 (year (reftex-get-bib-field "year" entry))
2170 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2171 (key (reftex-get-bib-field "=key=" entry))
2172 (journal (reftex-get-bib-field "journal" entry))
2173 (volume (reftex-get-bib-field "volume" entry))
2174 (pages (reftex-get-bib-field "pages" entry))
2175 (doi (reftex-get-bib-field "doi" entry))
2176 (url (reftex-get-bib-field "url" entry))
2179 ;; save key to clipboard to make saving pdf later easier by pasting.
2182 (kill-ring-save (point-min) (point-max)))
2184 ;; now look for entry in the notes file
2185 (if org-ref-bibliography-notes
2186 (find-file-other-window org-ref-bibliography-notes)
2187 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2189 (goto-char (point-min))
2190 ;; put new entry in notes if we don't find it.
2191 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2192 (funcall org-ref-open-notes-function)
2193 ;; no entry found, so add one
2194 (insert (format "\n** TODO %s - %s" year title))
2206 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2207 key author journal year volume pages doi url key org-ref-pdf-directory key))
2210 (defun org-ref-open-notes-from-reftex ()
2211 "Call reftex, and open notes for selected entry."
2213 (let ((bibtex-key )))
2215 ;; now look for entry in the notes file
2216 (if org-ref-bibliography-notes
2217 (find-file-other-window org-ref-bibliography-notes)
2218 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2220 (goto-char (point-min))
2222 (re-search-forward (format
2224 (first (reftex-citation t)) nil 'end))
2225 (funcall org-ref-open-notes-function))
2227 ;; ** Open bibtex entry in browser
2228 (defun org-ref-open-in-browser ()
2229 "Open the bibtex entry at point in a browser using the url field or doi field."
2232 (bibtex-beginning-of-entry)
2234 (let ((url (bibtex-autokey-get-field "url")))
2239 (let ((doi (bibtex-autokey-get-field "doi")))
2241 (if (string-match "^http" doi)
2243 (browse-url (format "http://dx.doi.org/%s" doi)))
2245 (message "No url or doi found"))))
2247 ;; ** upload entry to citeulike
2249 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2250 "With point in a bibtex entry get bibtex string and submit to citeulike.
2252 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2254 (message "uploading to citeulike")
2256 (bibtex-narrow-to-entry)
2257 (let ((startpos (point-min))
2258 (endpos (point-max))
2259 (bibtex-string (buffer-string))
2260 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2261 (with-temp-buffer (insert bibtex-string)
2262 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2264 ;; ** Build a pdf of the bibtex file
2265 (defun org-ref-build-full-bibliography ()
2266 "Build pdf of all bibtex entries, and open it."
2268 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2269 (bib-base (file-name-sans-extension bibfile))
2270 (texfile (concat bib-base ".tex"))
2271 (pdffile (concat bib-base ".pdf")))
2274 (insert (format "\\documentclass[12pt]{article}
2275 \\usepackage[version=3]{mhchem}
2277 \\usepackage[numbers]{natbib}
2278 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2282 \\bibliographystyle{unsrtnat}
2284 \\end{document}" bib-base))
2286 (shell-command (concat "pdflatex " bib-base))
2287 (shell-command (concat "bibtex " bib-base))
2288 (shell-command (concat "pdflatex " bib-base))
2289 (shell-command (concat "pdflatex " bib-base))
2290 (kill-buffer texfile)
2291 (org-open-file pdffile)
2294 ;; ** Extract bibtex entries in org-file
2296 (defun org-ref-extract-bibtex-entries ()
2297 "Extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2299 If no bibliography is in the buffer the variable
2300 `reftex-default-bibliography' is used."
2302 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2303 (tempname (make-temp-file "extract-bib"))
2304 (contents (buffer-string))
2305 (cb (current-buffer))
2306 basename texfile bibfile results)
2308 ;; open tempfile and insert org-buffer contents
2309 (find-file tempname)
2311 (setq basename (file-name-sans-extension
2312 (file-name-nondirectory buffer-file-name))
2313 texfile (concat tempname ".tex")
2314 bibfile (concat tempname ".bib"))
2316 ;; see if we have a bibliography, and insert the default one if not.
2318 (goto-char (point-min))
2319 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2320 (insert (format "\nbibliography:%s"
2321 (mapconcat 'identity reftex-default-bibliography ",")))))
2324 ;; get a latex file and extract the references
2325 (org-latex-export-to-latex)
2328 (reftex-create-bibtex-file bibfile)
2330 ;; save results of the references
2331 (setq results (buffer-string))
2333 ;; kill buffers. these are named by basename, not full path
2334 (kill-buffer (concat basename ".bib"))
2335 (kill-buffer (concat basename ".tex"))
2336 (kill-buffer basename)
2338 (delete-file bibfile)
2339 (delete-file texfile)
2340 (delete-file tempname)
2342 ;; Now back to the original org buffer and insert the results
2343 (switch-to-buffer cb)
2344 (when (not (string= "" results))
2346 (goto-char (point-max))
2348 (org-insert-heading)
2349 (insert (format " Bibtex entries
2351 #+BEGIN_SRC text :tangle %s
2353 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2355 ;; ** Find bad citations
2358 (defun index (substring list)
2359 "Return the index of SUBSTRING in a LIST of strings."
2362 (dolist (arg list i)
2363 (if (string-match (concat "^" substring "$") arg)
2368 ;; return counter if found, otherwise return nil
2372 (defun org-ref-find-bad-citations ()
2373 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2375 Makes a new buffer with clickable links."
2377 ;; generate the list of bibtex-keys and cited keys
2378 (let* ((bibtex-files (org-ref-find-bibliography))
2379 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2380 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2381 (bad-citations '()))
2383 (org-element-map (org-element-parse-buffer) 'link
2385 (let ((plist (nth 1 link)))
2386 (when (-contains? org-ref-cite-types (plist-get plist :type))
2387 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2388 (when (not (index key bibtex-keys))
2393 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2396 (plist-get plist :begin)))))
2398 ;; set with-affilates to t to get citations in a caption
2403 (switch-to-buffer-other-window "*Missing citations*")
2406 (insert "* List of bad cite links\n")
2407 (insert (mapconcat 'identity bad-citations ""))
2408 ;(setq buffer-read-only t)
2409 (use-local-map (copy-keymap org-mode-map))
2410 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2412 (when (get-buffer "*Missing citations*")
2413 (kill-buffer "*Missing citations*"))
2414 (message "No bad cite links found"))))
2416 ;; ** helm interface to bad citations, labels, refs and files in orgfile
2417 (defun org-ref-bad-cite-candidates ()
2418 "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2419 (let* ((cp (point)) ; save to return to later
2420 (bibtex-files (org-ref-find-bibliography))
2421 (bibtex-file-path (mapconcat
2423 (file-name-directory (file-truename x)))
2425 (bibtex-keys (mapcar (lambda (x) (car x))
2426 (bibtex-global-key-alist)))
2427 (bad-citations '()))
2429 (org-element-map (org-element-parse-buffer) 'link
2431 (let ((plist (nth 1 link)))
2432 (when (-contains? org-ref-cite-types (plist-get plist :type))
2433 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2434 (when (not (index key bibtex-keys))
2435 (goto-char (plist-get plist :begin))
2436 (re-search-forward key)
2437 (push (cons key (point-marker)) bad-citations)))
2439 ;; add with-affiliates to get cites in caption
2445 (defun org-ref-bad-ref-candidates ()
2446 "Return a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2447 ;; first get a list of legitimate labels
2449 (labels (org-ref-get-labels))
2451 ;; now loop over ref links
2452 (goto-char (point-min))
2453 (org-element-map (org-element-parse-buffer) 'link
2455 (let ((plist (nth 1 link)))
2456 (when (or (equal (plist-get plist ':type) "ref")
2457 (equal (plist-get plist ':type) "eqref")
2458 (equal (plist-get plist ':type) "pageref")
2459 (equal (plist-get plist ':type) "nameref"))
2460 (unless (-contains? labels (plist-get plist :path))
2461 (goto-char (plist-get plist :begin))
2464 (cons (plist-get plist :path)
2465 (point-marker))))))))
2470 (defun org-ref-bad-label-candidates ()
2471 "Return a list of labels where label is multiply defined."
2472 (let ((labels (org-ref-get-labels))
2473 (multiple-labels '()))
2474 (when (not (= (length labels)
2475 (length (-uniq labels))))
2476 (dolist (label labels)
2477 (when (> (-count (lambda (a)
2480 ;; this is a multiply defined label.
2482 (goto-char (point-min))
2483 (while (re-search-forward
2484 (format "[^#+]label:%s\\s-" label) nil t)
2485 (push (cons label (point-marker)) multiple-labels))
2486 (goto-char (point-min))
2487 (while (re-search-forward
2488 (format "\\label{%s}\\s-?" label) nil t)
2489 (push (cons label (point-marker)) multiple-labels))
2491 (goto-char (point-min))
2492 (while (re-search-forward
2493 (format "^#\\+label:\\s-*%s" label) nil t)
2494 (push (cons label (point-marker)) multiple-labels))
2496 (goto-char (point-min))
2497 (while (re-search-forward
2498 (format "^#\\+tblname:\\s-*%s" label) nil t)
2499 (push (cons label (point-marker)) multiple-labels))
2503 (defun org-ref-bad-file-link-candidates ()
2504 "Return list of conses (link . marker) wehre the file in the link does not exist."
2505 (let* ((bad-files '()))
2506 (org-element-map (org-element-parse-buffer) 'link
2508 (let ((type (org-element-property :type link)))
2509 (when (or (string= "file" type)
2510 (string= "attachfile" type))
2511 (unless (file-exists-p (org-element-property :path link))
2512 (add-to-list 'bad-files
2513 (cons (org-element-property :path link)
2516 (org-element-property :begin link))
2517 (point-marker)))))))))
2518 ;; Let us also check \attachfile{fname}
2520 (goto-char (point-min))
2521 (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
2522 (unless (file-exists-p (match-string 1))
2523 (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
2528 "Opens a helm interface to actions for org-ref.
2529 Shows bad citations, ref links and labels"
2531 (let ((cb (current-buffer))
2532 (bad-citations (org-ref-bad-cite-candidates))
2533 (bad-refs (org-ref-bad-ref-candidates))
2534 (bad-labels (org-ref-bad-label-candidates))
2535 (bad-files (org-ref-bad-file-link-candidates)))
2537 (helm :sources `(((name . "Bad citations")
2538 (candidates . ,bad-citations)
2539 (action . (lambda (marker)
2540 (switch-to-buffer (marker-buffer marker))
2541 (goto-char marker))))
2543 ((name . "Bad Labels")
2544 (candidates . ,bad-labels)
2545 (action . (lambda (marker)
2546 (switch-to-buffer (marker-buffer marker))
2547 (goto-char marker))))
2549 ((name . "Bad ref links")
2550 (candidates . ,bad-refs)
2551 (action . (lambda (marker)
2552 (switch-to-buffer (marker-buffer marker))
2553 (goto-char marker))))
2555 ((name . "Bad file links")
2556 (candidates . ,bad-files)
2558 (switch-to-buffer (marker-buffer marker))
2559 (goto-char marker)))
2561 ((name . "Utilities")
2562 (candidates . (("Check buffer again" . org-ref)
2563 ("Insert citation" . helm-bibtex)
2564 ("Insert label link" . org-ref-helm-insert-label-link)
2565 ("Insert ref link" . org-ref-helm-insert-ref-link)
2566 ("List of figures" . org-ref-list-of-figures)
2567 ("List of tables" . org-ref-list-of-tables)
2568 ("Table of contents" . nil)
2570 (action . (lambda (x)
2571 (switch-to-buffer ,cb)
2574 ((name . "Export functions")
2575 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2576 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2577 ("Export to pdf and open" . (lambda ()
2578 (org-open-file (org-latex-export-to-pdf))))
2579 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2580 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2583 (action . (lambda (x)
2584 (switch-to-buffer ,cb)
2587 ;; ** Find non-ascii charaters
2588 (defun org-ref-find-non-ascii-characters ()
2589 "Find non-ascii characters in the buffer. Useful for cleaning up bibtex files."
2591 (occur "[^[:ascii:]]"))
2593 ;; ** Sort fields in a bibtex entry
2595 (defun org-ref-sort-bibtex-entry ()
2596 "Sort fields of entry in standard order and downcase them."
2598 (bibtex-beginning-of-entry)
2599 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2600 (entry (bibtex-parse-entry))
2603 (type (cdr (assoc "=type=" entry)))
2604 (key (cdr (assoc "=key=" entry))))
2606 ;; these are the fields we want to order that are in this entry
2607 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2608 ;; we do not want to reenter these fields
2609 (setq entry-fields (remove "=key=" entry-fields))
2610 (setq entry-fields (remove "=type=" entry-fields))
2612 ;;these are the other fields in the entry
2613 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2616 ;; right now we only resort articles
2617 ((string= (downcase type) "article")
2620 (concat "@article{" key ",\n"
2623 (when (member field entry-fields)
2624 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2627 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2629 (bibtex-find-entry key)
2631 (bibtex-clean-entry)
2634 ;; ** Clean a bibtex entry
2635 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2636 "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"
2638 (bibtex-beginning-of-entry)
2640 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2641 (unless (string-match ",$" (thing-at-point 'line))
2645 ;; check for empty pages, and put eid or article id in its place
2646 (let ((entry (bibtex-parse-entry))
2647 (pages (bibtex-autokey-get-field "pages"))
2648 (year (bibtex-autokey-get-field "year"))
2649 (doi (bibtex-autokey-get-field "doi"))
2650 ;; The Journal of Chemical Physics uses eid
2651 (eid (bibtex-autokey-get-field "eid")))
2653 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2654 ;; but we only want the doi.
2655 (when (string-match "^http://dx.doi.org/" doi)
2656 (bibtex-beginning-of-entry)
2657 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2659 (bibtex-make-field "doi")
2661 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2663 ;; asap articles often set year to 0, which messes up key
2664 ;; generation. fix that.
2665 (when (string= "0" year)
2666 (bibtex-beginning-of-entry)
2667 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2669 (bibtex-make-field "year")
2671 (insert (read-string "Enter year: ")))
2673 ;; fix pages if they are empty if there is an eid to put there.
2674 (when (string= "-" pages)
2676 (bibtex-beginning-of-entry)
2677 ;; this seems like a clunky way to set the pages field.But I
2678 ;; cannot find a better way.
2679 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2681 (bibtex-make-field "pages")
2685 ;; replace naked & with \&
2687 (bibtex-narrow-to-entry)
2688 (bibtex-beginning-of-entry)
2689 (message "checking &")
2690 (replace-regexp " & " " \\\\& ")
2693 ;; generate a key, and if it duplicates an existing key, edit it.
2695 (let ((key (bibtex-generate-autokey)))
2697 ;; first we delete the existing key
2698 (bibtex-beginning-of-entry)
2699 (re-search-forward bibtex-entry-maybe-empty-head)
2700 (if (match-beginning bibtex-key-in-head)
2701 (delete-region (match-beginning bibtex-key-in-head)
2702 (match-end bibtex-key-in-head)))
2703 ;; check if the key is in the buffer
2704 (when (save-excursion
2705 (bibtex-search-entry key))
2707 (bibtex-search-entry key)
2708 (bibtex-copy-entry-as-kill)
2709 (switch-to-buffer-other-window "*duplicate entry*")
2711 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2714 (kill-new key))) ;; save key for pasting
2716 ;; run hooks. each of these operates on the entry with no arguments.
2717 ;; this did not work like i thought, it gives a symbolp error.
2718 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2723 org-ref-clean-bibtex-entry-hook)
2725 ;; sort fields within entry
2726 (org-ref-sort-bibtex-entry)
2727 ;; check for non-ascii characters
2728 (occur "[^[:ascii:]]")
2731 (defun org-ref-get-citation-year (key)
2732 "Get the year of an entry with KEY. Return year as a string."
2733 (let* ((results (org-ref-get-bibtex-key-and-file key))
2734 (bibfile (cdr results)))
2736 (insert-file-contents bibfile)
2737 (bibtex-search-entry key nil 0)
2738 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2741 ;; ** Sort cite in cite link
2742 (defun org-ref-sort-citation-link ()
2743 "Replace link at point with sorted link by year."
2745 (let* ((object (org-element-context))
2746 (type (org-element-property :type object))
2747 (begin (org-element-property :begin object))
2748 (end (org-element-property :end object))
2749 (link-string (org-element-property :path object))
2751 (setq keys (org-ref-split-and-strip-string link-string))
2752 (setq years (mapcar 'org-ref-get-citation-year keys))
2753 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2754 (setq data (cl-sort data (lambda (x y) (< (string-to-int (car x)) (string-to-int (car y))))))
2755 ;; now get the keys separated by commas
2756 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2757 ;; and replace the link with the sorted keys
2758 (cl--set-buffer-substring begin end (concat type ":" keys))))
2760 ;; ** Shift-arrow sorting of keys in a cite link
2762 (defun org-ref-swap-keys (i j keys)
2763 "Swap the KEYS in a list with index I and J."
2764 (let ((tempi (nth i keys)))
2765 (setf (nth i keys) (nth j keys))
2766 (setf (nth j keys) tempi))
2770 (defun org-ref-swap-citation-link (direction)
2771 "Move citation at point in DIRECTION +1 is to the right, -1 to the left."
2773 (let* ((object (org-element-context))
2774 (type (org-element-property :type object))
2775 (begin (org-element-property :begin object))
2776 (end (org-element-property :end object))
2777 (link-string (org-element-property :path object))
2779 ;; We only want this to work on citation links
2780 (when (-contains? org-ref-cite-types type)
2781 (setq key (org-ref-get-bibtex-key-under-cursor))
2782 (setq keys (org-ref-split-and-strip-string link-string))
2783 (setq i (index key keys)) ;; defined in org-ref
2784 (if (> direction 0) ;; shift right
2785 (org-ref-swap-keys i (+ i 1) keys)
2786 (org-ref-swap-keys i (- i 1) keys))
2787 (setq keys (mapconcat 'identity keys ","))
2788 ;; and replace the link with the sorted keys
2789 (cl--set-buffer-substring
2793 ;; It seems the space at the end can get consumed, so we see if there
2794 ;; is a space, and add it if so. Sometimes there is a comma or period,
2795 ;; then we do not want a space.
2799 (looking-back " ")) " ")))
2800 ;; now go forward to key so we can move with the key
2801 (re-search-forward key)
2802 (goto-char (match-beginning 0)))))
2804 ;; add hooks to make it work
2805 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2806 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2808 ;; ** context around org-ref links
2809 (defun org-ref-get-label-context (label)
2810 "Return a string of context around a LABEL."
2813 (goto-char (point-min))
2814 (when (re-search-forward
2815 (format "label:%s\\b" label) nil t)
2816 (throw 'result (buffer-substring
2825 (goto-char (point-min))
2826 (when (re-search-forward
2827 (format "\\label{%s}" label) nil t)
2828 (throw 'result (buffer-substring
2837 (goto-char (point-min))
2838 (when (re-search-forward
2839 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2840 (throw 'result (buffer-substring
2849 (goto-char (point-min))
2850 (when (re-search-forward
2851 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2852 (throw 'result (buffer-substring
2860 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2863 (defun org-ref-link-message ()
2864 "Print a minibuffer message about the link that point is on."
2868 (when (eq major-mode 'org-mode)
2869 (let* ((object (org-element-context))
2870 (type (org-element-property :type object)))
2874 ((-contains? org-ref-cite-types type)
2875 (message (org-ref-get-citation-string-at-point)))
2877 ;; message some context about the label we are referring to
2878 ((string= type "ref")
2879 (message "%scount: %s"
2880 (org-ref-get-label-context
2881 (org-element-property :path object))
2882 (org-ref-count-labels
2883 (org-element-property :path object))))
2885 ((string= type "eqref")
2886 (message "%scount: %s"
2887 (org-ref-get-label-context
2888 (org-element-property :path object))
2889 (org-ref-count-labels
2890 (org-element-property :path object))))
2892 ;; message the count
2893 ((string= type "label")
2894 (let ((count (org-ref-count-labels
2895 (org-element-property :path object))))
2896 ;; get plurality on occurrence correct
2898 (number-to-string count)
2900 (when (or (= count 0)
2904 ((string= type "custom-id")
2906 (org-open-link-from-string
2907 (format "[[#%s]]" (org-element-property :path object)))
2908 (message "%s" (org-get-heading))))
2910 ;; check if the bibliography files exist.
2911 ((string= type "bibliography")
2913 ;; object is the link you clicked on
2914 (object (org-element-context))
2915 (link-string (org-element-property :path object))
2916 (link-string-beginning)
2919 (goto-char (org-element-property :begin object))
2920 (search-forward link-string nil nil 1)
2921 (setq link-string-beginning (match-beginning 0))
2922 (setq link-string-end (match-end 0)))
2924 ;; make sure we are in link and not before the :
2925 (when (> link-string-beginning (point))
2926 (goto-char link-string-beginning))
2928 ;; now if we have comma separated bibliographies
2929 ;; we find the one clicked on. we want to
2930 ;; search forward to next comma from point
2932 (if (search-forward "," link-string-end 1 1)
2933 (setq key-end (- (match-end 0) 1)) ; we found a match
2934 (setq key-end (point)))) ; no comma found so take the point
2936 ;; and backward to previous comma from point
2938 (if (search-backward "," link-string-beginning 1 1)
2939 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2940 (setq key-beginning (point)))) ; no match found
2941 ;; save the key we clicked on.
2943 (org-ref-strip-string
2944 (buffer-substring key-beginning key-end)))
2945 (if (file-exists-p bibfile)
2946 (message "%s exists." bibfile)
2947 (message "!!! %s NOT FOUND !!!" bibfile))))))))))
2950 (defalias 'oro 'org-ref-open-citation-at-point)
2951 (defalias 'orc 'org-ref-citation-at-point)
2952 (defalias 'orp 'org-ref-open-pdf-at-point)
2953 (defalias 'oru 'org-ref-open-url-at-point)
2954 (defalias 'orn 'org-ref-open-notes-at-point)
2955 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2957 (defalias 'orib 'org-ref-insert-bibliography-link)
2958 (defalias 'oric 'org-ref-insert-cite-link)
2959 (defalias 'orir 'org-ref-insert-ref-link)
2960 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2962 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2964 ;; * Helm bibtex setup
2966 (setq helm-bibtex-additional-search-fields '(keywords))
2968 (defun helm-bibtex-candidates-formatter (candidates source)
2969 "Formats BibTeX entries for display in results list.
2970 Argument CANDIDATES helm candidates.
2971 Argument SOURCE the helm source."
2973 with width = (with-helm-window (helm-bibtex-window-width))
2974 for entry in candidates
2975 for entry = (cdr entry)
2976 for entry-key = (helm-bibtex-get-value "=key=" entry)
2977 if (assoc-string "author" entry 'case-fold)
2978 for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2980 for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
2981 for fields = (--map (helm-bibtex-clean-string
2982 (helm-bibtex-get-value it entry " "))
2984 for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
2985 for fields = (append fields
2986 (list (or (helm-bibtex-get-value "keywords" entry)
2989 (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
2990 (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
2991 fields (list 36 (- width 85) 4 1 1 7 7)))
2994 ;; * org-ref bibtex keywords
2995 ;; adapted from bibtex-utils.el
2996 ;; these are candidates for selecting keywords/tags
2997 (defun org-ref-bibtex-keywords ()
2998 "Get keywords defined in current bibtex file.
2999 These are in the keywords field, and are comma or semicolon separated."
3001 (goto-char (point-min))
3002 (let (keywords kstring)
3003 (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
3004 ;; TWS - remove newlines/multiple spaces:
3005 (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
3008 (add-to-list 'keywords v t))
3009 (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
3013 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
3014 "Add KEYWORDS to a bibtex entry.
3015 If KEYWORDS is a list, it is converted to a comma-separated
3016 string. The KEYWORDS are added to the beginning of the
3017 field. Otherwise KEYWORDS should be a string of comma-separate
3018 keywords. Optional argument ARG prefix arg to replace keywords."
3019 (interactive "sKeywords: \nP")
3024 (if (listp keywords)
3025 (mapconcat 'identity keywords ", ")
3027 ;; else concatentate
3029 (if (listp keywords)
3030 (mapconcat 'identity keywords ", ")
3032 (when (not (string= "" (bibtex-autokey-get-field "keywords")))
3033 (concat ", " (bibtex-autokey-get-field "keywords"))))))
3037 (defun helm-tag-bibtex-entry ()
3038 "Helm interface to add keywords to a bibtex entry.
3039 Run this with the point in a bibtex entry."
3041 (let ((keyword-source `((name . "Existing keywords")
3042 (candidates . ,(org-ref-bibtex-keywords))
3043 (action . (lambda (candidate)
3044 (org-ref-set-bibtex-keywords
3047 (helm-marked-candidates)
3049 (fallback-source `((name . "Add new keywords")
3051 (action . (lambda (candidate)
3052 (org-ref-set-bibtex-keywords helm-pattern)
3054 (helm :sources '(keyword-source fallback-source))))
3056 (defun helm-bibtex-show-entry (key)
3057 "Show the entry for KEY in the BibTeX file.
3058 The original function in `helm-bibtex' has a bug where it finds the
3059 first key that partially matches. This version avoids that."
3061 (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
3062 helm-bibtex-bibliography
3063 (list helm-bibtex-bibliography)))
3064 (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
3066 (find-file bibtex-file)
3068 (lambda (key start end)
3069 (add-to-list 'entries (cons key start))))
3070 (if (assoc key entries)
3072 (goto-char (cdr (assoc key entries)))
3077 (defun org-ref-helm-tag-entries (candidates)
3078 "Set tags on selected bibtex entries from `helm-bibtex'.
3079 User is prompted for tags. This function is called from `helm-bibtex'.
3080 Argument CANDIDATES helm candidates."
3082 (let ((keywords (read-string "Keywords (comma separated): ")))
3083 (loop for key in (helm-marked-candidates)
3085 (save-window-excursion
3086 (helm-bibtex-show-entry key)
3091 ", " (bibtex-autokey-get-field "keywords")))
3094 (setq helm-source-bibtex
3095 '((name . "BibTeX entries")
3096 (init . helm-bibtex-init)
3097 (candidates . helm-bibtex-candidates)
3098 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3099 (action . (("Insert citation" . helm-bibtex-insert-citation)
3100 ("Show entry" . helm-bibtex-show-entry)
3101 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3102 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3103 ("Insert formatted reference" . helm-bibtex-insert-reference)
3104 ("Insert BibTeX key" . helm-bibtex-insert-key)
3105 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3106 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3107 ("Edit notes" . helm-bibtex-edit-notes)
3108 ("Add keywords to entries" . org-ref-helm-tag-entries)
3111 (defun helm-bibtex-format-org-ref (keys)
3112 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3113 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.
3115 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3117 C-u C-u will change the key at point to the selected keys."
3118 (let* ((object (org-element-context))
3119 (last-char (save-excursion
3120 (when (org-element-property :end object)
3121 (goto-char (org-element-property :end object))
3124 (if (looking-at " ")
3128 ;; case where we are in a link
3129 ((and (equal (org-element-type object) 'link)
3132 (org-element-property :type object)))
3134 ;; no prefix. append keys
3135 ((equal helm-current-prefix-arg nil)
3136 (goto-char (org-element-property :end object))
3137 (while (looking-back " ") (backward-char))
3138 (insert (concat "," (mapconcat 'identity keys ","))))
3139 ;; double prefix, replace key at point
3140 ((equal helm-current-prefix-arg '(16))
3141 (setf (buffer-substring
3142 (org-element-property :begin object)
3143 (org-element-property :end object))
3145 (replace-regexp-in-string
3146 (car (org-ref-get-bibtex-key-and-file)) ; key
3147 (mapconcat 'identity keys ",") ; new keys
3148 (org-element-property :raw-link object))
3149 ;; replace space at end to avoid collapsing into next word.
3151 ;; and we want to go to the end of the new link
3153 (org-element-property :end (org-element-context))))
3155 (message "Not found"))))
3157 ;; We are next to a link, and we want to append
3158 ;; next to a link means one character back is on a link.
3160 (unless (bobp) (backward-char))
3161 (and (equal (org-element-type (org-element-context)) 'link)
3164 (org-element-property :type (org-element-context)))))
3165 (while (looking-back " ") (backward-char))
3166 (insert (concat "," (mapconcat 'identity keys ","))))
3168 ;; insert fresh link
3170 ;;(message-box "fresh link")
3172 (concat (if (equal helm-current-prefix-arg '(4))
3173 (helm :sources `((name . "link types")
3174 (candidates . ,org-ref-cite-types)
3175 (action . (lambda (x) x))))
3176 org-ref-default-citation-link)
3178 (s-join "," keys))))))
3179 ;; return empty string for helm
3182 (setq helm-bibtex-format-citation-functions
3183 '((org-mode . helm-bibtex-format-org-ref)))
3186 (defun org-ref-helm-insert-cite-link (arg)
3187 "org-ref function to use helm-bibtex to insert a citation link.
3188 With one prefix arg, insert a ref link.
3189 With two prefix args, insert a label link."
3193 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3196 (org-ref-helm-insert-ref-link))
3198 (org-ref-helm-insert-label-link))))
3201 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3202 (setq helm-bibtex-fallback-options
3203 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3205 (setq helm-bibtex-fallback-options
3208 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3209 helm-bibtex-fallback-options))
3211 (setq helm-bibtex-fallback-options
3212 (-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))
3214 (defun org-ref-get-citation-string-at-point ()
3215 "Get a string of a formatted citation."
3216 (let* ((results (org-ref-get-bibtex-key-and-file))
3218 (bibfile (cdr results)))
3222 (insert-file-contents bibfile)
3223 (bibtex-search-entry key)
3224 (org-ref-bib-citation)))
3225 "!!! No entry found !!!" )))
3228 (defun org-ref-cite-candidates ()
3229 "Generate the list of possible candidates for click actions on a cite link.
3230 Checks for pdf and doi, and add appropriate functions."
3231 (let* ((results (org-ref-get-bibtex-key-and-file))
3233 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3234 (bibfile (cdr results))
3235 (url (save-excursion
3237 (insert-file-contents bibfile)
3238 (bibtex-search-entry key)
3239 (bibtex-autokey-get-field "url"))))
3240 (doi (save-excursion
3242 (insert-file-contents bibfile)
3243 (bibtex-search-entry key)
3244 ;; I like this better than bibtex-url which does not always find
3246 (bibtex-autokey-get-field "doi"))))
3247 (candidates `(("Quit" . org-ref-citation-at-point)
3248 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3249 ;; for some reason, when there is no doi or url, they are returned as "". I
3250 ;; prefer nil so we correct this here.
3251 (when (string= doi "") (setq doi nil))
3252 (when (string= url "") (setq url nil))
3254 ;; Conditional pdf functions
3255 (if (file-exists-p pdf-file)
3258 '("Open pdf" . org-ref-open-pdf-at-point)
3262 '("Try to get pdf" . (lambda ()
3263 (save-window-excursion
3264 (org-ref-open-citation-at-point)
3265 (bibtex-beginning-of-entry)
3266 (doi-utils-get-bibtex-entry-pdf))))
3272 '("Open notes" . org-ref-open-notes-at-point)
3275 ;; conditional url and doi functions
3279 '("Open in browser" . org-ref-open-url-at-point)
3284 (add-to-list 'candidates x t))
3285 `(("WOS" . org-ref-wos-at-point)
3286 ("Related articles in WOS" . org-ref-wos-related-at-point)
3287 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3288 ("Google Scholar" . org-ref-google-scholar-at-point)
3289 ("Pubmed" . org-ref-pubmed-at-point)
3290 ("Crossref" . org-ref-crossref-at-point)
3295 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3300 '("Copy key to clipboard" . (lambda ()
3302 (car (org-ref-get-bibtex-key-and-file)))))
3307 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3312 '("Email bibtex entry and pdf" . (lambda ()
3314 (org-ref-open-citation-at-point)
3315 (email-bibtex-entry))))
3317 ;; finally return a numbered list of the candidates
3319 for cell in candidates
3320 collect (cons (format "%2s. %s" i (car cell))
3324 (defvar org-ref-helm-user-candidates '()
3325 "List of user-defined candidates to act when clicking on a cite link.
3326 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.")
3328 ;; example of adding your own function
3330 'org-ref-helm-user-candidates
3331 '("Example" . (lambda () (message-box "You did it!")))
3335 (defun org-ref-cite-click-helm (key)
3336 "Open helm for actions on a cite link.
3339 1. get name and candidates before entering helm because we need
3342 2. switch back to the org buffer before evaluating the
3343 action. most of them need the point and buffer.
3345 KEY is returned for the selected item(s) in helm."
3347 (let ((name (org-ref-get-citation-string-at-point))
3348 (candidates (org-ref-cite-candidates))
3349 (cb (current-buffer)))
3351 (helm :sources `(((name . ,name)
3352 (candidates . ,candidates)
3353 (action . (lambda (f)
3354 (switch-to-buffer cb)
3356 ((name . "User functions")
3357 (candidates . ,org-ref-helm-user-candidates)
3358 (action . (lambda (f)
3359 (switch-to-buffer cb)
3363 ;; * Hydra menus in org-ref
3365 (when (featurep 'hydra)
3367 (setq hydra-is-helpful t)
3369 (defhydra org-ref-cite-hydra (:color blue)
3371 _p_: Open pdf _w_: WOS _g_: Google Scholar _K_: Copy citation to clipboard
3372 _u_: Open url _r_: WOS related _P_: Pubmed _k_: Copy key to clipboard
3373 _n_: Open notes _c_: WOS citing _C_: Crossref _f_: Copy bibtex entry to file
3374 _o_: Open entry _e_: Email entry and pdf
3376 ("o" org-ref-open-citation-at-point nil)
3377 ("p" org-ref-open-pdf-at-point nil)
3378 ("n" org-ref-open-notes-at-point nil)
3379 ("u" org-ref-open-url-at-point nil)
3380 ("w" org-ref-wos-at-point nil)
3381 ("r" org-ref-wos-related-at-point nil)
3382 ("c" org-ref-wos-citing-at-point nil)
3383 ("g" org-ref-google-scholar-at-point nil)
3384 ("P" org-ref-pubmed-at-point nil)
3385 ("C" org-ref-crossref-at-point nil)
3386 ("K" org-ref-copy-entry-as-summary nil)
3389 (car (org-ref-get-bibtex-key-and-file)))) nil)
3390 ("f" org-ref-copy-entry-at-point-to-file nil)
3392 ("e" (save-excursion
3393 (org-ref-open-citation-at-point)
3394 (email-bibtex-entry)) nil)))
3397 (defun org-ref-help ()
3398 "Open the org-ref manual."
3400 (find-file (expand-file-name
3402 (file-name-directory
3403 (find-library-name "org-ref")))))
3406 (defun org-ref-org-menu ()
3407 "Add org-ref menu to the Org menu."
3411 '( ["Insert citation" org-ref-helm-insert-cite-link]
3412 ["Insert ref" org-ref-helm-insert-ref-link]
3413 ["Insert label" org-ref-helm-insert-label-link]
3415 ["List of figures" org-ref-list-of-figures]
3416 ["List of tables" org-ref-list-of-tables]
3417 ["Extract bibtex entries" org-ref-extract-bibtex-entries]
3418 ["Check org-file" org-ref]
3420 ["Help" org-ref-help]
3421 ["Customize org-ref" (customize-group 'org-ref)])
3424 (easy-menu-change '("Org") "--" nil "Show/Hide"))
3426 (add-hook 'org-mode-hook 'org-ref-org-menu)
3431 ;;; org-ref.el ends here