Skip to content

Instantly share code, notes, and snippets.

@jrnold
Created April 23, 2012 06:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrnold/2469044 to your computer and use it in GitHub Desktop.
Save jrnold/2469044 to your computer and use it in GitHub Desktop.
knitr rendering for restructured text / sphinx
roptions

dev='png',highlight=FALSE

print(2 + 2)

cat("hello")

what is 2+2

library(stringr)
#' @rdname hook_plot
#' @export
hook_plot_rest <- function (x, options)
{
print(x)
## Use * and only first name of the plot?
y <- sprintf("\n.. image:: %s.*", x[1])
opts.str <- c()
if (!is.null(options$out.height)) {
opts.str <- c(opts.str,
sprintf(" :height: %s", options$out.height))
}
if (!is.null(options$out.width)) {
opts.str <- c(opts.str,
sprintf(" :width: %s", options$out.width))
}
paste(y, paste(opts.str, collapse="\n"), sep="\n")
}
#' @rdname output_hooks
#' @export
render_rest <- function() {
knit_hooks$restore()
opts_chunk$set(dev = 'png', highlight = FALSE)
hook.src <- function(x, options) {
c("\n\n::\n\n", knitr:::line_prompt(x, " ", " "), "\n")
}
hook.output <- function(x, options) {
if(knitr:::output_asis(x, options)) {
x
} else {
hook.src(x, options)
}
}
hook.warning <- hook.src
hook.error <- hook.src
hook.message <- hook.src
hook.inline <- function(x) {
if (inherits(x, 'AsIs')) {
'%s'
} else {
'``%s``'
}, knitr:::.inline.hook(x)
}
hook.plot <- hook_plot_rest
knit_hooks$set(source = hook.src,
output = hook.output,
warning = hook.warning,
error = hook.error,
message = hook.message,
inline = hook.inline,
plot = hook.plot)
}
#' @rdname output_hooks
#'
#' Variation on standard reStructured text that uses the code-block directive.
#'
#' @export
render_sphinx <- function() {
render_rest()
hook.src <- function(x, options) {
c(".. code-block:: r\n",
str_c("\n", knitr:::line_prompt(x, " ", " ")),
"\n")
}
knit_hooks$set(source = hook.src)
}
pat_rest <- function() {
pat <-
list(
chunk.begin = "^..\\s+<<(.*)>>=\\s*$",
chunk.end = "^..\\s+@\\s*$",
chunk.code = "^..",
ref.chunk = "^..\\s*<<(.*)>>\\s*$",
inline.code = ":R:`([^`]*)`",
global.options = ":roptions:\\s+([^\n]*)",
ref.label = "^## @knitr (.*)$")
knit_patterns$restore()
knit_patterns$set(pat)
}
pat_rest()
# render_rest()
render_sphinx()
@yihui
Copy link

yihui commented Apr 23, 2012

this is great; could you commit this to your forked repository? I have comments that I want to do them line by line. After that you can send me a pull request. Thanks!

@jrnold
Copy link
Author

jrnold commented Apr 23, 2012

Done. I added the changes to the branch "rest" in my forked repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment