Define engines

These engines are made of two ingredients: the function formatR::tidy_source to format the code, and the function highr::hi_html to highlight the code.

engine_showscript <- function(options){
  tidycode <- formatR::tidy_source(
    source = options$script,
    indent = 2L
  )$text.tidy
  out <- c("<pre class='hl'>", highr::hi_html(tidycode), "</pre>")
  options$results <- "asis"
  options$echo <- FALSE
  knitr::engine_output(options, "", out)
}
knitr::knit_engines$set(showscript = engine_showscript)
engine_showfun <- function(options){
  body <- capture.output(eval(parse(text=options$fun)))
  if(substr(tail(body,1), 1, 4) == "<env"){
    body <- head(body,-1)
  }
  body[1] <- sprintf("%s <- %s", options$fun, body[1])
  tidycode <- formatR::tidy_source(text=body,
                                   indent=2)$text.tidy
  out <- c("<pre class='hl'>", highr::hi_html(tidycode), "</pre>")
  options$results <- "asis"
  options$echo <- FALSE
  knitr::engine_output(options, "", out)
}
knitr::knit_engines$set(showfun = engine_showfun)
<link rel='stylesheet' href='hl.css'/>

The content of this file is given at the end of this document. Of course you are free to modify the styles.

Demo showscript

Make an empty chunk with the option engine="showscript" and the option script set to the path of your script:

```{r, engine="showscript", script="path/to/script.R"}
```
# a function
f <- function(x) {
  return(x + 1)
}

# another function
g <- function(y) {
  z <- sqrt(y)
  return(z)
}

Demo showfun

For example:

```{r, engine="fun", fun="engine_showscript"}
```

Result:

engine_showscript <- function(options) {
  tidycode <- formatR::tidy_source(source = options$script, indent = 2L)$text.tidy
  out <- c("<pre class='hl'>", highr::hi_html(tidycode), "</pre>")
  options$results <- "asis"
  options$echo <- FALSE
  knitr::engine_output(options, "", out)
}

The css file

This is the content of the file hl.css:

body.hl { background-color:#e0eaee; }
pre.hl  { color:#000000; background-color:seaShell; font-size:10pt; font-family:'Courier New';}
.hl.num { color:#b07e00; }
.hl.esc { color:#ff00ff; }
.hl.str { color:#AB0000; }
.hl.pps { color:#818100; }
.hl.slc { color:#838183; font-style:italic; }
.hl.com { color:#514F51; font-style:italic; }
.hl.ppc { color:#008200; }
.hl.opt { color:#B95F0A; }
.hl.lin { color:#555555; }
.hl.kwa { color:#3A003A; font-weight:bold; }
.hl.kwb { color:#008000; }
.hl.kwc { color:#6F4827; font-weight:bold; }
.hl.kwd { color:#010181; font-weight:bold;}