Skip to content

Instantly share code, notes, and snippets.

@riethmayer
Forked from even4void/.emacs
Last active March 21, 2022 13:36
Show Gist options
  • Save riethmayer/936dcbbcad18fdca2d9c to your computer and use it in GitHub Desktop.
Save riethmayer/936dcbbcad18fdca2d9c to your computer and use it in GitHub Desktop.
A basic previewer for R Markdown files edited with Emacs
(add-to-list 'auto-mode-alist '("\\.md\\'" . markdown-mode))
(add-to-list 'auto-mode-alist '("\\.Rmd\\'" . markdown-mode))
(add-to-list 'auto-mode-alist '("\\.rmd\\'" . markdown-mode))
(add-hook 'markdown-mode-hook 'turn-on-outline-minor-mode)
(defun rmarkdown-new-chunk (name)
"Insert a new R chunk."
(interactive "sChunk name: ")
(insert "\n```{r " name "}\n")
(save-excursion
(newline)
(insert "```\n")
(previous-line)))
(defun rmarkdown-weave-file ()
"Run knitr on the current file and weave it as MD and HTML."
(interactive)
(shell-command
(format "knit.sh -c %s"
(shell-quote-argument (buffer-file-name)))))
(defun rmarkdown-tangle-file ()
"Run knitr on the current file and tangle its R code."
(interactive)
(shell-command
(format "knit.sh -t %s"
(shell-quote-argument (buffer-file-name)))))
(defun rmarkdown-preview-file ()
"Run knitr on the current file and display output in a browser."
(interactive)
(shell-command
(format "knit.sh -b %s"
(shell-quote-argument (buffer-file-name)))))
#! /usr/bin/env sh
#
# Process R Markdown file and display HTML output directly in the browser.
#
usage()
{
cat << EOF
Usage: $0 [-h] [-c] [-b] [-t] filename
This script weaves and tangles an R Markdown file using knitr.
OPTIONS:
-h show this message
-c compile Rmd file to Markdown and HTML
-b compile Rmd file and display HTML file in browser
-t tangle Rmd file
EOF
}
while getopts ":hcbt" o; do
case $o in
h)
usage
exit 1
;;
c)
compile=1
;;
b)
browser=1
;;
t)
tangle=1
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
if [ -r "$1" ]; then
mdfile="$1"
mdfile="${mdfile%.*}" # remove extension
if [[ $compile = 1 ]]; then
(
Rscript -e "require(knitr); require(markdown); knit('${mdfile}.rmd', quiet=TRUE); \
markdownToHTML('${mdfile}.md', '${mdfile}.html')"
) > /dev/null 2>&1
fi
if [[ $browser = 1 ]]; then
(
Rscript -e "require(knitr); require(markdown); knit('${mdfile}.rmd', quiet=TRUE); \
markdownToHTML('${mdfile}.md', '${mdfile}.html'); browseURL('${mdfile}.html')"
) > /dev/null 2>&1
fi
if [[ $tangle = 1 ]]; then
(
Rscript -e "require(knitr); purl('${mdfile}.rmd')"
) > /dev/null 2>&1
fi
else
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment