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)
44 (require 'org-element)
48 "Customization group for org-ref.")
50 (defcustom org-ref-bibliography-notes
52 "Filename where you will put all your notes about an entry in the default bibliography."
56 (defcustom org-ref-default-bibliography
58 "List of bibtex files to search for.
59 You should use full-paths for each file."
60 :type '(repeat :tag "List of bibtex files" file)
63 (defcustom org-ref-pdf-directory
65 "Directory where pdfs are stored by key. put a trailing / in."
69 (defcustom org-ref-default-citation-link
71 "The default type of citation link to use."
75 (defcustom org-ref-insert-cite-key
77 "Keyboard shortcut to insert a citation."
81 (defcustom org-ref-bibliography-entry-format
82 '(("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>.")
84 ("book" . "%a, %t, %u (%y).")
85 ("techreport" . "%a, %t, %i, %u (%y).")
86 ("proceedings" . "%e, %t in %S, %u (%y).")
87 ("inproceedings" . "%a, %t, %p, in %b, edited by %e, %u (%y)"))
88 "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."
92 (defcustom org-ref-open-notes-function
98 ;;(org-tree-to-indirect-buffer)
99 (outline-previous-visible-heading 1)
100 (recenter-top-bottom 0))
101 "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."
106 (defcustom org-ref-open-pdf-function
107 'org-ref-open-pdf-at-point
108 "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'."
113 (defcustom org-ref-insert-cite-function
114 'org-ref-helm-insert-cite-link
115 "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."
120 (defcustom org-ref-cite-onclick-function
121 'org-ref-cite-click-helm
122 "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'."
127 (defcustom org-ref-show-citation-on-enter t
128 "If non-nil add a hook function to show the citation summary in the minibuffer."
131 (defcustom org-ref-cite-types
132 '("cite" "nocite" ;; the default latex cite commands
133 ;; natbib cite commands, http://ctan.unixbrain.com/macros/latex/contrib/natbib/natnotes.pdf
134 "citet" "citet*" "citep" "citep*"
135 "citealt" "citealt*" "citealp" "citealp*"
137 "citeauthor" "citeauthor*"
138 "citeyear" "citeyear*"
139 "Citet" "Citep" "Citealt" "Citealp" "Citeauthor"
141 ;; http://ctan.mirrorcatalogs.com/macros/latex/contrib/biblatex/doc/biblatex.pdf
143 "parencite" "Parencite"
144 "footcite" "footcitetext"
145 "textcite" "Textcite"
146 "smartcite" "Smartcite"
147 "cite*" "parencite*" "supercite"
148 "autocite" "Autocite" "autocite*" "Autocite*"
150 "citetitle" "citetitle*"
151 "citedate" "citedate*"
153 "fullcite" "footfullcite"
154 ;; "volcite" "Volcite" cannot support the syntax
155 "notecite" "Notecite"
156 "pnotecite" "Pnotecite"
158 ;; multicites. Very limited support for these.
159 "cites" "Cites" "parencites" "Parencites"
160 "footcites" "footcitetexts"
161 "smartcites" "Smartcites" "textcites" "Textcites"
162 "supercites" "autocites" "Autocites"
163 ;; for the bibentry package
166 "List of citation types known in `org-ref'."
167 :type '(repeat :tag "List of citation types" string)
170 (defcustom org-ref-clean-bibtex-entry-hook nil
171 "Hook that is run in `org-ref-clean-bibtex-entry'. The functions should take no arguments, and operate on the bibtex entry at point."
175 (defvar org-ref-bibliography-files
177 "Variable to hold bibliography files to be searched.")
179 ;; * org-mode / reftex setup
181 (defun org-mode-reftex-setup ()
182 "Setup `org-mode' and reftex for org-ref."
183 (and (buffer-file-name)
184 (file-exists-p (buffer-file-name))
185 (global-auto-revert-mode t))
186 (make-local-variable 'reftex-cite-format)
187 (setq reftex-cite-format 'org))
189 ;; define key for inserting citations
190 (define-key org-mode-map
191 (kbd org-ref-insert-cite-key)
192 org-ref-insert-cite-function)
194 (add-hook 'org-mode-hook 'org-mode-reftex-setup)
196 (eval-after-load 'reftex-vars
198 (add-to-list 'reftex-cite-format-builtin
199 '(org "Org-mode citation"
200 ((?\C-m . "cite:%l") ; default
201 (?d . ",%l") ; for appending
207 (?h . "citeauthor:%l")
208 (?H . "citeauthor*:%l")
214 ;; * Messages for link at cursor
215 (defvar org-ref-message-timer nil
216 "Variable to store the link message timer in.")
219 (defun org-ref-show-link-messages ()
220 "Turn on link messages.
221 You will see a message in the minibuffer when on a cite, ref or label link."
223 (or org-ref-message-timer
224 (setq org-ref-message-timer
225 (run-with-idle-timer 0.5 t 'org-ref-link-message))))
228 (defun org-ref-cancel-link-messages ()
229 "Stop showing messages in minibuffer when on a link."
231 (cancel-timer org-ref-message-timer)
232 (setq org-ref-message-timer nil))
235 (when org-ref-show-citation-on-enter
236 (org-ref-show-link-messages))
238 ;; ** Messages for context under mouse pointer
240 (defvar org-ref-last-mouse-pos nil
241 "Stores last mouse position for use in `org-ref-mouse-message'.")
243 (defun org-ref-can-move-p ()
244 "See if a character is under the mouse. If so return the position for `goto-char'."
245 (let* ((line (cddr org-ref-last-mouse-pos))
246 (col (cadr org-ref-last-mouse-pos)))
248 (goto-char (window-start))
251 (> (- (line-end-position) (line-beginning-position)) col)
252 (progn (forward-char col) (point))
256 (defun org-ref-mouse-message ()
257 "Display message for link under mouse cursor."
259 (when (not (equal (mouse-position) org-ref-last-mouse-pos))
260 (setq org-ref-last-mouse-pos (mouse-position))
261 (let ((p (org-ref-can-move-p)))
265 (org-ref-link-message))))))
268 (defvar org-ref-message-timer-mouse nil
269 "Store mouse timer.")
272 (defvar org-ref-mouse-message-interval 0.5
273 "How often to run the mouse message timer in seconds.")
276 (defun org-ref-mouse-messages-on ()
277 "Turn on mouse messages."
279 (or org-ref-message-timer-mouse
280 (setq org-ref-message-timer-mouse
281 (run-at-time "0.5 sec"
282 org-ref-mouse-message-interval
283 'org-ref-mouse-message))))
286 (defun org-ref-mouse-messages-off ()
287 "Turn off mouse messages."
289 (cancel-timer org-ref-message-timer-mouse)
290 (setq org-ref-message-timer-mouse nil)
291 (message "Mouse messages are off"))
293 ;; Colorizing org-ref links
294 (defcustom org-ref-colorize-links
296 "When non-nil, change colors of links."
300 (defcustom org-ref-cite-color
302 "Color of cite like links."
306 (defcustom org-ref-ref-color
308 "Color of ref like links."
312 (defcustom org-ref-label-color
314 "Color of label links."
318 (defvar org-ref-cite-re nil
319 "Regexp for cite links.")
322 (setq org-ref-cite-re
323 (concat "\\(" (mapconcat
325 (replace-regexp-in-string "\*" "\\\\*" x)
327 org-ref-cite-types "\\|") "\\)"
328 ":\\([a-zA-Z0-9-_:\\./]*,?\\)*"))
331 (defvar org-ref-label-re
332 "label:\\([a-zA-Z0-9-_:]*,?\\)*")
335 (defvar org-ref-ref-re
336 "\\(eq\\)?ref:\\([a-zA-Z0-9-_:]*,?\\)*")
339 (defface org-ref-cite-face
340 `((t (:inherit org-link :foreground ,org-ref-cite-color)))
341 "Color for cite-like links in org-ref.")
344 (defface org-ref-label-face
345 `((t (:inherit org-link :foreground ,org-ref-label-color)))
346 "Color for ref links in org-ref.")
349 (defface org-ref-ref-face
350 `((t (:inherit org-link :foreground ,org-ref-ref-color)))
351 "Face for ref links in org-ref.")
354 (defun org-ref-colorize-links ()
355 "Colorize org-ref links."
357 (highlight-regexp org-ref-cite-re 'org-ref-cite-face)
358 (highlight-regexp org-ref-label-re 'org-ref-label-face)
359 (highlight-regexp org-ref-ref-re 'org-ref-ref-face))
362 (when org-ref-colorize-links
363 (add-hook 'org-mode-hook 'org-ref-colorize-links))
365 ;; * General org-ref utilities
366 (defun org-ref-strip-string (string)
367 "Strip leading and trailing whitespace from the STRING."
368 (replace-regexp-in-string
369 (concat search-whitespace-regexp "$" ) ""
370 (replace-regexp-in-string
371 (concat "^" search-whitespace-regexp ) "" string)))
373 (defun org-ref-split-and-strip-string (string)
374 "Split key-string and strip keys in STRING.
375 Assumes the key-string is comma delimited."
376 (mapcar 'org-ref-strip-string (split-string string ",")))
378 (defun org-ref-reftex-get-bib-field (field entry &optional format)
379 "Similar to reftex-get-bib-field, but removes enclosing braces and quotes in FIELD in the bibtex ENTRY.
380 Optional argument FORMAT bibtex format."
382 (setq result (reftex-get-bib-field field entry format))
383 (when (and (not (string= result "")) (string= "{" (substring result 0 1)))
384 (setq result (substring result 1 -1)))
385 (when (and (not (string= result "")) (string= "\"" (substring result 0 1)))
386 (setq result (substring result 1 -1)))
389 (defun org-ref-reftex-format-citation (entry format)
390 "Return a formatted string for the bibtex ENTRY (from bibtex-parse-entry) according to the FORMAT argument.
391 The format is a string with these percent escapes.
393 In the format, the following percent escapes will be expanded.
395 %l The BibTeX label of the citation.
396 %a List of author names, see also `reftex-cite-punctuation'.
397 %2a Like %a, but abbreviate more than 2 authors like Jones et al.
398 %A First author name only.
399 %e Works like %a, but on list of editor names. (%2e and %E work a well)
401 It is also possible to access all other BibTeX database fields:
402 %b booktitle %c chapter %d edition %h howpublished
403 %i institution %j journal %k key %m month
404 %n number %o organization %p pages %P first page
405 %r address %s school %u publisher %t title
407 %B booktitle, abbreviated %T title, abbreviated
412 Usually, only %l is needed. The other stuff is mainly for the echo area
413 display, and for (setq reftex-comment-citations t).
415 %< as a special operator kills punctuation and space around it after the
416 string has been formatted.
418 A pair of square brackets indicates an optional argument, and RefTeX
419 will prompt for the values of these arguments.
421 Beware that all this only works with BibTeX database files. When
422 citations are made from the \bibitems in an explicit thebibliography
423 environment, only %l is available."
424 ;; Format a citation from the info in the BibTeX ENTRY
425 (unless (stringp format) (setq format "\\cite{%l}"))
427 (if (and reftex-comment-citations
428 (string-match "%l" reftex-cite-comment-format))
429 (error "Reftex-cite-comment-format contains invalid %%l"))
432 "\\(\\`\\|[^%]\\)\\(\\(%\\([0-9]*\\)\\([a-zA-Z]\\)\\)[.,;: ]*\\)"
434 (let ((n (string-to-number (match-string 4 format)))
435 (l (string-to-char (match-string 5 format)))
441 (org-ref-reftex-get-bib-field "&key" entry)
442 (if reftex-comment-citations
443 reftex-cite-comment-format
445 ((= l ?a) (reftex-format-names
446 (reftex-get-bib-names "author" entry)
448 ((= l ?A) (car (reftex-get-bib-names "author" entry)))
449 ((= l ?b) (org-ref-reftex-get-bib-field "booktitle" entry "in: %s"))
450 ((= l ?B) (reftex-abbreviate-title
451 (org-ref-reftex-get-bib-field "booktitle" entry "in: %s")))
452 ((= l ?c) (org-ref-reftex-get-bib-field "chapter" entry))
453 ((= l ?d) (org-ref-reftex-get-bib-field "edition" entry))
454 ((= l ?D) (org-ref-reftex-get-bib-field "doi" entry))
455 ((= l ?e) (reftex-format-names
456 (reftex-get-bib-names "editor" entry)
458 ((= l ?E) (car (reftex-get-bib-names "editor" entry)))
459 ((= l ?h) (org-ref-reftex-get-bib-field "howpublished" entry))
460 ((= l ?i) (org-ref-reftex-get-bib-field "institution" entry))
461 ((= l ?j) (let ((jt (reftex-get-bib-field "journal" entry)))
463 (reftex-get-bib-field "journaltitle" entry)
465 ((= l ?k) (org-ref-reftex-get-bib-field "=key=" entry))
466 ((= l ?m) (org-ref-reftex-get-bib-field "month" entry))
467 ((= l ?n) (org-ref-reftex-get-bib-field "number" entry))
468 ((= l ?o) (org-ref-reftex-get-bib-field "organization" entry))
469 ((= l ?p) (org-ref-reftex-get-bib-field "pages" entry))
470 ((= l ?P) (car (split-string
471 (org-ref-reftex-get-bib-field "pages" entry)
473 ((= l ?s) (org-ref-reftex-get-bib-field "school" entry))
474 ((= l ?S) (org-ref-reftex-get-bib-field "series" entry))
475 ((= l ?u) (org-ref-reftex-get-bib-field "publisher" entry))
476 ((= l ?U) (org-ref-reftex-get-bib-field "url" entry))
477 ((= l ?r) (org-ref-reftex-get-bib-field "address" entry))
478 ;; strip enclosing brackets from title if they are there
479 ((= l ?t) (org-ref-reftex-get-bib-field "title" entry))
480 ((= l ?T) (reftex-abbreviate-title
481 (org-ref-reftex-get-bib-field "title" entry)))
482 ((= l ?v) (org-ref-reftex-get-bib-field "volume" entry))
483 ((= l ?y) (org-ref-reftex-get-bib-field "year" entry)))))
486 (setq b (match-beginning 2) e (match-end 2))
487 (setq b (match-beginning 3) e (match-end 3)))
488 (setq format (concat (substring format 0 b) rpl (substring format e)))))
489 (while (string-match "%%" format)
490 (setq format (replace-match "%" t t format)))
491 (while (string-match "[ ,.;:]*%<" format)
492 (setq format (replace-match "" t t format)))
493 ;; also replace carriage returns, tabs, and multiple whitespaces
494 (setq format (replace-regexp-in-string "\n\\|\t\\|\s+" " " format))
497 (defun org-ref-get-bibtex-entry-citation (key)
498 "Return a string for the bibliography entry corresponding to KEY.
499 Format according to the type in `org-ref-bibliography-entry-format'."
501 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
502 (file) (entry) (bibtex-entry) (entry-type) (format))
504 (setq file (catch 'result
505 (cl-loop for file in org-ref-bibliography-files do
506 (if (org-ref-key-in-file-p key (file-truename file))
508 (message "%s not found in %s"
509 key (file-truename file))))))
512 (insert-file-contents file)
513 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
514 (bibtex-search-entry key nil 0)
515 (setq bibtex-entry (bibtex-parse-entry))
516 ;; downcase field names so they work in the format-citation code
517 (dolist (cons-cell bibtex-entry)
518 (setf (car cons-cell) (downcase (car cons-cell))))
519 (setq entry-type (downcase (cdr (assoc "=type=" bibtex-entry))))
520 (setq format (cdr (assoc entry-type org-ref-bibliography-entry-format)))
522 (setq entry (org-ref-reftex-format-citation bibtex-entry format))
523 ;; if no format, we use the bibtex entry itself as a fallback
525 (bibtex-narrow-to-entry)
526 (setq entry (buffer-string)))))
529 (defun org-ref-get-bibtex-keys ()
530 "Return a list of unique keys in the buffer."
532 (org-element-map (org-element-parse-buffer) 'link
534 (let ((plist (nth 1 link)))
535 (when (-contains? org-ref-cite-types (plist-get plist ':type))
538 (org-ref-split-and-strip-string (plist-get plist ':path)))
539 (when (not (-contains? keys key))
540 (setq keys (append keys (list key))))))))
541 ;; set with-affiliated to get keys in captions
543 ;; Sort keys alphabetically
544 (setq keys (cl-sort keys 'string-lessp :key 'downcase))
547 (defun org-ref-get-bibtex-entry-html (key)
548 "Return an html string for the bibliography entry corresponding to KEY."
550 (setq output (org-ref-get-bibtex-entry-citation key))
552 (setq output (replace-regexp-in-string "\\\\&" "&" output))
553 ;; hack to replace {} around text
554 (setq output (replace-regexp-in-string "{" "" output))
555 (setq output (replace-regexp-in-string "}" "" output))
556 ;; get rid of empty parens
557 (setq output (replace-regexp-in-string "()" "" output))
558 ;; get rid of empty link and doi
559 (setq output (replace-regexp-in-string " <a href=\"\">link</a>\\." "" output))
560 ;; change double dash to single dash
561 (setq output (replace-regexp-in-string "--" "-" output))
562 (setq output (replace-regexp-in-string " <a href=\"http://dx\\.doi\\.org/\">doi</a>\\." "" output))
563 (format "<li><a id=\"%s\">[%s] %s</a></li>"
566 (defun org-ref-get-html-bibliography ()
567 "Create an html bibliography when there are keys."
568 (let ((keys (org-ref-get-bibtex-keys)))
570 (concat "<h1>Bibliography</h1>
572 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-html x)) keys "\n")
575 (defun org-ref-get-bibtex-entry-org (key)
576 "Return an org string for the bibliography entry corresponding to KEY."
577 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
578 (file) (entry) (bibtex-entry) (entry-type) (format))
580 (setq file (catch 'result
581 (cl-loop for file in org-ref-bibliography-files do
582 (if (org-ref-key-in-file-p key (file-truename file))
584 (message "%s not found in %s" key (file-truename file))))))
587 (insert-file-contents file)
588 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
589 (bibtex-search-entry key nil 0)
590 (setq entry (bibtex-parse-entry))
595 " (org-ref-reftex-get-bib-field "author" entry)
596 (org-ref-reftex-get-bib-field "title" entry)
597 (concat " :CUSTOM_ID: " (org-ref-reftex-get-bib-field "=key=" entry) "\n"
598 (mapconcat (lambda (element) (format " :%s: %s"
599 (upcase (car element))
604 (defun org-ref-get-org-bibliography ()
605 "Create an org bibliography when there are keys."
606 (let ((keys (org-ref-get-bibtex-keys)))
608 (concat "* Bibliography
610 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-org x)) keys "\n")
613 (defun org-ref-get-bibtex-entry-ascii (key)
614 "Return an ascii string for the bibliography entry corresponding to KEY."
616 (format "[%s] %s" key (org-ref-get-bibtex-entry-citation key)))
618 (defun org-ref-get-ascii-bibliography ()
619 "Create an html bibliography when there are keys."
620 (let ((keys (org-ref-get-bibtex-keys)))
626 (mapconcat (lambda (x) (org-ref-get-bibtex-entry-ascii x)) keys "\n")
630 ;; ** bibliography and bibliographystyle
631 (org-add-link-type "bibliography"
632 ;; this code is run on clicking. The bibliography
633 ;; may contain multiple files. this code finds the
634 ;; one you clicked on and opens it.
635 (lambda (link-string)
636 ;; get link-string boundaries we have to go to the
637 ;; beginning of the line, and then search forward
639 ;; object is the link you clicked on
640 (object (org-element-context))
641 (link-string-beginning)
645 (goto-char (org-element-property :begin object))
646 (search-forward link-string nil nil 1)
647 (setq link-string-beginning (match-beginning 0))
648 (setq link-string-end (match-end 0)))
650 ;; Make sure point is in the link-path.
651 (if (< cp link-string-beginning)
652 (goto-char link-string-beginning))
653 ;; We set the reftex-default-bibliography
654 ;; here. it should be a local variable only in
655 ;; the current buffer. We need this for using
656 ;; reftex to do citations.
657 (set (make-local-variable 'reftex-default-bibliography)
659 (org-element-property :path object) ","))
661 (let (key-beginning key-end)
662 ;; now if we have comma separated bibliographies
663 ;; we find the one clicked on. we want to
664 ;; search forward to next comma from point
666 (if (search-forward "," link-string-end 1 1)
668 (setq key-end (- (match-end 0) 1))
669 ;; no comma found so take the point
670 (setq key-end (point))))
671 ;; and backward to previous comma from point
673 (if (search-backward "," link-string-beginning 1 1)
675 (setq key-beginning (+ (match-beginning 0) 1))
676 (setq key-beginning (point)))) ; no match found
677 ;; save the key we clicked on.
678 (setq bibfile (org-ref-strip-string
679 (buffer-substring key-beginning key-end)))
680 ;; open file on click
681 (find-file bibfile))))
684 (lambda (keyword desc format)
686 ((eq format 'org) (org-ref-get-org-bibliography))
687 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
688 ((eq format 'html) (org-ref-get-html-bibliography))
690 ;; write out the latex bibliography command
691 (format "\\bibliography{%s}"
692 (replace-regexp-in-string
696 (mapcar 'expand-file-name
697 (split-string keyword ","))
700 (org-add-link-type "nobibliography"
701 ;; this code is run on clicking. The bibliography
702 ;; may contain multiple files. this code finds the
703 ;; one you clicked on and opens it.
704 (lambda (link-string)
705 ;; get link-string boundaries
706 ;; we have to go to the beginning of the line, and then search forward
709 ;; object is the link you clicked on
710 (object (org-element-context))
712 (link-string-beginning)
716 (goto-char (org-element-property :begin object))
717 (search-forward link-string nil nil 1)
718 (setq link-string-beginning (match-beginning 0))
719 (setq link-string-end (match-end 0)))
721 ;; We set the reftex-default-bibliography
722 ;; here. it should be a local variable only in
723 ;; the current buffer. We need this for using
724 ;; reftex to do citations.
725 (set (make-local-variable 'reftex-default-bibliography)
726 (split-string (org-element-property :path object) ","))
728 (let (key-beginning key-end)
729 ;; now if we have comma separated bibliographies
730 ;; we find the one clicked on. we want to
731 ;; search forward to next comma from point
733 (if (search-forward "," link-string-end 1 1)
734 (setq key-end (- (match-end 0) 1)) ; we found a match
735 (setq key-end (point)))) ; no comma found so take the point
736 ;; and backward to previous comma from point
738 (if (search-backward "," link-string-beginning 1 1)
739 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
740 (setq key-beginning (point)))) ; no match found
741 ;; save the key we clicked on.
742 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
743 (find-file bibfile)))) ; open file on click
746 (lambda (keyword desc format)
748 ((eq format 'org) (org-ref-get-org-bibliography))
749 ((eq format 'ascii) (org-ref-get-ascii-bibliography))
750 ((eq format 'html) (org-ref-get-html-bibliography))
752 ;; write out the latex bibliography command
753 (format "\\nobibliography{%s}"
754 (replace-regexp-in-string "\\.bib" "" (mapconcat 'identity
755 (mapcar 'expand-file-name
756 (split-string keyword ","))
759 (org-add-link-type "printbibliography"
760 (lambda (arg) (message "Nothing implemented for clicking here."))
761 (lambda (keyword desc format)
763 ((eq format 'org) (org-ref-get-org-bibliography))
764 ((eq format 'html) (org-ref-get-html-bibliography))
766 ;; write out the biblatex bibliography command
767 "\\printbibliography"))))
769 (org-add-link-type "bibliographystyle"
770 (lambda (arg) (message "Nothing implemented for clicking here."))
771 (lambda (keyword desc format)
774 ;; write out the latex bibliography command
775 (format "\\bibliographystyle{%s}" keyword))
776 ;; Other styles should not have an output for this
781 (defun org-bibliographystyle-complete-link (&optional arg)
782 "Completion function for bibliographystyle link.
784 (format "bibliographystyle:%s" (ido-completing-read
786 '("unsrt" "plain" "alpha"
788 ;; https://www.sharelatex.com/learn/Natbib_bibliography_styles
789 "dinat" "humannat" "plainnat"
790 "abbrnat" "unsrtnat" "rusnat"
794 (defun org-bibliography-complete-link (&optional arg)
795 "Completion function for bibliography link.
797 (format "bibliography:%s" (read-file-name "enter file: " nil nil t)))
800 (defun org-ref-insert-bibliography-link ()
801 "Insert a bibliography with completion."
803 (insert (org-bibliography-complete-link)))
807 (org-add-link-type "addbibresource"
808 ;; this code is run on clicking. The addbibresource
809 ;; may contain multiple files. this code finds the
810 ;; one you clicked on and opens it.
811 (lambda (link-string)
812 ;; get link-string boundaries
813 ;; we have to go to the beginning of the line, and then search forward
816 ;; object is the link you clicked on
817 (object (org-element-context))
819 (link-string-beginning)
823 (goto-char (org-element-property :begin object))
824 (search-forward link-string nil nil 1)
825 (setq link-string-beginning (match-beginning 0))
826 (setq link-string-end (match-end 0)))
828 ;; We set the reftex-default-addbibresource
829 ;; here. it should be a local variable only in
830 ;; the current buffer. We need this for using
831 ;; reftex to do citations.
832 (set (make-local-variable 'reftex-default-addbibresource)
833 (split-string (org-element-property :path object) ","))
835 (let (key-beginning key-end)
836 ;; now if we have comma separated bibliographies
837 ;; we find the one clicked on. we want to
838 ;; search forward to next comma from point
840 (if (search-forward "," link-string-end 1 1)
841 (setq key-end (- (match-end 0) 1)) ; we found a match
842 (setq key-end (point)))) ; no comma found so take the point
843 ;; and backward to previous comma from point
845 (if (search-backward "," link-string-beginning 1 1)
846 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
847 (setq key-beginning (point)))) ; no match found
848 ;; save the key we clicked on.
849 (setq bibfile (org-ref-strip-string (buffer-substring key-beginning key-end)))
850 (find-file bibfile)))) ; open file on click
853 (lambda (keyword desc format)
855 ((eq format 'html) (format "")); no output for html
857 ;; write out the latex addbibresource command
858 (format "\\addbibresource{%s}" keyword)))))
860 ;; ** List of figures
861 (defun org-ref-list-of-figures (&optional arg)
862 "Generate buffer with list of figures in them.
865 (save-excursion (widen)
866 (let* ((c-b (buffer-name))
869 (org-element-map (org-element-parse-buffer) 'link
871 "create a link for to the figure"
873 (and (string= (org-element-property :type link) "file")
875 "[^.]*\\.\\(png\\|jpg\\|eps\\|pdf\\)$"
876 (org-element-property :path link)))
879 (let* ((start (org-element-property :begin link))
880 (parent (car (cdr (org-element-property :parent link))))
881 (caption (cl-caaar (plist-get parent :caption)))
882 (name (plist-get parent :name)))
885 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]] %s\n"
886 c-b start counter (or name "") caption)
888 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][figure %s: %s]]\n"
889 c-b start counter (or name "")))))))))
890 (switch-to-buffer "*List of Figures*")
891 (setq buffer-read-only nil)
894 (insert (mapconcat 'identity list-of-figures ""))
895 (setq buffer-read-only t)
896 (use-local-map (copy-keymap org-mode-map))
897 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
901 'org-ref-list-of-figures ; on click
902 (lambda (keyword desc format)
905 (format "\\listoffigures")))))
908 (defun org-ref-list-of-tables (&optional arg)
909 "Generate a buffer with a list of tables.
914 (let* ((c-b (buffer-name))
917 (org-element-map (org-element-parse-buffer 'element) 'table
919 "create a link for to the table"
921 (let ((start (org-element-property :begin table))
922 (name (org-element-property :name table))
923 (caption (cl-caaar (org-element-property :caption table))))
926 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]] %s\n"
927 c-b start counter (or name "") caption)
929 "[[elisp:(progn (switch-to-buffer \"%s\")(widen)(goto-char %s))][table %s: %s]]\n"
930 c-b start counter (or name ""))))))))
931 (switch-to-buffer "*List of Tables*")
932 (setq buffer-read-only nil)
935 (insert (mapconcat 'identity list-of-tables ""))
936 (setq buffer-read-only t)
937 (use-local-map (copy-keymap org-mode-map))
938 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))))
942 'org-ref-list-of-tables
943 (lambda (keyword desc format)
946 (format "\\listoftables")))))
950 (defun org-ref-count-labels (label)
951 "Counts number of matches for LABEL in the document."
952 (+ (count-matches (format "label:%s\\b[^-:]" label) (point-min) (point-max))
953 ;; for tblname, it is not enough to get word boundary
954 ;; tab-little and tab-little-2 match then.
955 (count-matches (format "^#\\+tblname:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
956 (count-matches (format "\\label{%s}" label) (point-min) (point-max))
957 ;; this is the org-format #+label:
958 (count-matches (format "^#\\+label:\\s-*%s\\b[^-:]" label) (point-min) (point-max))
959 (let ((custom-id-count 0))
962 (when (string= label (org-entry-get (point) "CUSTOM_ID"))
963 (setq custom-id-count (+ 1 custom-id-count)))))
969 "on clicking count the number of label tags used in the buffer. A number greater than one means multiple labels!"
970 (let ((count (org-ref-count-labels label)))
971 (message (format "%s occurence%s"
977 (org-ref-count-labels label))))
978 (lambda (keyword desc format)
980 ((eq format 'html) (format "<div id=\"%s\">" keyword))
982 (format "\\label{%s}" keyword)))))
984 (defun org-label-store-link ()
985 "Store a link to a label. The output will be a ref to that label."
986 ;; First we have to make sure we are on a label link.
987 (let* ((object (org-element-context)))
988 (when (and (equal (org-element-type object) 'link)
989 (equal (org-element-property :type object) "label"))
990 (org-store-link-props
992 :link (concat "ref:" (org-element-property :path object))))
994 ;; Store link on table
995 (when (equal (org-element-type object) 'table)
996 (org-store-link-props
998 :link (concat "ref:" (org-element-property :name object))))
1000 ;; store link on heading with custom_id
1001 ;; this is not a ref link, but it is still what you want
1002 (when (and (equal (org-element-type object) 'headline)
1003 (org-entry-get (point) "CUSTOM_ID"))
1004 (org-store-link-props
1006 :link (format "[[#%s]]" (org-entry-get (point) "CUSTOM_ID"))))
1008 ;; and to #+label: lines
1010 (when (and (equal (org-element-type object) 'paragraph)
1011 (org-element-property :name object))
1012 (org-store-link-props
1014 :link (concat "ref:" (org-element-property :name object))))))
1016 (add-hook 'org-store-link-functions 'org-label-store-link)
1022 "on clicking goto the label. Navigate back with C-c &"
1023 (org-mark-ring-push)
1024 ;; next search from beginning of the buffer
1025 ;; it is possible you would not find the label if narrowing is in effect
1031 (goto-char (point-min))
1032 (re-search-forward (format "label:%s\\b" label) nil t))
1036 (goto-char (point-min))
1037 (re-search-forward (format "\\label{%s}" label) nil t))
1039 ;; #+label: name org-definition
1041 (goto-char (point-min))
1043 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1047 (goto-char (point-min))
1049 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1051 ;; we did not find anything, so go back to where we came
1052 (org-mark-ring-goto)
1053 (error "%s not found" label))
1055 (message "go back with (org-mark-ring-goto) `C-c &`"))
1057 (lambda (keyword desc format)
1059 ((eq format 'html) (format "<a href=\"#%s\">%s</a>" keyword keyword))
1061 (format "\\ref{%s}" keyword)))))
1064 (defun org-ref-get-org-labels ()
1065 "Return a list of #+LABEL: labels."
1067 (goto-char (point-min))
1068 (let ((matches '()))
1069 (while (re-search-forward "^#\\+label:\\s-+\\(.*\\)\\b" (point-max) t)
1070 ;; do not do this for tables. We get those in `org-ref-get-tblnames'.
1071 ;; who would have thought you have save match data here? Trust me. When
1072 ;; I wrote this, you did.
1073 (unless (save-match-data (equal (car (org-element-at-point)) 'table))
1074 (add-to-list 'matches (match-string-no-properties 1) t)))
1078 (defun org-ref-get-custom-ids ()
1079 "Return a list of custom_id properties in the buffer."
1080 (let ((results '()) custom_id)
1083 (let ((custom_id (org-entry-get (point) "CUSTOM_ID")))
1084 (when (not (null custom_id))
1085 (setq results (append results (list custom_id)))))))
1089 (defun org-ref-get-latex-labels ()
1090 "Return list of matchin LaTeX defined labels in buffer."
1092 (goto-char (point-min))
1093 (let ((matches '()))
1094 (while (re-search-forward "\\\\label{\\([a-zA-z0-9:-]*\\)}" (point-max) t)
1095 (add-to-list 'matches (match-string-no-properties 1) t))
1099 (defun org-ref-get-tblnames ()
1100 "Return list of table names in the buffer."
1101 (org-element-map (org-element-parse-buffer 'element) 'table
1103 (org-element-property :name table))))
1106 (defun org-ref-get-labels ()
1107 "Return a list of labels in the buffer that you can make a ref link to.
1108 This is used to complete ref links and in helm menus."
1112 (goto-char (point-min))
1113 (let ((matches '()))
1114 ;; these are the org-ref label:stuff kinds
1115 (while (re-search-forward
1116 "[^#+]label:\\([a-zA-z0-9:-]*\\)" (point-max) t)
1117 (add-to-list 'matches (match-string-no-properties 1) t))
1118 ;; now add all the other kinds of labels.
1121 (org-ref-get-org-labels)
1123 (org-ref-get-latex-labels)
1124 ;; #+tblname: and actually #+label
1125 (org-ref-get-tblnames)
1127 (org-ref-get-custom-ids))))))
1130 (defun org-ref-helm-insert-label-link ()
1131 "Insert a label link. helm just shows you what labels already exist.
1132 If you are on a label link, replace it."
1134 (let* ((labels (org-ref-get-labels))
1135 (cb (current-buffer)))
1136 (helm :sources `(((name . "Existing labels")
1137 (candidates . ,labels)
1138 ;; default action is to open to the label
1139 (action . (lambda (label)
1140 ;; unfortunately I do not have markers here
1141 (org-open-link-from-string
1142 (format "ref:%s" label))))
1143 ;; if you select a label, replace current one
1144 (action . (lambda (label)
1145 (switch-to-buffer ,cb)
1147 ;; no prefix or on a link
1148 ((equal helm-current-prefix-arg nil)
1149 (let* ((object (org-element-context))
1150 (last-char (save-excursion
1151 (goto-char (org-element-property :end object))
1153 (if (looking-at " ")
1156 (when (-contains? '("label")
1157 (org-element-property :type object))
1158 ;; we are on a link, so replace it.
1161 (org-element-property :begin object)
1162 (org-element-property :end object))
1164 (replace-regexp-in-string
1165 (org-element-property :path object)
1167 (org-element-property :raw-link object))
1169 ;; no prefix options defined
1171 ;; no matching selection creates a new label
1172 ((name . "Create new label")
1174 ;; default action creates a new label, or replaces old one
1175 (action . (lambda (label)
1176 (switch-to-buffer ,cb)
1177 (let* ((object (org-element-context))
1178 (last-char (save-excursion
1179 (goto-char (org-element-property :end object))
1181 (if (looking-at " ")
1184 (if (-contains? '("label")
1185 (org-element-property :type object))
1186 ;; we are on a link, so replace it.
1189 (org-element-property :begin object)
1190 (org-element-property :end object))
1192 (replace-regexp-in-string
1193 (org-element-property :path object)
1195 (org-element-property :raw-link object))
1202 helm-pattern))))))))))))
1205 (defun org-ref-complete-link (&optional arg)
1206 "Completion function for ref links.
1207 Optional argument ARG Does nothing."
1209 (setq label (completing-read "label: " (org-ref-get-labels)))
1210 (format "ref:%s" label)))
1213 (defun org-ref-insert-ref-link ()
1214 "Completion function for a ref link."
1216 (insert (org-ref-complete-link)))
1219 (defun org-ref-helm-insert-ref-link ()
1220 "Helm menu to insert ref links to labels in the document.
1221 If you are on link, replace with newly selected label.
1222 Use C-u to insert a different kind of ref link.
1223 Use C-u C-u to insert a [[#custom-id]] link"
1225 (let* ((labels (org-ref-get-labels))
1226 (bs (buffer-string))
1227 (contexts (with-temp-buffer
1229 (mapcar 'org-ref-get-label-context labels)))
1230 (cb (current-buffer)))
1232 (helm :input (thing-at-point 'word)
1233 :sources `(((name . "Available labels to ref")
1234 (candidates . ,(cl-loop for label in labels
1235 for context in contexts
1236 ;; we do some kludgy adding spaces
1237 ;; and bars to make it "easier" to
1239 collect (cons (concat
1244 (split-string context "\n")
1247 ;; default action to replace or insert ref link.
1248 (action . (lambda (label)
1249 (switch-to-buffer ,cb)
1252 ;; no prefix or on a link
1253 ((equal helm-current-prefix-arg nil)
1254 (let* ((object (org-element-context))
1255 (last-char (save-excursion
1256 (goto-char (org-element-property :end object))
1258 (if (looking-at " ")
1261 (if (-contains? '("ref" "eqref" "pageref" "nameref")
1262 (org-element-property :type object))
1263 ;; we are on a link, so replace it.
1266 (org-element-property :begin object)
1267 (org-element-property :end object))
1269 (replace-regexp-in-string
1270 (org-element-property :path object)
1272 (org-element-property :raw-link object))
1274 ;; insert a new link
1279 ;; one prefix, alternate ref link
1280 ((equal helm-current-prefix-arg '(4))
1283 (helm :sources '((name . "Ref link types")
1284 (candidates . ("ref" "eqref" "pageref" "nameref"))
1285 (action . (lambda (x) x))))
1287 ;; two prefixes, insert section custom-id link
1288 ((equal helm-current-prefix-arg '(16))
1290 (format "[[#%s]]" label)))
1298 "on clicking goto the label. Navigate back with C-c &"
1299 (org-mark-ring-push)
1300 ;; next search from beginning of the buffer
1306 (goto-char (point-min))
1307 (re-search-forward (format "label:%s\\b" label) nil t))
1311 (goto-char (point-min))
1312 (re-search-forward (format "\\label{%s}" label) nil t))
1314 ;; #+label: name org-definition
1316 (goto-char (point-min))
1318 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1322 (goto-char (point-min))
1324 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)))
1325 ;; we did not find anything, so go back to where we came
1326 (org-mark-ring-goto)
1327 (error "%s not found" label))
1328 (message "go back with (org-mark-ring-goto) `C-c &`"))
1330 (lambda (keyword desc format)
1332 ((eq format 'html) (format "(<pageref>%s</pageref>)" path))
1334 (format "\\pageref{%s}" keyword)))))
1337 (defun org-pageref-complete-link (&optional arg)
1338 "Completion function for ref links.
1339 Optional argument ARG Does nothing."
1341 (setq label (completing-read "label: " (org-ref-get-labels)))
1342 (format "ref:%s" label)))
1345 (defun org-pageref-insert-ref-link ()
1346 "Insert a pageref link with completion."
1348 (insert (org-pageref-complete-link)))
1355 "on clicking goto the label. Navigate back with C-c &"
1356 (org-mark-ring-push)
1357 ;; next search from beginning of the buffer
1363 (goto-char (point-min))
1364 (re-search-forward (format "\\label{%s}" label) nil t))
1366 ;; we did not find anything, so go back to where we came
1367 (org-mark-ring-goto)
1368 (error "%s not found" label))
1369 (message "go back with (org-mark-ring-goto) `C-c &`"))
1371 (lambda (keyword desc format)
1373 ((eq format 'html) (format "(<nameref>%s</nameref>)" path))
1375 (format "\\nameref{%s}" keyword)))))
1382 "on clicking goto the label. Navigate back with C-c &"
1383 (org-mark-ring-push)
1384 ;; next search from beginning of the buffer
1386 (goto-char (point-min))
1389 ;; search forward for the first match
1391 (re-search-forward (format "label:%s" label) nil t)
1393 (re-search-forward (format "\\label{%s}" label) nil t)
1394 ;; #+label: name org-definition
1395 (re-search-forward (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t))
1396 (org-mark-ring-goto)
1397 (error "%s not found" label))
1398 (message "go back with (org-mark-ring-goto) `C-c &`"))
1400 (lambda (keyword desc format)
1402 ((eq format 'html) (format "(<eqref>%s</eqref>)" path))
1404 (format "\\eqref{%s}" keyword)))))
1408 (defun org-ref-get-bibtex-key-under-cursor ()
1409 "Return key under the bibtex cursor.
1410 We search forward from
1411 point to get a comma, or the end of the link, and then backwards
1412 to get a comma, or the beginning of the link. that delimits the
1413 keyword we clicked on. We also strip the text properties."
1414 (let* ((object (org-element-context))
1415 (link-string (org-element-property :path object)))
1416 ;; you may click on the part before the citations. here we make
1417 ;; sure to move to the beginning so you get the first citation.
1419 (goto-char (org-element-property :begin object))
1420 (search-forward link-string (org-element-property :end object))
1421 (goto-char (match-beginning 0))
1422 ;; check if we clicked before the path and move as needed.
1423 (unless (< cp (point))
1426 (if (not (org-element-property :contents-begin object))
1427 ;; this means no description in the link
1429 ;; we need the link path start and end
1430 (let (link-string-beginning link-string-end)
1432 (goto-char (org-element-property :begin object))
1433 (search-forward link-string nil nil 1)
1434 (setq link-string-beginning (match-beginning 0))
1435 (setq link-string-end (match-end 0)))
1437 (let (key-beginning key-end)
1438 ;; The key is the text between commas, or the link boundaries
1440 (if (search-forward "," link-string-end t 1)
1441 (setq key-end (- (match-end 0) 1)) ; we found a match
1442 (setq key-end link-string-end))) ; no comma found so take the end
1443 ;; and backward to previous comma from point which defines the start character
1445 (if (search-backward "," link-string-beginning 1 1)
1446 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
1447 (setq key-beginning link-string-beginning))) ; no match found
1448 ;; save the key we clicked on.
1450 (org-ref-strip-string
1451 (buffer-substring key-beginning key-end))))
1452 (set-text-properties 0 (length bibtex-key) nil bibtex-key)
1454 ;; link with description. assume only one key
1457 (defun org-ref-find-bibliography ()
1458 "Find the bibliography in the buffer.
1459 This function sets and returns cite-bibliography-files, which is a list of files
1460 either from bibliography:f1.bib,f2.bib
1461 \bibliography{f1,f2}
1462 internal bibliographies
1464 falling back to what the user has set in `org-ref-default-bibliography'"
1467 (goto-char (point-min))
1468 ;; look for a bibliography link
1469 (when (re-search-forward "\\<bibliography:\\([^\]\|\n]+\\)" nil t)
1470 (setq org-ref-bibliography-files
1471 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1472 (throw 'result org-ref-bibliography-files))
1475 ;; we did not find a bibliography link. now look for \bibliography
1476 (goto-char (point-min))
1477 (when (re-search-forward "\\\\bibliography{\\([^}]+\\)}" nil t)
1478 ;; split, and add .bib to each file
1479 (setq org-ref-bibliography-files
1480 (mapcar (lambda (x) (concat x ".bib"))
1481 (mapcar 'org-ref-strip-string
1482 (split-string (match-string 1) ","))))
1483 (throw 'result org-ref-bibliography-files))
1485 ;; no bibliography found. maybe we need a biblatex addbibresource
1486 (goto-char (point-min))
1487 ;; look for a bibliography link
1488 (when (re-search-forward "addbibresource:\\([^\]\|\n]+\\)" nil t)
1489 (setq org-ref-bibliography-files
1490 (mapcar 'org-ref-strip-string (split-string (match-string 1) ",")))
1491 (throw 'result org-ref-bibliography-files))
1493 ;; we did not find anything. use defaults
1494 (setq org-ref-bibliography-files org-ref-default-bibliography)))
1496 ;; set reftex-default-bibliography so we can search
1497 (set (make-local-variable 'reftex-default-bibliography) org-ref-bibliography-files)
1498 org-ref-bibliography-files)
1500 (defun org-ref-key-in-file-p (key filename)
1501 "Determine if the KEY is in the FILENAME."
1502 (save-current-buffer
1503 (let ((bibtex-files (list filename)))
1504 ;; This is something I am trying because when the bibtex file is open, and
1505 ;; you have added to it, the only way I find to get the update to update
1506 ;; is to close it and reopen it. or to save it and revert it.
1507 (when (get-file-buffer filename)
1508 (set-buffer (get-file-buffer filename))
1510 (revert-buffer t t))
1511 (bibtex-search-entry key t))))
1513 (defun org-ref-get-bibtex-key-and-file (&optional key)
1514 "Return the bibtex KEY and file that it is in. If no key is provided, get one under point."
1515 (let ((org-ref-bibliography-files (org-ref-find-bibliography))
1518 (setq key (org-ref-get-bibtex-key-under-cursor)))
1519 (setq file (catch 'result
1520 (cl-loop for file in org-ref-bibliography-files do
1521 (if (org-ref-key-in-file-p key (file-truename file))
1522 (throw 'result file)))))
1525 ;; *** key at point functions
1527 (defun org-ref-open-pdf-at-point ()
1528 "Open the pdf for bibtex key under point if it exists."
1530 (let* ((results (org-ref-get-bibtex-key-and-file))
1532 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key)))
1533 (if (file-exists-p pdf-file)
1534 (org-open-file pdf-file)
1535 (message "no pdf found for %s" key))))
1538 (defun org-ref-open-url-at-point ()
1539 "Open the url for bibtex key under point."
1541 (let* ((results (org-ref-get-bibtex-key-and-file))
1543 (bibfile (cdr results)))
1546 (insert-file-contents bibfile)
1547 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1548 (bibtex-search-entry key)
1549 ;; I like this better than bibtex-url which does not always find
1552 (let ((url (bibtex-autokey-get-field "url")))
1554 (browse-url (s-trim url))
1557 (let ((doi (bibtex-autokey-get-field "doi")))
1559 (if (string-match "^http" doi)
1561 (browse-url (format "http://dx.doi.org/%s" (s-trim doi))))
1562 (throw 'done nil))))))))
1565 (defun org-ref-open-notes-at-point ()
1566 "Open the notes for bibtex key under point."
1568 (let* ((results (org-ref-get-bibtex-key-and-file))
1570 (bibfile (cdr results)))
1573 (insert-file-contents bibfile)
1574 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1575 (bibtex-search-entry key)
1576 (org-ref-open-bibtex-notes)))))
1579 (defun org-ref-citation-at-point ()
1580 "Give message of current citation at point."
1582 (let* ((cb (current-buffer))
1583 (results (org-ref-get-bibtex-key-and-file))
1585 (bibfile (cdr results)))
1586 (message "%s" (progn
1588 (insert-file-contents bibfile)
1589 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1590 (bibtex-search-entry key)
1591 (org-ref-bib-citation))))))
1594 (defun org-ref-open-citation-at-point ()
1595 "Open bibtex file to key at point."
1597 (let* ((cb (current-buffer))
1598 (results (org-ref-get-bibtex-key-and-file))
1600 (bibfile (cdr results)))
1602 (bibtex-search-entry key)))
1606 (defvar org-ref-cite-menu-funcs '()
1607 "Functions to run on cite click menu.
1608 Each entry is a list of (key menu-name function).
1609 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.")
1612 (defvar org-ref-user-cite-menu-funcs
1613 '(("C" "rossref" org-ref-crossref-at-point)
1614 ("y" "Copy entry to file" org-ref-copy-entry-at-point-to-file)
1615 ("s" "Copy summary" org-ref-copy-entry-as-summary))
1616 "User-defined functions to run on bibtex key at point.")
1619 (defun org-ref-copy-entry-as-summary ()
1620 "Copy the bibtex entry for the citation at point as a summary."
1622 (save-window-excursion
1623 (org-ref-open-citation-at-point)
1624 (kill-new (org-ref-bib-citation))))
1627 (defun org-ref-copy-entry-at-point-to-file ()
1628 "Copy the bibtex entry for the citation at point to NEW-FILE.
1629 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."
1631 (let ((new-file (ido-completing-read
1633 (append org-ref-default-bibliography
1634 (f-entries "." (lambda (f) (f-ext? f "bib"))))))
1635 (key (org-ref-get-bibtex-key-under-cursor)))
1636 (save-window-excursion
1637 (org-ref-open-citation-at-point)
1638 (bibtex-copy-entry-as-kill))
1640 (let ((bibtex-files (list (file-truename new-file))))
1641 (if (assoc key (bibtex-global-key-alist))
1642 (message "That key already exists in %s" new-file)
1644 (save-window-excursion
1645 (find-file new-file)
1646 (goto-char (point-max))
1647 ;; make sure we are at the beginning of a line.
1648 (unless (looking-at "^") (insert "\n\n"))
1653 (defun org-ref-get-doi-at-point ()
1654 "Get doi for key at point."
1655 (let* ((results (org-ref-get-bibtex-key-and-file))
1657 (bibfile (cdr results))
1661 (insert-file-contents bibfile)
1662 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1663 (bibtex-search-entry key)
1664 (setq doi (bibtex-autokey-get-field "doi"))
1665 ;; in case doi is a url, remove the url part.
1666 (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))))
1669 ;; **** functions that operate on key at point for click menu
1670 (defun org-ref-wos-at-point ()
1671 "Open the doi in wos for bibtex key under point."
1673 (doi-utils-wos (org-ref-get-doi-at-point)))
1676 (defun org-ref-wos-citing-at-point ()
1677 "Open the doi in wos citing articles for bibtex key under point."
1679 (doi-utils-wos-citing (org-ref-get-doi-at-point)))
1682 (defun org-ref-wos-related-at-point ()
1683 "Open the doi in wos related articles for bibtex key under point."
1685 (doi-utils-wos-related (org-ref-get-doi-at-point)))
1688 (defun org-ref-google-scholar-at-point ()
1689 "Open the doi in google scholar for bibtex key under point."
1691 (doi-utils-google-scholar (org-ref-get-doi-at-point)))
1694 (defun org-ref-pubmed-at-point ()
1695 "Open the doi in pubmed for bibtex key under point."
1697 (doi-utils-pubmed (org-ref-get-doi-at-point)))
1700 (defun org-ref-crossref-at-point ()
1701 "Open the doi in crossref for bibtex key under point."
1703 (doi-utils-crossref (org-ref-get-doi-at-point)))
1705 ;; *** Minibuffer menu
1707 (defun org-ref-cite-onclick-minibuffer-menu (&optional link-string)
1708 "Action when a cite link is clicked on.
1709 Provides a menu of context sensitive actions. If the bibtex entry
1710 has a pdf, you get an option to open it. If there is a doi, you
1711 get a lot of options. LINK-STRING is used by the link function."
1713 (let* ((results (org-ref-get-bibtex-key-and-file))
1715 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
1716 (bibfile (cdr results))
1717 (url (save-excursion
1719 (insert-file-contents bibfile)
1720 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1721 (bibtex-search-entry key)
1722 (bibtex-autokey-get-field "url"))))
1723 (doi (save-excursion
1725 (insert-file-contents bibfile)
1726 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1727 (bibtex-search-entry key)
1728 ;; I like this better than bibtex-url which does not always find
1730 (bibtex-autokey-get-field "doi")))))
1732 (when (string= "" doi) (setq doi nil))
1733 (when (string= "" url) (setq url nil))
1734 (setq org-ref-cite-menu-funcs '())
1740 'org-ref-cite-menu-funcs
1741 '("o" "pen" org-ref-open-citation-at-point)))
1744 (when (file-exists-p pdf-file)
1746 'org-ref-cite-menu-funcs
1747 `("p" "df" ,org-ref-open-pdf-function) t))
1751 'org-ref-cite-menu-funcs
1752 '("n" "otes" org-ref-open-notes-at-point) t)
1757 'org-ref-cite-menu-funcs
1758 '("u" "rl" org-ref-open-url-at-point) t))
1763 'org-ref-cite-menu-funcs
1764 '("w" "os" org-ref-wos-at-point) t)
1767 'org-ref-cite-menu-funcs
1768 '("c" "iting" org-ref-wos-citing-at-point) t)
1771 'org-ref-cite-menu-funcs
1772 '("r" "elated" org-ref-wos-related-at-point) t)
1775 'org-ref-cite-menu-funcs
1776 '("g" "oogle scholar" org-ref-google-scholar-at-point) t)
1779 'org-ref-cite-menu-funcs
1780 '("P" "ubmed" org-ref-pubmed-at-point) t))
1782 ;; add user functions
1783 (dolist (tup org-ref-user-cite-menu-funcs)
1785 'org-ref-cite-menu-funcs
1790 'org-ref-cite-menu-funcs
1791 '("q" "uit" (lambda ())) t)
1793 ;; now we make a menu
1794 ;; construct menu string as a message
1797 (let* ((results (org-ref-get-bibtex-key-and-file))
1799 (bibfile (cdr results)))
1802 (insert-file-contents bibfile)
1803 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
1804 (bibtex-search-entry key)
1805 (org-ref-bib-citation))))
1809 (concat "[" (elt tup 0) "]"
1811 org-ref-cite-menu-funcs "")))
1813 (let* ((input (read-char-exclusive))
1815 (char-to-string input) org-ref-cite-menu-funcs)))
1816 ;; now run the function (2nd element in choice)
1823 ;; *** Generation of the cite links
1824 (defmacro org-ref-make-completion-function (type)
1825 "Macro to make a link completion function for a link of TYPE."
1826 `(defun ,(intern (format "org-%s-complete-link" type)) (&optional arg)
1832 (let ((bibtex-files (org-ref-find-bibliography)))
1833 (bibtex-global-key-alist))))))
1835 (defmacro org-ref-make-format-function (type)
1836 "Macro to make a format function for a link of TYPE."
1837 `(defun ,(intern (format "org-ref-format-%s" type)) (keyword desc format)
1842 (format "[[#%s][%s]]" key key))
1843 (org-ref-split-and-strip-string keyword) ","))
1850 (org-ref-split-and-strip-string keyword) ",") "]"))
1855 (format "<a href=\"#%s\">%s</a>" key key))
1856 (org-ref-split-and-strip-string keyword) ","))
1859 (if (string= (substring type -1) "s")
1860 ;; biblatex format for multicite commands, which all end in s. These are formated as \cites{key1}{key2}...
1861 (concat "\\" ,type (mapconcat (lambda (key) (format "{%s}" key))
1862 (org-ref-split-and-strip-string keyword) ""))
1864 (concat "\\" ,type (when desc (org-ref-format-citation-description desc)) "{"
1865 (mapconcat (lambda (key) key) (org-ref-split-and-strip-string keyword) ",")
1867 ;; for markdown we generate pandoc citations
1870 (desc ;; pre and or post text
1871 (let* ((text (split-string desc "::"))
1875 (format "[@%s," keyword)
1876 (when pre (format " %s" pre))
1877 (when post (format ", %s" post))
1882 (lambda (key) (concat "@" key))
1883 (org-ref-split-and-strip-string keyword)
1886 (defun org-ref-format-citation-description (desc)
1887 "Return formatted citation description.
1888 If the cite link has a DESC (description), it is optional text
1889 for the citation command. You can specify pre and post text by
1890 separating these with ::, for example [[cite:key][pre text::post
1893 ((string-match "::" desc)
1894 (format "[%s][%s]" (car (setq results (split-string desc "::"))) (cadr results)))
1895 (t (format "[%s]" desc))))
1897 (defun org-ref-define-citation-link (type &optional key)
1898 "Add a citation link of TYPE for org-ref.
1899 With optional KEY, set the reftex binding. For example:
1900 \(org-ref-define-citation-link \"citez\" ?z) will create a new
1901 citez link, with reftex key of z, and the completion function."
1902 (interactive "sCitation Type: \ncKey: ")
1904 ;; create the formatting function
1905 (eval `(org-ref-make-format-function ,type))
1910 org-ref-cite-onclick-function
1911 (quote ,(intern (format "org-ref-format-%s" type)))))
1913 ;; create the completion function
1914 (eval `(org-ref-make-completion-function ,type))
1916 ;; store new type so it works with adding citations, which checks
1917 ;; for existence in this list
1918 (add-to-list 'org-ref-cite-types type)
1920 ;; and finally if a key is specified, we modify the reftex menu
1922 (setf (nth 2 (assoc 'org reftex-cite-format-builtin))
1923 (append (nth 2 (assoc 'org reftex-cite-format-builtin))
1924 `((,key . ,(concat type ":%l")))))))
1926 ;; create all the link types and their completion functions
1927 (mapcar 'org-ref-define-citation-link org-ref-cite-types)
1929 (defun org-ref-insert-cite-link (alternative-cite)
1930 "Insert a default citation link using reftex.
1931 If you are on a link, it appends to the end of the link,
1932 otherwise, a new link is inserted. Use a prefix
1933 arg (ALTERNATIVE-CITE) to get a menu of citation types."
1935 (org-ref-find-bibliography)
1936 (let* ((object (org-element-context))
1937 (link-string-beginning (org-element-property :begin object))
1938 (link-string-end (org-element-property :end object))
1939 (path (org-element-property :path object)))
1941 (if (not alternative-cite)
1944 ;; case where we are in a link
1945 ((and (equal (org-element-type object) 'link)
1946 (-contains? org-ref-cite-types (org-element-property :type object)))
1947 (goto-char link-string-end)
1948 ;; sometimes there are spaces at the end of the link
1949 ;; this code moves point pack until no spaces are there
1950 (while (looking-back " ") (backward-char))
1951 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1953 ;; We are next to a link, and we want to append
1956 (and (equal (org-element-type (org-element-context)) 'link)
1957 (-contains? org-ref-cite-types (org-element-property :type (org-element-context)))))
1958 (while (looking-back " ") (backward-char))
1959 (insert (concat "," (mapconcat 'identity (reftex-citation t ?a) ","))))
1961 ;; insert fresh link
1964 (concat org-ref-default-citation-link
1966 (mapconcat 'identity (reftex-citation t) ",")))))
1968 ;; you pressed a C-u so we run this code
1969 (reftex-citation))))
1971 (defun org-ref-insert-cite-with-completion (type)
1972 "Insert a cite link of TYPE with completion."
1973 (interactive (list (ido-completing-read "Type: " org-ref-cite-types)))
1974 (insert (funcall (intern (format "org-%s-complete-link" type)))))
1976 (defun org-ref-store-bibtex-entry-link ()
1977 "Save a citation link to the current bibtex entry. Save in the default link type."
1979 (let ((link (concat org-ref-default-citation-link
1982 (bibtex-beginning-of-entry)
1983 (reftex-get-bib-field "=key=" (bibtex-parse-entry))))))
1984 (message "saved %s" link)
1985 (push (list link) org-stored-links)
1986 (car org-stored-links)))
1994 (lambda (path desc format)
1997 (format "\\index{%s}" path)))))
1999 ;; this will generate a temporary index of entries in the file.
2003 (let ((*index-links* '())
2004 (*initial-letters* '()))
2007 (org-element-map (org-element-parse-buffer) 'link
2009 (let ((type (nth 0 link))
2010 (plist (nth 1 link)))
2012 (when (equal (plist-get plist ':type) "index")
2015 (cons (plist-get plist :path)
2017 "[[elisp:(progn (switch-to-buffer \"%s\") (goto-char %s))][%s]]"
2019 (plist-get plist :begin) ;; position of link
2020 ;; grab a description
2022 (goto-char (plist-get plist :begin))
2023 (if (thing-at-point 'sentence)
2025 (replace-regexp-in-string
2026 "\n" "" (thing-at-point 'sentence))
2027 ;; or call it a link
2031 (setq *index-links* (cl-sort *index-links* 'string-lessp :key 'car))
2033 ;; now first letters
2034 (dolist (link *index-links*)
2035 (add-to-list '*initial-letters* (substring (car link) 0 1) t))
2037 ;; now create the index
2038 (switch-to-buffer (get-buffer-create "*index*"))
2041 (insert "#+TITLE: Index\n\n")
2042 (dolist (letter *initial-letters*)
2043 (insert (format "* %s\n" (upcase letter)))
2044 ;; now process the links
2047 (string= letter (substring (car (car *index-links*)) 0 1)))
2048 (let ((link (pop *index-links*)))
2049 (insert (format "%s %s\n\n" (car link) (cdr link))))))
2050 (switch-to-buffer "*index*")))
2052 (lambda (path desc format)
2055 (format "\\printindex")))))
2060 nil ;; no follow action
2061 (lambda (path desc format)
2064 (format "\\newglossaryentry{%s}{%s}" path desc)))))
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)))))
2088 nil ;; no follow action
2089 (lambda (path desc format)
2092 (format "\\Gls{%s}" path)))))
2097 nil ;; no follow action
2098 (lambda (path desc format)
2101 (format "\\Glspl{%s}" path)))))
2104 ;; ** create text citations from a bibtex entry
2105 (defun org-ref-bib-citation ()
2106 "From a bibtex entry, create and return a simple citation string.
2107 This assumes you are in an article."
2108 (bibtex-set-dialect nil t)
2109 (bibtex-beginning-of-entry)
2110 (let* ((cb (current-buffer))
2111 (bibtex-expand-strings t)
2112 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2113 collect (cons (downcase key) value)))
2114 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2115 (year (reftex-get-bib-field "year" entry))
2116 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2117 (key (reftex-get-bib-field "=key=" entry))
2118 (journal (let ((jt (reftex-get-bib-field "journal" entry)))
2120 (reftex-get-bib-field "journaltitle" 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))
2127 ;;authors, "title", Journal, vol(iss):pages (year).
2128 (format "%s, \"%s\", %s, %s:%s (%s)"
2129 author title journal volume pages year)))
2131 (defun org-ref-bib-html-citation ()
2132 "From a bibtex entry, create and return a simple citation with html links."
2133 (bibtex-beginning-of-entry)
2134 (let* ((cb (current-buffer))
2135 (bibtex-expand-strings t)
2136 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2137 collect (cons (downcase key) value)))
2138 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2139 (year (reftex-get-bib-field "year" entry))
2140 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2141 (key (reftex-get-bib-field "=key=" entry))
2142 (journal (reftex-get-bib-field "journal" entry))
2143 (volume (reftex-get-bib-field "volume" entry))
2144 (pages (reftex-get-bib-field "pages" entry))
2145 (doi (reftex-get-bib-field "doi" entry))
2146 (url (reftex-get-bib-field "url" entry)))
2147 ;;authors, "title", Journal, vol(iss):pages (year).
2148 (concat (format "%s, \"%s\", %s, %s:%s (%s)."
2149 author title journal volume pages year)
2150 (when url (format " <a href=\"%s\">link</a>" url))
2152 (format " <a href=\"http://dx.doi.org/%s\">doi</a>" doi)))))
2154 ;; ** Open pdf in bibtex entry
2155 (defun org-ref-open-bibtex-pdf ()
2156 "Open pdf for a bibtex entry, if it exists.
2158 the entry of interest in the bibfile. but does not check that."
2161 (bibtex-beginning-of-entry)
2162 (let* ((bibtex-expand-strings t)
2163 (entry (bibtex-parse-entry t))
2164 (key (reftex-get-bib-field "=key=" entry))
2165 (pdf (format (concat org-ref-pdf-directory "%s.pdf") key)))
2167 (if (file-exists-p pdf)
2168 (org-open-link-from-string (format "[[file:%s]]" pdf))
2171 ;; ** Open notes from bibtex entry
2173 (defun org-ref-open-bibtex-notes ()
2174 "From a bibtex entry, open the notes if they exist, and create a heading if they do not.
2176 I never did figure out how to use reftex to make this happen
2177 non-interactively. the reftex-format-citation function did not
2178 work perfectly; there were carriage returns in the strings, and
2179 it did not put the key where it needed to be. so, below I replace
2180 the carriage returns and extra spaces with a single space and
2181 construct the heading by hand."
2184 (bibtex-beginning-of-entry)
2185 (let* ((cb (current-buffer))
2186 (bibtex-expand-strings t)
2187 (entry (cl-loop for (key . value) in (bibtex-parse-entry t)
2188 collect (cons (downcase key) value)))
2189 (title (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "title" entry)))
2190 (year (reftex-get-bib-field "year" entry))
2191 (author (replace-regexp-in-string "\n\\|\t\\|\s+" " " (reftex-get-bib-field "author" entry)))
2192 (key (reftex-get-bib-field "=key=" entry))
2193 (journal (reftex-get-bib-field "journal" entry))
2194 (volume (reftex-get-bib-field "volume" entry))
2195 (pages (reftex-get-bib-field "pages" entry))
2196 (doi (reftex-get-bib-field "doi" entry))
2197 (url (reftex-get-bib-field "url" entry))
2200 ;; save key to clipboard to make saving pdf later easier by pasting.
2203 (kill-ring-save (point-min) (point-max)))
2205 ;; now look for entry in the notes file
2206 (if org-ref-bibliography-notes
2207 (find-file-other-window org-ref-bibliography-notes)
2208 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2210 (goto-char (point-min))
2211 ;; put new entry in notes if we don't find it.
2212 (if (re-search-forward (format ":Custom_ID: %s$" key) nil 'end)
2213 (funcall org-ref-open-notes-function)
2214 ;; no entry found, so add one
2215 (insert (format "\n** TODO %s - %s" year title))
2227 [[cite:%s]] [[file:%s/%s.pdf][pdf]]\n\n"
2228 key author journal year volume pages doi url key org-ref-pdf-directory key))
2231 (defun org-ref-open-notes-from-reftex ()
2232 "Call reftex, and open notes for selected entry."
2234 (let ((bibtex-key )))
2236 ;; now look for entry in the notes file
2237 (if org-ref-bibliography-notes
2238 (find-file-other-window org-ref-bibliography-notes)
2239 (error "Org-ref-bib-bibliography-notes is not set to anything"))
2241 (goto-char (point-min))
2243 (re-search-forward (format
2245 (cl-first (reftex-citation t)) nil 'end))
2246 (funcall org-ref-open-notes-function))
2248 ;; ** Open bibtex entry in browser
2249 (defun org-ref-open-in-browser ()
2250 "Open the bibtex entry at point in a browser using the url field or doi field."
2253 (bibtex-beginning-of-entry)
2255 (let ((url (bibtex-autokey-get-field "url")))
2260 (let ((doi (bibtex-autokey-get-field "doi")))
2262 (if (string-match "^http" doi)
2264 (browse-url (format "http://dx.doi.org/%s" doi)))
2266 (message "No url or doi found"))))
2268 ;; ** upload entry to citeulike
2270 (defun org-ref-upload-bibtex-entry-to-citeulike ()
2271 "With point in a bibtex entry get bibtex string and submit to citeulike.
2273 Relies on the python script /upload_bibtex_citeulike.py being in the user directory."
2275 (message "uploading to citeulike")
2277 (bibtex-narrow-to-entry)
2278 (let ((startpos (point-min))
2279 (endpos (point-max))
2280 (bibtex-string (buffer-string))
2281 (script (concat "python " starter-kit-dir "/upload_bibtex_citeulike.py&")))
2282 (with-temp-buffer (insert bibtex-string)
2283 (shell-command-on-region (point-min) (point-max) script t nil nil t)))))
2285 ;; ** Build a pdf of the bibtex file
2286 (defun org-ref-build-full-bibliography ()
2287 "Build pdf of all bibtex entries, and open it."
2289 (let* ((bibfile (file-name-nondirectory (buffer-file-name)))
2290 (bib-base (file-name-sans-extension bibfile))
2291 (texfile (concat bib-base ".tex"))
2292 (pdffile (concat bib-base ".pdf")))
2295 (insert (format "\\documentclass[12pt]{article}
2296 \\usepackage[version=3]{mhchem}
2298 \\usepackage[numbers]{natbib}
2299 \\usepackage[colorlinks=true, linkcolor=blue, urlcolor=blue, pdfstartview=FitH]{hyperref}
2303 \\bibliographystyle{unsrtnat}
2305 \\end{document}" bib-base))
2307 (shell-command (concat "pdflatex " bib-base))
2308 (shell-command (concat "bibtex " bib-base))
2309 (shell-command (concat "pdflatex " bib-base))
2310 (shell-command (concat "pdflatex " bib-base))
2311 (kill-buffer texfile)
2312 (org-open-file pdffile)
2315 ;; ** Extract bibtex entries in org-file
2317 (defun org-ref-extract-bibtex-entries ()
2318 "Extract the bibtex entries referred to by cite links in the current buffer into a src block at the bottom of the current buffer.
2320 If no bibliography is in the buffer the variable
2321 `reftex-default-bibliography' is used."
2323 (let* ((temporary-file-directory (file-name-directory (buffer-file-name)))
2324 (tempname (make-temp-file "extract-bib"))
2325 (contents (buffer-string))
2326 (cb (current-buffer))
2327 basename texfile bibfile results)
2329 ;; open tempfile and insert org-buffer contents
2330 (find-file tempname)
2332 (setq basename (file-name-sans-extension
2333 (file-name-nondirectory buffer-file-name))
2334 texfile (concat tempname ".tex")
2335 bibfile (concat tempname ".bib"))
2337 ;; see if we have a bibliography, and insert the default one if not.
2339 (goto-char (point-min))
2340 (unless (re-search-forward "^bibliography:" (point-max) 'end)
2341 (insert (format "\nbibliography:%s"
2342 (mapconcat 'identity reftex-default-bibliography ",")))))
2345 ;; get a latex file and extract the references
2346 (org-latex-export-to-latex)
2349 (reftex-create-bibtex-file bibfile)
2351 ;; save results of the references
2352 (setq results (buffer-string))
2354 ;; kill buffers. these are named by basename, not full path
2355 (kill-buffer (concat basename ".bib"))
2356 (kill-buffer (concat basename ".tex"))
2357 (kill-buffer basename)
2359 (delete-file bibfile)
2360 (delete-file texfile)
2361 (delete-file tempname)
2363 ;; Now back to the original org buffer and insert the results
2364 (switch-to-buffer cb)
2365 (when (not (string= "" results))
2367 (goto-char (point-max))
2369 (org-insert-heading)
2370 (insert (format " Bibtex entries
2372 #+BEGIN_SRC text :tangle %s
2374 #+END_SRC" (concat (file-name-sans-extension (file-name-nondirectory (buffer-file-name))) ".bib") results))))))
2376 ;; ** Find bad citations
2379 (defun index (substring list)
2380 "Return the index of SUBSTRING in a LIST of strings."
2383 (dolist (arg list i)
2384 (if (string-match (concat "^" substring "$") arg)
2389 ;; return counter if found, otherwise return nil
2393 (defun org-ref-find-bad-citations ()
2394 "Create a list of citation keys in an org-file that do not have a bibtex entry in the known bibtex files.
2396 Makes a new buffer with clickable links."
2398 ;; generate the list of bibtex-keys and cited keys
2399 (let* ((bibtex-files (org-ref-find-bibliography))
2400 (bibtex-file-path (mapconcat (lambda (x) (file-name-directory (file-truename x))) bibtex-files ":"))
2401 (bibtex-keys (mapcar (lambda (x) (car x)) (bibtex-global-key-alist)))
2402 (bad-citations '()))
2404 (org-element-map (org-element-parse-buffer) 'link
2406 (let ((plist (nth 1 link)))
2407 (when (-contains? org-ref-cite-types (plist-get plist :type))
2408 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)))
2409 (when (not (index key bibtex-keys))
2414 `(,(format "%s [[elisp:(progn (switch-to-buffer-other-frame \"%s\")(goto-char %s))][not found here]]\n"
2417 (plist-get plist :begin)))))
2419 ;; set with-affilates to t to get citations in a caption
2424 (switch-to-buffer-other-window "*Missing citations*")
2427 (insert "* List of bad cite links\n")
2428 (insert (mapconcat 'identity bad-citations ""))
2429 ;(setq buffer-read-only t)
2430 (use-local-map (copy-keymap org-mode-map))
2431 (local-set-key "q" #'(lambda () (interactive) (kill-buffer))))
2433 (when (get-buffer "*Missing citations*")
2434 (kill-buffer "*Missing citations*"))
2435 (message "No bad cite links found"))))
2437 ;; ** helm interface to bad citations, labels, refs and files in orgfile
2438 (defun org-ref-bad-cite-candidates ()
2439 "Return a list of conses (key . marker) where key does not exist in the known bibliography files, and marker points to the key."
2440 (let* ((cp (point)) ; save to return to later
2441 (bibtex-files (org-ref-find-bibliography))
2442 (bibtex-file-path (mapconcat
2444 (file-name-directory (file-truename x)))
2446 (bibtex-keys (mapcar (lambda (x) (car x))
2447 (bibtex-global-key-alist)))
2448 (bad-citations '()))
2450 (org-element-map (org-element-parse-buffer) 'link
2452 (let ((plist (nth 1 link)))
2453 (when (-contains? org-ref-cite-types (plist-get plist :type))
2454 (dolist (key (org-ref-split-and-strip-string (plist-get plist :path)) )
2455 (when (not (index key bibtex-keys))
2456 (goto-char (plist-get plist :begin))
2457 (re-search-forward key)
2458 (push (cons key (point-marker)) bad-citations)))
2460 ;; add with-affiliates to get cites in caption
2466 (defun org-ref-bad-ref-candidates ()
2467 "Return a list of conses (ref . marker) where ref is a ref link that does not point to anything (i.e. a label)."
2468 ;; first get a list of legitimate labels
2470 (labels (org-ref-get-labels))
2472 ;; now loop over ref links
2473 (goto-char (point-min))
2474 (org-element-map (org-element-parse-buffer) 'link
2476 (let ((plist (nth 1 link)))
2477 (when (or (equal (plist-get plist ':type) "ref")
2478 (equal (plist-get plist ':type) "eqref")
2479 (equal (plist-get plist ':type) "pageref")
2480 (equal (plist-get plist ':type) "nameref"))
2481 (unless (-contains? labels (plist-get plist :path))
2482 (goto-char (plist-get plist :begin))
2485 (cons (plist-get plist :path)
2486 (point-marker))))))))
2491 (defun org-ref-bad-label-candidates ()
2492 "Return a list of labels where label is multiply defined."
2493 (let ((labels (org-ref-get-labels))
2494 (multiple-labels '()))
2495 (when (not (= (length labels)
2496 (length (-uniq labels))))
2497 (dolist (label labels)
2498 (when (> (-count (lambda (a)
2501 ;; this is a multiply defined label.
2503 (goto-char (point-min))
2504 (while (re-search-forward
2505 (format "[^#+]label:%s\\s-" label) nil t)
2506 (push (cons label (point-marker)) multiple-labels))
2507 (goto-char (point-min))
2508 (while (re-search-forward
2509 (format "\\label{%s}\\s-?" label) nil t)
2510 (push (cons label (point-marker)) multiple-labels))
2512 (goto-char (point-min))
2513 (while (re-search-forward
2514 (format "^#\\+label:\\s-*%s" label) nil t)
2515 (push (cons label (point-marker)) multiple-labels))
2517 (goto-char (point-min))
2518 (while (re-search-forward
2519 (format "^#\\+tblname:\\s-*%s" label) nil t)
2520 (push (cons label (point-marker)) multiple-labels))
2524 (defun org-ref-bad-file-link-candidates ()
2525 "Return list of conses (link . marker) wehre the file in the link does not exist."
2526 (let* ((bad-files '()))
2527 (org-element-map (org-element-parse-buffer) 'link
2529 (let ((type (org-element-property :type link)))
2530 (when (or (string= "file" type)
2531 (string= "attachfile" type))
2532 (unless (file-exists-p (org-element-property :path link))
2533 (add-to-list 'bad-files
2534 (cons (org-element-property :path link)
2537 (org-element-property :begin link))
2538 (point-marker)))))))))
2539 ;; Let us also check \attachfile{fname}
2541 (goto-char (point-min))
2542 (while (re-search-forward "\\attachfile{\\(.*\\)}" nil t)
2543 (unless (file-exists-p (match-string 1))
2544 (add-to-list 'bad-files (cons (match-string 1) (point-marker))))))
2549 "Opens a helm interface to actions for org-ref.
2550 Shows bad citations, ref links and labels"
2552 (let ((cb (current-buffer))
2553 (bad-citations (org-ref-bad-cite-candidates))
2554 (bad-refs (org-ref-bad-ref-candidates))
2555 (bad-labels (org-ref-bad-label-candidates))
2556 (bad-files (org-ref-bad-file-link-candidates)))
2558 (helm :sources `(((name . "Bad citations")
2559 (candidates . ,bad-citations)
2560 (action . (lambda (marker)
2561 (switch-to-buffer (marker-buffer marker))
2562 (goto-char marker))))
2564 ((name . "Bad Labels")
2565 (candidates . ,bad-labels)
2566 (action . (lambda (marker)
2567 (switch-to-buffer (marker-buffer marker))
2568 (goto-char marker))))
2570 ((name . "Bad ref links")
2571 (candidates . ,bad-refs)
2572 (action . (lambda (marker)
2573 (switch-to-buffer (marker-buffer marker))
2574 (goto-char marker))))
2576 ((name . "Bad file links")
2577 (candidates . ,bad-files)
2579 (switch-to-buffer (marker-buffer marker))
2580 (goto-char marker)))
2582 ((name . "Utilities")
2583 (candidates . (("Check buffer again" . org-ref)
2584 ("Insert citation" . helm-bibtex)
2585 ("Insert label link" . org-ref-helm-insert-label-link)
2586 ("Insert ref link" . org-ref-helm-insert-ref-link)
2587 ("List of figures" . org-ref-list-of-figures)
2588 ("List of tables" . org-ref-list-of-tables)
2589 ("Table of contents" . nil)
2591 (action . (lambda (x)
2592 (switch-to-buffer ,cb)
2595 ((name . "Export functions")
2596 (candidates . (("Extract cited entries" . org-ref-extract-bibtex-entries)
2597 ("Export to html and open" . (lambda () (org-open-file (org-html-export-to-html))))
2598 ("Export to pdf and open" . (lambda ()
2599 (org-open-file (org-latex-export-to-pdf))))
2600 ("Export to manuscript pdf and open" . ox-manuscript-export-and-build-and-open)
2601 ("Export submission manuscript pdf and open" . ox-manuscript-build-submission-manuscript-and-open)
2604 (action . (lambda (x)
2605 (switch-to-buffer ,cb)
2608 ;; ** Find non-ascii charaters
2609 (defun org-ref-find-non-ascii-characters ()
2610 "Find non-ascii characters in the buffer. Useful for cleaning up bibtex files."
2612 (occur "[^[:ascii:]]"))
2614 ;; ** Sort fields in a bibtex entry
2616 (defun org-ref-sort-bibtex-entry ()
2617 "Sort fields of entry in standard order and downcase them."
2619 (bibtex-beginning-of-entry)
2620 (let* ((master '("author" "title" "journal" "volume" "number" "pages" "year" "doi" "url"))
2621 (entry (bibtex-parse-entry))
2624 (type (cdr (assoc "=type=" entry)))
2625 (key (cdr (assoc "=key=" entry))))
2627 ;; these are the fields we want to order that are in this entry
2628 (setq entry-fields (mapcar (lambda (x) (car x)) entry))
2629 ;; we do not want to reenter these fields
2630 (setq entry-fields (remove "=key=" entry-fields))
2631 (setq entry-fields (remove "=type=" entry-fields))
2633 ;;these are the other fields in the entry
2634 (setq other-fields (remove-if-not (lambda(x) (not (member x master))) entry-fields))
2637 ;; right now we only resort articles
2638 ((string= (downcase type) "article")
2641 (concat "@article{" key ",\n"
2644 (when (member field entry-fields)
2645 (format "%s = %s," (downcase field) (cdr (assoc field entry))))) master "\n")
2648 (format "%s = %s," (downcase field) (cdr (assoc field entry)))) other-fields "\n")
2650 (bibtex-find-entry key)
2652 (bibtex-clean-entry)
2655 ;; ** Clean a bibtex entry
2656 (defun org-ref-clean-bibtex-entry(&optional keep-key)
2657 "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"
2659 (bibtex-beginning-of-entry)
2661 ;; some entries do not have a key or comma in first line. We check and add it, if needed.
2662 (unless (string-match ",$" (thing-at-point 'line))
2666 ;; check for empty pages, and put eid or article id in its place
2667 (let ((entry (bibtex-parse-entry))
2668 (pages (bibtex-autokey-get-field "pages"))
2669 (year (bibtex-autokey-get-field "year"))
2670 (doi (bibtex-autokey-get-field "doi"))
2671 ;; The Journal of Chemical Physics uses eid
2672 (eid (bibtex-autokey-get-field "eid")))
2674 ;; replace http://dx.doi.org/ in doi. some journals put that in,
2675 ;; but we only want the doi.
2676 (when (string-match "^http://dx.doi.org/" doi)
2677 (bibtex-beginning-of-entry)
2678 (goto-char (car (cdr (bibtex-search-forward-field "doi" t))))
2680 (bibtex-make-field "doi")
2682 (insert (replace-regexp-in-string "^http://dx.doi.org/" "" doi)))
2684 ;; asap articles often set year to 0, which messes up key
2685 ;; generation. fix that.
2686 (when (string= "0" year)
2687 (bibtex-beginning-of-entry)
2688 (goto-char (car (cdr (bibtex-search-forward-field "year" t))))
2690 (bibtex-make-field "year")
2692 (insert (read-string "Enter year: ")))
2694 ;; fix pages if they are empty if there is an eid to put there.
2695 (when (string= "-" pages)
2697 (bibtex-beginning-of-entry)
2698 ;; this seems like a clunky way to set the pages field.But I
2699 ;; cannot find a better way.
2700 (goto-char (car (cdr (bibtex-search-forward-field "pages" t))))
2702 (bibtex-make-field "pages")
2706 ;; replace naked & with \&
2708 (bibtex-narrow-to-entry)
2709 (bibtex-beginning-of-entry)
2710 (message "checking &")
2711 (replace-regexp " & " " \\\\& ")
2714 ;; generate a key, and if it duplicates an existing key, edit it.
2716 (let ((key (bibtex-generate-autokey)))
2718 ;; first we delete the existing key
2719 (bibtex-beginning-of-entry)
2720 (re-search-forward bibtex-entry-maybe-empty-head)
2721 (if (match-beginning bibtex-key-in-head)
2722 (delete-region (match-beginning bibtex-key-in-head)
2723 (match-end bibtex-key-in-head)))
2724 ;; check if the key is in the buffer
2725 (when (save-excursion
2726 (bibtex-search-entry key))
2728 (bibtex-search-entry key)
2729 (bibtex-copy-entry-as-kill)
2730 (switch-to-buffer-other-window "*duplicate entry*")
2732 (setq key (bibtex-read-key "Duplicate Key found, edit: " key)))
2735 (kill-new key))) ;; save key for pasting
2737 ;; run hooks. each of these operates on the entry with no arguments.
2738 ;; this did not work like i thought, it gives a symbolp error.
2739 ;; (run-hooks org-ref-clean-bibtex-entry-hook)
2744 org-ref-clean-bibtex-entry-hook)
2746 ;; sort fields within entry
2747 (org-ref-sort-bibtex-entry)
2748 ;; check for non-ascii characters
2749 (occur "[^[:ascii:]]")
2752 (defun org-ref-get-citation-year (key)
2753 "Get the year of an entry with KEY. Return year as a string."
2754 (let* ((results (org-ref-get-bibtex-key-and-file key))
2755 (bibfile (cdr results)))
2757 (insert-file-contents bibfile)
2758 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
2759 (bibtex-search-entry key nil 0)
2760 (prog1 (reftex-get-bib-field "year" (bibtex-parse-entry t))
2763 ;; ** Sort cite in cite link
2764 (defun org-ref-sort-citation-link ()
2765 "Replace link at point with sorted link by year."
2767 (let* ((object (org-element-context))
2768 (type (org-element-property :type object))
2769 (begin (org-element-property :begin object))
2770 (end (org-element-property :end object))
2771 (link-string (org-element-property :path object))
2773 (setq keys (org-ref-split-and-strip-string link-string))
2774 (setq years (mapcar 'org-ref-get-citation-year keys))
2775 (setq data (mapcar* (lambda (a b) `(,a . ,b)) years keys))
2776 (setq data (cl-sort data (lambda (x y) (< (string-to-number (car x)) (string-to-number (car y))))))
2777 ;; now get the keys separated by commas
2778 (setq keys (mapconcat (lambda (x) (cdr x)) data ","))
2779 ;; and replace the link with the sorted keys
2780 (cl--set-buffer-substring begin end (concat type ":" keys))))
2782 ;; ** Shift-arrow sorting of keys in a cite link
2784 (defun org-ref-swap-keys (i j keys)
2785 "Swap the KEYS in a list with index I and J."
2786 (let ((tempi (nth i keys)))
2787 (setf (nth i keys) (nth j keys))
2788 (setf (nth j keys) tempi))
2792 (defun org-ref-swap-citation-link (direction)
2793 "Move citation at point in DIRECTION +1 is to the right, -1 to the left."
2795 (let* ((object (org-element-context))
2796 (type (org-element-property :type object))
2797 (begin (org-element-property :begin object))
2798 (end (org-element-property :end object))
2799 (link-string (org-element-property :path object))
2801 ;; We only want this to work on citation links
2802 (when (-contains? org-ref-cite-types type)
2803 (setq key (org-ref-get-bibtex-key-under-cursor))
2804 (setq keys (org-ref-split-and-strip-string link-string))
2805 (setq i (index key keys)) ;; defined in org-ref
2806 (if (> direction 0) ;; shift right
2807 (org-ref-swap-keys i (+ i 1) keys)
2808 (org-ref-swap-keys i (- i 1) keys))
2809 (setq keys (mapconcat 'identity keys ","))
2810 ;; and replace the link with the sorted keys
2811 (cl--set-buffer-substring
2815 ;; It seems the space at the end can get consumed, so we see if there
2816 ;; is a space, and add it if so. Sometimes there is a comma or period,
2817 ;; then we do not want a space.
2821 (looking-back " ")) " ")))
2822 ;; now go forward to key so we can move with the key
2823 (re-search-forward key)
2824 (goto-char (match-beginning 0)))))
2826 ;; add hooks to make it work
2827 (add-hook 'org-shiftright-hook (lambda () (org-ref-swap-citation-link 1)))
2828 (add-hook 'org-shiftleft-hook (lambda () (org-ref-swap-citation-link -1)))
2830 ;; ** context around org-ref links
2831 (defun org-ref-get-label-context (label)
2832 "Return a string of context around a LABEL."
2835 (goto-char (point-min))
2836 (when (re-search-forward
2837 (format "label:%s\\b" label) nil t)
2838 (throw 'result (buffer-substring
2847 (goto-char (point-min))
2848 (when (re-search-forward
2849 (format "\\label{%s}" label) nil t)
2850 (throw 'result (buffer-substring
2859 (goto-char (point-min))
2860 (when (re-search-forward
2861 (format "^#\\+label:\\s-*\\(%s\\)\\b" label) nil t)
2862 (throw 'result (buffer-substring
2871 (goto-char (point-min))
2872 (when (re-search-forward
2873 (format "^#\\+tblname:\\s-*\\(%s\\)\\b" label) nil t)
2874 (throw 'result (buffer-substring
2882 (throw 'result "!!! NO CONTEXT FOUND !!!"))))
2885 (defun org-ref-link-message ()
2886 "Print a minibuffer message about the link that point is on."
2890 (when (eq major-mode 'org-mode)
2891 (let* ((object (org-element-context))
2892 (type (org-element-property :type object)))
2896 ((-contains? org-ref-cite-types type)
2897 (message (org-ref-get-citation-string-at-point)))
2899 ;; message some context about the label we are referring to
2900 ((string= type "ref")
2901 (message "%scount: %s"
2902 (org-ref-get-label-context
2903 (org-element-property :path object))
2904 (org-ref-count-labels
2905 (org-element-property :path object))))
2907 ((string= type "eqref")
2908 (message "%scount: %s"
2909 (org-ref-get-label-context
2910 (org-element-property :path object))
2911 (org-ref-count-labels
2912 (org-element-property :path object))))
2914 ;; message the count
2915 ((string= type "label")
2916 (let ((count (org-ref-count-labels
2917 (org-element-property :path object))))
2918 ;; get plurality on occurrence correct
2920 (number-to-string count)
2922 (when (or (= count 0)
2926 ((string= type "custom-id")
2928 (org-open-link-from-string
2929 (format "[[#%s]]" (org-element-property :path object)))
2930 (message "%s" (org-get-heading))))
2932 ;; check if the bibliography files exist.
2933 ((string= type "bibliography")
2935 ;; object is the link you clicked on
2936 (object (org-element-context))
2937 (link-string (org-element-property :path object))
2938 (link-string-beginning)
2941 (goto-char (org-element-property :begin object))
2942 (search-forward link-string nil nil 1)
2943 (setq link-string-beginning (match-beginning 0))
2944 (setq link-string-end (match-end 0)))
2946 ;; make sure we are in link and not before the :
2947 (when (> link-string-beginning (point))
2948 (goto-char link-string-beginning))
2950 (let (key-beginning key-end)
2951 ;; now if we have comma separated bibliographies
2952 ;; we find the one clicked on. we want to
2953 ;; search forward to next comma from point
2955 (if (search-forward "," link-string-end 1 1)
2956 (setq key-end (- (match-end 0) 1)) ; we found a match
2957 (setq key-end (point)))) ; no comma found so take the point
2959 ;; and backward to previous comma from point
2961 (if (search-backward "," link-string-beginning 1 1)
2962 (setq key-beginning (+ (match-beginning 0) 1)) ; we found a match
2963 (setq key-beginning (point)))) ; no match found
2964 ;; save the key we clicked on.
2966 (org-ref-strip-string
2967 (buffer-substring key-beginning key-end)))
2968 (if (file-exists-p bibfile)
2969 (message "%s exists." bibfile)
2970 (message "!!! %s NOT FOUND !!!" bibfile)))))))))))
2973 (defalias 'oro 'org-ref-open-citation-at-point)
2974 (defalias 'orc 'org-ref-citation-at-point)
2975 (defalias 'orp 'org-ref-open-pdf-at-point)
2976 (defalias 'oru 'org-ref-open-url-at-point)
2977 (defalias 'orn 'org-ref-open-notes-at-point)
2978 (defalias 'ornr 'org-ref-open-notes-from-reftex)
2980 (defalias 'orib 'org-ref-insert-bibliography-link)
2981 (defalias 'oric 'org-ref-insert-cite-link)
2982 (defalias 'orir 'org-ref-insert-ref-link)
2983 (defalias 'orsl 'org-ref-store-bibtex-entry-link)
2985 (defalias 'orcb 'org-ref-clean-bibtex-entry)
2987 ;; * Helm bibtex setup
2989 (setq helm-bibtex-additional-search-fields '(keywords))
2991 (defun helm-bibtex-candidates-formatter (candidates source)
2992 "Formats BibTeX entries for display in results list.
2993 Argument CANDIDATES helm candidates.
2994 Argument SOURCE the helm source."
2996 with width = (with-helm-window (helm-bibtex-window-width))
2997 for entry in candidates
2998 for entry = (cdr entry)
2999 for entry-key = (helm-bibtex-get-value "=key=" entry)
3000 if (assoc-string "author" entry 'case-fold)
3001 for fields = '("author" "title" "year" "=has-pdf=" "=has-note=" "=type=")
3003 for fields = '("editor" "title" "year" "=has-pdf=" "=has-note=" "=type=")
3004 for fields = (--map (helm-bibtex-clean-string
3005 (helm-bibtex-get-value it entry " "))
3007 for fields = (-update-at 0 'helm-bibtex-shorten-authors fields)
3008 for fields = (append fields
3009 (list (or (helm-bibtex-get-value "keywords" entry)
3012 (cons (s-format "$0 $1 $2 $3 $4$5 $6" 'elt
3013 (-zip-with (lambda (f w) (truncate-string-to-width f w 0 ?\s))
3014 fields (list 36 (- width 85) 4 1 1 7 7)))
3017 ;; * org-ref bibtex keywords
3018 ;; adapted from bibtex-utils.el
3019 ;; these are candidates for selecting keywords/tags
3020 (defun org-ref-bibtex-keywords ()
3021 "Get keywords defined in current bibtex file.
3022 These are in the keywords field, and are comma or semicolon separated."
3024 (goto-char (point-min))
3025 (let (keywords kstring)
3026 (while (re-search-forward "^\\s-*keywords.*{\\([^}]+\\)}" nil t)
3027 ;; TWS - remove newlines/multiple spaces:
3028 (setq kstring (replace-regexp-in-string "[ \t\n]+" " " (match-string 1)))
3031 (add-to-list 'keywords v t))
3032 (split-string kstring "\\(,\\|;\\)[ \n]*\\|{\\|}" t)))
3036 (defun org-ref-set-bibtex-keywords (keywords &optional arg)
3037 "Add KEYWORDS to a bibtex entry.
3038 If KEYWORDS is a list, it is converted to a comma-separated
3039 string. The KEYWORDS are added to the beginning of the
3040 field. Otherwise KEYWORDS should be a string of comma-separate
3041 keywords. Optional argument ARG prefix arg to replace keywords."
3042 (interactive "sKeywords: \nP")
3047 (if (listp keywords)
3048 (mapconcat 'identity keywords ", ")
3050 ;; else concatentate
3052 (if (listp keywords)
3053 (mapconcat 'identity keywords ", ")
3055 (when (not (string= "" (bibtex-autokey-get-field "keywords")))
3056 (concat ", " (bibtex-autokey-get-field "keywords"))))))
3060 (defun helm-tag-bibtex-entry ()
3061 "Helm interface to add keywords to a bibtex entry.
3062 Run this with the point in a bibtex entry."
3064 (let ((keyword-source `((name . "Existing keywords")
3065 (candidates . ,(org-ref-bibtex-keywords))
3066 (action . (lambda (candidate)
3067 (org-ref-set-bibtex-keywords
3070 (helm-marked-candidates)
3072 (fallback-source `((name . "Add new keywords")
3074 (action . (lambda (candidate)
3075 (org-ref-set-bibtex-keywords helm-pattern)
3077 (helm :sources '(keyword-source fallback-source))))
3079 (defun helm-bibtex-show-entry (key)
3080 "Show the entry for KEY in the BibTeX file.
3081 The original function in `helm-bibtex' has a bug where it finds the
3082 first key that partially matches. This version avoids that."
3084 (dolist (bibtex-file (if (listp helm-bibtex-bibliography)
3085 helm-bibtex-bibliography
3086 (list helm-bibtex-bibliography)))
3087 (let ((buf (helm-bibtex-buffer-visiting bibtex-file))
3089 (find-file bibtex-file)
3091 (lambda (key start end)
3092 (add-to-list 'entries (cons key start))))
3093 (if (assoc key entries)
3095 (goto-char (cdr (assoc key entries)))
3100 (defun org-ref-helm-tag-entries (candidates)
3101 "Set tags on selected bibtex entries from `helm-bibtex'.
3102 User is prompted for tags. This function is called from `helm-bibtex'.
3103 Argument CANDIDATES helm candidates."
3105 (let ((keywords (read-string "Keywords (comma separated): ")))
3106 (cl-loop for key in (helm-marked-candidates)
3108 (save-window-excursion
3109 (helm-bibtex-show-entry key)
3114 ", " (bibtex-autokey-get-field "keywords")))
3117 (setq helm-source-bibtex
3118 '((name . "BibTeX entries")
3119 (init . helm-bibtex-init)
3120 (candidates . helm-bibtex-candidates)
3121 (filtered-candidate-transformer . helm-bibtex-candidates-formatter)
3122 (action . (("Insert citation" . helm-bibtex-insert-citation)
3123 ("Show entry" . helm-bibtex-show-entry)
3124 ("Open PDF file (if present)" . helm-bibtex-open-pdf)
3125 ("Open URL or DOI in browser" . helm-bibtex-open-url-or-doi)
3126 ("Insert formatted reference" . helm-bibtex-insert-reference)
3127 ("Insert BibTeX key" . helm-bibtex-insert-key)
3128 ("Insert BibTeX entry" . helm-bibtex-insert-bibtex)
3129 ("Attach PDF to email" . helm-bibtex-add-PDF-attachment)
3130 ("Edit notes" . helm-bibtex-edit-notes)
3131 ("Add keywords to entries" . org-ref-helm-tag-entries)
3134 (defun helm-bibtex-format-org-ref (keys)
3135 "Insert selected KEYS as cite link. Append KEYS if you are on a link.
3136 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.
3138 In the helm-bibtex buffer, C-u will give you a helm menu to select a new link type for the selected entries.
3140 C-u C-u will change the key at point to the selected keys."
3141 (let* ((object (org-element-context))
3142 (last-char (save-excursion
3143 (when (org-element-property :end object)
3144 (goto-char (org-element-property :end object))
3147 (if (looking-at " ")
3151 ;; case where we are in a link
3152 ((and (equal (org-element-type object) 'link)
3155 (org-element-property :type object)))
3157 ;; no prefix. append keys
3158 ((equal helm-current-prefix-arg nil)
3159 (goto-char (org-element-property :end object))
3160 (while (looking-back " ") (backward-char))
3161 (insert (concat "," (mapconcat 'identity keys ","))))
3162 ;; double prefix, replace key at point
3163 ((equal helm-current-prefix-arg '(16))
3164 (setf (buffer-substring
3165 (org-element-property :begin object)
3166 (org-element-property :end object))
3168 (replace-regexp-in-string
3169 (car (org-ref-get-bibtex-key-and-file)) ; key
3170 (mapconcat 'identity keys ",") ; new keys
3171 (org-element-property :raw-link object))
3172 ;; replace space at end to avoid collapsing into next word.
3174 ;; and we want to go to the end of the new link
3176 (org-element-property :end (org-element-context))))
3178 (message "Not found"))))
3180 ;; We are next to a link, and we want to append
3181 ;; next to a link means one character back is on a link.
3183 (unless (bobp) (backward-char))
3184 (and (equal (org-element-type (org-element-context)) 'link)
3187 (org-element-property :type (org-element-context)))))
3188 (while (looking-back " ") (backward-char))
3189 (insert (concat "," (mapconcat 'identity keys ","))))
3191 ;; insert fresh link
3193 ;;(message-box "fresh link")
3195 (concat (if (equal helm-current-prefix-arg '(4))
3196 (helm :sources `((name . "link types")
3197 (candidates . ,org-ref-cite-types)
3198 (action . (lambda (x) x))))
3199 org-ref-default-citation-link)
3201 (s-join "," keys))))))
3202 ;; return empty string for helm
3205 (setq helm-bibtex-format-citation-functions
3206 '((org-mode . helm-bibtex-format-org-ref)))
3209 (defun org-ref-helm-insert-cite-link (arg)
3210 "org-ref function to use helm-bibtex to insert a citation link.
3211 With one prefix arg, insert a ref link.
3212 With two prefix args, insert a label link."
3216 (let ((helm-bibtex-bibliography (org-ref-find-bibliography)))
3219 (org-ref-helm-insert-ref-link))
3221 (org-ref-helm-insert-label-link))))
3224 ;; add our own fallback entries where we want them. These appear in reverse order of adding in the menu
3225 (setq helm-bibtex-fallback-options
3226 (-insert-at 1 '("Crossref" . "http://search.crossref.org/?q=%s") helm-bibtex-fallback-options))
3228 (setq helm-bibtex-fallback-options
3231 '("Scopus" . "http://www.scopus.com/scopus/search/submit/xadvanced.url?searchfield=TITLE-ABS-KEY(%s)")
3232 helm-bibtex-fallback-options))
3234 (setq helm-bibtex-fallback-options
3235 (-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))
3237 (defun org-ref-get-citation-string-at-point ()
3238 "Get a string of a formatted citation."
3239 (let* ((results (org-ref-get-bibtex-key-and-file))
3241 (bibfile (cdr results)))
3245 (insert-file-contents bibfile)
3246 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3247 (bibtex-search-entry key)
3248 (org-ref-bib-citation)))
3249 "!!! No entry found !!!" )))
3252 (defun org-ref-cite-candidates ()
3253 "Generate the list of possible candidates for click actions on a cite link.
3254 Checks for pdf and doi, and add appropriate functions."
3255 (let* ((results (org-ref-get-bibtex-key-and-file))
3257 (pdf-file (format (concat org-ref-pdf-directory "%s.pdf") key))
3258 (bibfile (cdr results))
3259 (url (save-excursion
3261 (insert-file-contents bibfile)
3262 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3263 (bibtex-search-entry key)
3264 (bibtex-autokey-get-field "url"))))
3265 (doi (save-excursion
3267 (insert-file-contents bibfile)
3268 (bibtex-set-dialect (parsebib-find-bibtex-dialect) t)
3269 (bibtex-search-entry key)
3270 ;; I like this better than bibtex-url which does not always find
3272 (bibtex-autokey-get-field "doi"))))
3273 (candidates `(("Quit" . org-ref-citation-at-point)
3274 ("Open bibtex entry" . org-ref-open-citation-at-point))))
3275 ;; for some reason, when there is no doi or url, they are returned as "". I
3276 ;; prefer nil so we correct this here.
3277 (when (string= doi "") (setq doi nil))
3278 (when (string= url "") (setq url nil))
3280 ;; Conditional pdf functions
3281 (if (file-exists-p pdf-file)
3284 '("Open pdf" . org-ref-open-pdf-at-point)
3288 '("Try to get pdf" . (lambda ()
3289 (save-window-excursion
3290 (org-ref-open-citation-at-point)
3291 (bibtex-beginning-of-entry)
3292 (doi-utils-get-bibtex-entry-pdf))))
3298 '("Open notes" . org-ref-open-notes-at-point)
3301 ;; conditional url and doi functions
3305 '("Open in browser" . org-ref-open-url-at-point)
3310 (add-to-list 'candidates x t))
3311 `(("WOS" . org-ref-wos-at-point)
3312 ("Related articles in WOS" . org-ref-wos-related-at-point)
3313 ("Citing articles in WOS" . org-ref-wos-citing-at-point)
3314 ("Google Scholar" . org-ref-google-scholar-at-point)
3315 ("Pubmed" . org-ref-pubmed-at-point)
3316 ("Crossref" . org-ref-crossref-at-point)
3321 '("Copy formatted citation to clipboard" . org-ref-copy-entry-as-summary)
3326 '("Copy key to clipboard" . (lambda ()
3328 (car (org-ref-get-bibtex-key-and-file)))))
3333 '("Copy bibtex entry to file" . org-ref-copy-entry-at-point-to-file)
3338 '("Email bibtex entry and pdf" . (lambda ()
3340 (org-ref-open-citation-at-point)
3341 (email-bibtex-entry))))
3343 ;; finally return a numbered list of the candidates
3344 (cl-loop for i from 0
3345 for cell in candidates
3346 collect (cons (format "%2s. %s" i (car cell))
3350 (defvar org-ref-helm-user-candidates '()
3351 "List of user-defined candidates to act when clicking on a cite link.
3352 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.")
3354 ;; example of adding your own function
3356 'org-ref-helm-user-candidates
3357 '("Example" . (lambda () (message-box "You did it!")))
3361 (defun org-ref-cite-click-helm (key)
3362 "Open helm for actions on a cite link.
3365 1. get name and candidates before entering helm because we need
3368 2. switch back to the org buffer before evaluating the
3369 action. most of them need the point and buffer.
3371 KEY is returned for the selected item(s) in helm."
3373 (let ((name (org-ref-get-citation-string-at-point))
3374 (candidates (org-ref-cite-candidates))
3375 (cb (current-buffer)))
3377 (helm :sources `(((name . ,name)
3378 (candidates . ,candidates)
3379 (action . (lambda (f)
3380 (switch-to-buffer cb)
3382 ((name . "User functions")
3383 (candidates . ,org-ref-helm-user-candidates)
3384 (action . (lambda (f)
3385 (switch-to-buffer cb)
3389 ;; * Hydra menus in org-ref
3391 (when (featurep 'hydra)
3393 (setq hydra-is-helpful t)
3395 (defhydra org-ref-cite-hydra (:color blue)
3397 _p_: Open pdf _w_: WOS _g_: Google Scholar _K_: Copy citation to clipboard
3398 _u_: Open url _r_: WOS related _P_: Pubmed _k_: Copy key to clipboard
3399 _n_: Open notes _c_: WOS citing _C_: Crossref _f_: Copy bibtex entry to file
3400 _o_: Open entry _e_: Email entry and pdf
3402 ("o" org-ref-open-citation-at-point nil)
3403 ("p" org-ref-open-pdf-at-point nil)
3404 ("n" org-ref-open-notes-at-point nil)
3405 ("u" org-ref-open-url-at-point nil)
3406 ("w" org-ref-wos-at-point nil)
3407 ("r" org-ref-wos-related-at-point nil)
3408 ("c" org-ref-wos-citing-at-point nil)
3409 ("g" org-ref-google-scholar-at-point nil)
3410 ("P" org-ref-pubmed-at-point nil)
3411 ("C" org-ref-crossref-at-point nil)
3412 ("K" org-ref-copy-entry-as-summary nil)
3415 (car (org-ref-get-bibtex-key-and-file)))) nil)
3416 ("f" org-ref-copy-entry-at-point-to-file nil)
3418 ("e" (save-excursion
3419 (org-ref-open-citation-at-point)
3420 (email-bibtex-entry)) nil)))
3423 (defun org-ref-help ()
3424 "Open the org-ref manual."
3426 (find-file (expand-file-name
3428 (file-name-directory
3429 (find-library-name "org-ref")))))
3432 (defun org-ref-org-menu ()
3433 "Add org-ref menu to the Org menu."
3437 '( ["Insert citation" org-ref-helm-insert-cite-link]
3438 ["Insert ref" org-ref-helm-insert-ref-link]
3439 ["Insert label" org-ref-helm-insert-label-link]
3441 ["List of figures" org-ref-list-of-figures]
3442 ["List of tables" org-ref-list-of-tables]
3443 ["Extract bibtex entries" org-ref-extract-bibtex-entries]
3444 ["Check org-file" org-ref]
3446 ["Help" org-ref-help]
3447 ["Customize org-ref" (customize-group 'org-ref)])
3450 (easy-menu-change '("Org") "--" nil "Show/Hide"))
3452 (add-hook 'org-mode-hook 'org-ref-org-menu)
3457 ;;; org-ref.el ends here