| 1 |
#' Engines of other languages |
| 2 |
#' |
| 3 |
#' This object controls how to execute the code from languages other than R |
| 4 |
#' (when the chunk option \code{engine} is not \code{'R'}). Each component in |
| 5 |
#' this object is a function that takes a list of current chunk options |
| 6 |
#' (including the source code) and returns a character string to be written into |
| 7 |
#' the output. |
| 8 |
#' |
| 9 |
#' The engine function has one argument \code{options}: the source code of the |
| 10 |
#' current chunk is in \code{options$code}. Usually we can call external |
| 11 |
#' programs to run the code via \code{\link{system2}}. Other chunk options are |
| 12 |
#' also contained in this argument, e.g. \code{options$echo} and |
| 13 |
#' \code{options$eval}, etc. |
| 14 |
#' |
| 15 |
#' In most cases, \code{options$engine} can be directly used in command line to |
| 16 |
#' execute the code, e.g. \code{python} or \code{ruby}, but sometimes we may |
| 17 |
#' want to specify the path of the engine program, in which case we can pass it |
| 18 |
#' through the \code{engine.path} option. For example, \code{engine='ruby', |
| 19 |
#' engine.path='/usr/bin/ruby1.9.1'}. Additional command line arguments can be |
| 20 |
#' passed through \code{options$engine.opts}, e.g. \code{engine='ruby', |
| 21 |
#' engine.opts='-v'}. |
| 22 |
#' |
| 23 |
#' See \code{str(knitr::knit_engines$get())} for a list of built-in language |
| 24 |
#' engines. |
| 25 |
#' @export |
| 26 |
#' @note The Leiningen engine \code{lein} requires lein-exec plugin; see |
| 27 |
#' \url{https://github.com/yihui/knitr/issues/1176} for details. |
| 28 |
#' @references Usage: \url{https://yihui.org/knitr/objects/}; examples: |
| 29 |
#' \url{https://yihui.org/knitr/demo/engines/} |
| 30 |
#' @examples knit_engines$get('python'); knit_engines$get('awk') |
| 31 |
#' names(knit_engines$get()) |
| 32 |
knit_engines = new_defaults() |
| 33 |
|
| 34 |
|
| 35 |
#' Cache engines of other languages |
| 36 |
#' |
| 37 |
#' This object controls how to load cached environments from languages other |
| 38 |
#' than R (when the chunk option \code{engine} is not \code{'R'}). Each |
| 39 |
#' component in this object is a function that takes the current path to the |
| 40 |
#' chunk cache and loads it into the language environment. |
| 41 |
#' |
| 42 |
#' The cache engine function has one argument \code{options}, a list containing |
| 43 |
#' all chunk options. Note that \code{options$hash} is the path to the current |
| 44 |
#' chunk cache with the chunk's hash, but without any file extension, and the |
| 45 |
#' language engine may write a cache database to this path (with an extension). |
| 46 |
#' |
| 47 |
#' The cache engine function should load the cache environment and should know |
| 48 |
#' the extension appropriate for the language. |
| 49 |
#' @references See \url{https://github.com/rstudio/reticulate/pull/167} for an |
| 50 |
#' implementation of a cache engine for Python. |
| 51 |
#' @export |
| 52 |
cache_engines = new_defaults() |
| 53 |
|
| 54 |
#' An output wrapper for language engine output |
| 55 |
#' |
| 56 |
#' If you have designed a language engine, you may call this function in the end |
| 57 |
#' to format and return the text output from your engine. |
| 58 |
#' |
| 59 |
#' For expert users, an advanced usage of this function is |
| 60 |
#' \code{engine_output(options, out = LIST)} where \code{LIST} is a list that |
| 61 |
#' has the same structure as the output of \code{evaluate::evaluate()}. In this |
| 62 |
#' case, the arguments \code{code} and \code{extra} are ignored, and the list is |
| 63 |
#' passed to \code{knitr::sew()} to return a character vector of final output. |
| 64 |
#' @param options A list of chunk options. Usually this is just the object |
| 65 |
#' \code{options} passed to the engine function; see |
| 66 |
#' \code{\link{knit_engines}}. |
| 67 |
#' @param code Source code of the chunk, to which the output hook \code{source} |
| 68 |
#' is applied, unless the chunk option \code{echo} is \code{FALSE}. |
| 69 |
#' @param out Text output from the engine, to which the hook \code{output} is |
| 70 |
#' applied, unless the chunk option \code{results} is \code{'hide'} |
| 71 |
#' @param extra Any additional text output that you want to include. |
| 72 |
#' @return A character string generated from the source code and output using |
| 73 |
#' the appropriate output hooks. |
| 74 |
#' @export |
| 75 |
#' @examples library(knitr) |
| 76 |
#' engine_output(opts_chunk$merge(list(engine = 'Rscript')), code = '1 + 1', out = '[1] 2') |
| 77 |
#' engine_output(opts_chunk$merge(list(echo = FALSE, engine = 'Rscript')), code = '1 + 1', out = '[1] 2') |
| 78 |
#' |
| 79 |
#' # expert use only |
| 80 |
#' engine_output(opts_chunk$merge(list(engine = 'python')), out = list(structure(list(src = '1 + 1'), class = 'source'), '2')) |
| 81 |
engine_output = function(options, code, out, extra = NULL) { |
| 82 |
if (missing(code) && is.list(out)) return(unlist(sew(out, options))) |
| 83 |
if (!is.logical(options$echo)) code = code[options$echo] |
| 84 |
if (length(code) != 1L) code = one_string(code) |
| 85 |
if (options$engine == 'sas' && length(out) > 1L && !grepl('[[:alnum:]]', out[2])) |
| 86 |
out = tail(out, -3L) |
| 87 |
if (length(out) != 1L) out = one_string(out) |
| 88 |
out = sub('([^\n]+)$', '\\1\n', out) |
| 89 |
if (options$engine == 'stata') { |
| 90 |
out = gsub('\n+running.*profile\\.do', '', out) |
| 91 |
out = sub('\\.\\.\\.\n+', '', out) |
| 92 |
out = sub('\n\\. \nend of do-file\n', '', out) |
| 93 |
} |
| 94 |
one_string(c( |
| 95 |
if (length(options$echo) > 1L || options$echo) knit_hooks$get('source')(code, options), |
| 96 |
if (options$results != 'hide' && !is_blank(out)) { |
| 97 |
if (options$engine == 'highlight') out else sew.character(out, options) |
| 98 |
}, |
| 99 |
extra |
| 100 |
)) |
| 101 |
} |
| 102 |
|
| 103 |
## command-line tools |
| 104 |
eng_interpreted = function(options) { |
| 105 |
engine = options$engine |
| 106 |
code = if (engine %in% c('highlight', 'Rscript', 'sas', 'haskell', 'stata')) { |
| 107 |
f = wd_tempfile(engine, switch(engine, sas = '.sas', Rscript = '.R', stata = '.do', '.txt')) |
| 108 |
write_utf8(c(switch( |
| 109 |
engine, |
| 110 |
sas = "OPTIONS NONUMBER NODATE PAGESIZE = MAX FORMCHAR = '|----|+|---+=|-/<>*' FORMDLIM=' ';title;", |
| 111 |
NULL |
| 112 |
), options$code), f) |
| 113 |
on.exit(unlink(f), add = TRUE) |
| 114 |
switch( |
| 115 |
engine, |
| 116 |
haskell = paste('-e', shQuote(paste(':script', f))), |
| 117 |
sas = { |
| 118 |
logf = sub('[.]sas$', '.lst', f) |
| 119 |
on.exit(unlink(c(logf, sub('[.]sas$', '.log', f))), add = TRUE) |
| 120 |
f |
| 121 |
}, |
| 122 |
stata = { |
| 123 |
logf = sub('[.]do$', '.log', f) |
| 124 |
on.exit(unlink(c(logf)), add = TRUE) |
| 125 |
sprintf(switch( |
| 126 |
Sys.info()[['sysname']], |
| 127 |
Windows = '/q /e do %s', |
| 128 |
Darwin = paste('-q < %s >', shQuote(xfun::normalize_path(logf))), |
| 129 |
Linux = '-q -e do %s', |
| 130 |
'-q -b do %s' |
| 131 |
), shQuote(normalizePath(f))) |
| 132 |
}, |
| 133 |
f |
| 134 |
) |
| 135 |
} else paste(switch( |
| 136 |
engine, bash = '-c', coffee = '-e', groovy = '-e', lein = 'exec -ep', |
| 137 |
mysql = '-e', node = '-e', octave = '--eval', perl = '-E', php = '-r', |
| 138 |
psql = '-c', python = '-c', ruby = '-e', scala = '-e', sh = '-c', zsh = '-c', |
| 139 |
NULL |
| 140 |
), shQuote(one_string(options$code))) |
| 141 |
|
| 142 |
opts = get_engine_opts(options$engine.opts, engine) |
| 143 |
# FIXME: for these engines, the correct order is options + code + file |
| 144 |
code = if (engine %in% c('awk', 'gawk', 'sed', 'sas', 'psql', 'mysql')) |
| 145 |
paste(code, opts) else paste(opts, code) |
| 146 |
cmd = get_engine_path(options$engine.path, engine) |
| 147 |
out = if (options$eval) { |
| 148 |
if (options$message) message('running: ', cmd, ' ', code) |
| 149 |
tryCatch( |
| 150 |
system2(cmd, code, stdout = TRUE, stderr = TRUE, env = options$engine.env), |
| 151 |
error = function(e) { |
| 152 |
if (!options$error) stop(e) |
| 153 |
paste('Error in running command', cmd) |
| 154 |
} |
| 155 |
) |
| 156 |
} else '' |
| 157 |
# chunk option error=FALSE means we need to signal the error |
| 158 |
if (!options$error && !is.null(attr(out, 'status'))) stop(one_string(out)) |
| 159 |
if (options$eval && engine %in% c('sas', 'stata') && file.exists(logf)) |
| 160 |
out = c(read_utf8(logf), out) |
| 161 |
engine_output(options, options$code, out) |
| 162 |
} |
| 163 |
|
| 164 |
# options$engine.path can be list(name1 = path1, name2 = path2, ...); similarly, |
| 165 |
# options$engine.opts can be list(name1 = opts1, ...) |
| 166 |
get_engine_opts = function(opts, engine, fallback = '') { |
| 167 |
if (is.list(opts)) opts = opts[[engine]] |
| 168 |
opts %n% fallback |
| 169 |
} |
| 170 |
|
| 171 |
get_engine_path = function(path, engine, fallback = engine) { |
| 172 |
get_engine_opts(path, engine, fallback) |
| 173 |
} |
| 174 |
|
| 175 |
# execute an arbitrary command (optionally with arguments) |
| 176 |
# engine.opts = list(command, input, ext, clean, args, args1, args2) |
| 177 |
eng_exec = function(options) { |
| 178 |
opts = options$engine.opts |
| 179 |
if (!is.character(cmd <- opts$command %n% options$command)) stop( |
| 180 |
"The command of the 'exec' engine must be a character string." |
| 181 |
) |
| 182 |
cmd = get_engine_path(options$engine.path, options$engine, cmd) |
| 183 |
input = function(code, file) { |
| 184 |
write_utf8(code, file) |
| 185 |
file |
| 186 |
} |
| 187 |
if (is.character(i0 <- opts$input)) |
| 188 |
opts$input = function(code, file) input(code, i0) |
| 189 |
# turn all chunk options into function except 'command' |
| 190 |
opts = list_fun(opts, setdiff(names(opts), 'command')) |
| 191 |
|
| 192 |
# default options |
| 193 |
opts2 = list( |
| 194 |
ext = identity, input = input, args = function(code, file) { |
| 195 |
file |
| 196 |
}, clean = function(file) { |
| 197 |
unlink(file) |
| 198 |
}, args1 = function() NULL, args2 = function() NULL, |
| 199 |
output = function(options, code, output, file) { |
| 200 |
engine_output(options, code, output) |
| 201 |
} |
| 202 |
) |
| 203 |
|
| 204 |
opts = merge_list(opts2, opts) |
| 205 |
cmd2 = basename(cmd) # in case command is a full path |
| 206 |
ext = opts$ext(cmd2) # file extension |
| 207 |
f = wd_tempfile(cmd2, paste0('.', ext)) |
| 208 |
if (is.function(opts$clean)) on.exit(opts$clean(f), add = TRUE) |
| 209 |
f = opts$input(options$code, f) |
| 210 |
a = c(opts$args1(), opts$args(options$code, f), opts$args2()) |
| 211 |
|
| 212 |
out = if (options$eval) { |
| 213 |
if (options$message) message('running: ', paste(c(cmd, a), collapse = ' ')) |
| 214 |
f2 = wd_tempfile(cmd2) # capture stderr |
| 215 |
on.exit(unlink(f2), add = TRUE) |
| 216 |
tryCatch({ |
| 217 |
res = (if (options$error) suppressWarnings else identity)( |
| 218 |
system2(cmd, shQuote(a), stdout = TRUE, stderr = f2, env = options$engine.env) |
| 219 |
) |
| 220 |
# check error in the content run |
| 221 |
if (!is.null(attr(res, 'status')) && file.exists(f2) && file.size(f2) > 0) { |
| 222 |
e = readLines(f2) # f2 may not be UTF-8 |
| 223 |
if (!options$error) stop(one_string(e)) else e |
| 224 |
} else { |
| 225 |
res |
| 226 |
} |
| 227 |
}, error = function(e) { |
| 228 |
# error in the command run |
| 229 |
if (!options$error) stop(e) |
| 230 |
paste('Error in running command', cmd) |
| 231 |
} |
| 232 |
) |
| 233 |
} else '' |
| 234 |
# chunk option error=FALSE means we need to signal the error |
| 235 |
if (!options$error && !is.null(attr(out, 'status'))) stop(one_string(out)) |
| 236 |
options = set_lang(options, eng2lang(xfun::sans_ext(cmd2))) |
| 237 |
opts$output(options, options$code, out, f) |
| 238 |
} |
| 239 |
|
| 240 |
# turn elements of a list into functions: if an element is not a function, make |
| 241 |
# it a function that returns the non-function value |
| 242 |
list_fun = function(x, which = names(x)) { |
| 243 |
for (i in which) { |
| 244 |
if (!is.function(v <- x[[i]])) x[[i]] = local({ |
| 245 |
# a trick to avoid R's lazy evaluation (make a copy of v) |
| 246 |
v2 = v; function(...) v2 |
| 247 |
}) |
| 248 |
} |
| 249 |
x |
| 250 |
} |
| 251 |
|
| 252 |
## C, C++, and Fortran (via R CMD SHLIB) |
| 253 |
eng_shlib = function(options) { |
| 254 |
n = switch(options$engine, c = 'c', cc = 'cc', fortran = 'f', fortran95 = 'f95') |
| 255 |
f = wd_tempfile(n, paste0('.', n)) |
| 256 |
write_utf8(options$code, f) |
| 257 |
on.exit(unlink(c(f, with_ext(f, c('o', 'so', 'dll')))), add = TRUE) |
| 258 |
if (options$eval) { |
| 259 |
out = system(paste('R CMD SHLIB', f), intern = TRUE) |
| 260 |
dyn.load(sub(sprintf('[.]%s$', n), .Platform$dynlib.ext, f)) |
| 261 |
} else out = '' |
| 262 |
engine_output(options, options$code, out) |
| 263 |
} |
| 264 |
|
| 265 |
## Python |
| 266 |
eng_python = function(options) { |
| 267 |
if (isFALSE(options$python.reticulate)) { |
| 268 |
eng_interpreted(options) |
| 269 |
} else { |
| 270 |
if (!loadable('reticulate')) warning2( |
| 271 |
"The 'python' engine in knitr requires the reticulate package. ", |
| 272 |
"If you do not want to use the reticulate package, set the chunk option ", |
| 273 |
"python.reticulate = FALSE." |
| 274 |
) |
| 275 |
reticulate::eng_python(options) |
| 276 |
} |
| 277 |
} |
| 278 |
|
| 279 |
cache_eng_python = function(options) { |
| 280 |
if (isFALSE(options$python.reticulate)) return() |
| 281 |
# TODO: change this hack to reticulate::cache_eng_python(options) after |
| 282 |
# https://github.com/rstudio/reticulate/pull/167 is merged and released |
| 283 |
if (!'cache_eng_python' %in% ls(asNamespace('reticulate'))) return() |
| 284 |
fun = getFromNamespace('cache_eng_python', 'reticulate') |
| 285 |
fun(options) |
| 286 |
} |
| 287 |
|
| 288 |
## Java |
| 289 |
# e.g. see http://cran.rstudio.com/package=jvmr |
| 290 |
|
| 291 |
## Rcpp |
| 292 |
eng_Rcpp = function(options) { |
| 293 |
sourceCpp = getFromNamespace('sourceCpp', 'Rcpp') |
| 294 |
|
| 295 |
code = one_string(options$code) |
| 296 |
# engine.opts is a list of arguments to be passed to Rcpp function, e.g. |
| 297 |
# engine.opts=list(plugin='RcppArmadillo') |
| 298 |
opts = options$engine.opts |
| 299 |
|
| 300 |
# use custom cacheDir for sourceCpp if it's supported |
| 301 |
cache = options$cache && ('cacheDir' %in% names(formals(sourceCpp))) |
| 302 |
if (cache) { |
| 303 |
opts$cacheDir = paste(valid_path(options$cache.path, options$label), 'sourceCpp', sep = '_') |
| 304 |
opts$cleanupCacheDir = TRUE |
| 305 |
} |
| 306 |
|
| 307 |
if (!is.environment(opts$env)) opts$env = knit_global() # default env is knit_global() |
| 308 |
if (options$eval) { |
| 309 |
message('Building shared library for Rcpp code chunk...') |
| 310 |
do.call(sourceCpp, c(list(code = code), opts)) |
| 311 |
} |
| 312 |
|
| 313 |
engine_output(options, code, '') |
| 314 |
} |
| 315 |
|
| 316 |
## Julia |
| 317 |
eng_julia = function(options) { |
| 318 |
JuliaCall::eng_juliacall(options) |
| 319 |
} |
| 320 |
|
| 321 |
## Stan |
| 322 |
## Compiles Stan model in the code chunk, creates a stanmodel object, |
| 323 |
## and assigns it to a variable with the name given in engine.opts$x. |
| 324 |
eng_stan = function(options) { |
| 325 |
code = one_string(options$code) |
| 326 |
opts = options$engine.opts |
| 327 |
## name of the modelfit object returned by stan_model |
| 328 |
if (is.null(x <- options$output.var)) { |
| 329 |
warning("the option engine.opts$x is deprecated; use the chunk option output.var instead") |
| 330 |
x = opts$x |
| 331 |
} |
| 332 |
if (!is.character(x) || length(x) != 1L) stop( |
| 333 |
"the chunk option output.var must be a character string ", |
| 334 |
"providing a name for the returned `stanmodel` object." |
| 335 |
) |
| 336 |
opts$x = NULL |
| 337 |
if (options$eval) { |
| 338 |
message("Creating a 'stanmodel' object ", x) |
| 339 |
assign( |
| 340 |
x, |
| 341 |
do.call(getFromNamespace('stan_model', 'rstan'), c(list(model_code = code), opts)), |
| 342 |
envir = knit_global() |
| 343 |
) |
| 344 |
} |
| 345 |
engine_output(options, code, '') |
| 346 |
} |
| 347 |
|
| 348 |
## convert tikz string to PDF |
| 349 |
eng_tikz = function(options) { |
| 350 |
if (!options$eval) return(engine_output(options, options$code, '')) |
| 351 |
|
| 352 |
lines = read_utf8( |
| 353 |
options$engine.opts$template %n% system.file('misc', 'tikz2pdf.tex', package = 'knitr') |
| 354 |
) |
| 355 |
# add class options to template |
| 356 |
lines = insert_template( |
| 357 |
lines, '%% TIKZ_CLASSOPTION %%', options$engine.opts$classoption %n% 'tikz', TRUE |
| 358 |
) |
| 359 |
# insert code into preamble |
| 360 |
lines = insert_template( |
| 361 |
lines, '%% EXTRA_TIKZ_PREAMBLE_CODE %%', options$engine.opts$extra.preamble, TRUE |
| 362 |
) |
| 363 |
# insert tikz code into the tex template |
| 364 |
s = insert_template(lines, '%% TIKZ_CODE %%', options$code) |
| 365 |
write_utf8(s, texf <- wd_tempfile('tikz', '.tex')) |
| 366 |
on.exit(unlink(texf), add = TRUE) |
| 367 |
|
| 368 |
ext = dev2ext(options) |
| 369 |
|
| 370 |
to_svg = ext == 'svg' |
| 371 |
outf = if (to_svg) tinytex::latexmk(texf, 'latex') else tinytex::latexmk(texf) |
| 372 |
|
| 373 |
fig = fig_path(if (to_svg) '.dvi' else '.pdf', options) |
| 374 |
dir.create(dirname(fig), recursive = TRUE, showWarnings = FALSE) |
| 375 |
file.rename(outf, fig) |
| 376 |
|
| 377 |
fig2 = with_ext(fig, ext) |
| 378 |
if (to_svg) { |
| 379 |
# dvisvgm needs to be on the path |
| 380 |
# dvisvgm for windows needs ghostscript bin dir on the path also |
| 381 |
if (Sys.which('dvisvgm') == '') tinytex::tlmgr_install('dvisvgm') |
| 382 |
if (system2('dvisvgm', c( |
| 383 |
options$engine.opts$dvisvgm.opts, '-o', shQuote(fig2), fig |
| 384 |
)) != 0) stop('Failed to compile ', fig, ' to ', fig2) |
| 385 |
} else { |
| 386 |
# convert to the desired output-format using magick |
| 387 |
if (ext != 'pdf') magick::image_write(do.call(magick::image_convert, c( |
| 388 |
list(magick::image_read_pdf(fig), ext), options$engine.opts$convert.opts |
| 389 |
)), fig2) |
| 390 |
} |
| 391 |
fig = fig2 |
| 392 |
|
| 393 |
options$fig.num = 1L; options$fig.cur = 1L |
| 394 |
extra = run_hook_plot(fig, options) |
| 395 |
engine_output(options, options$code, '', extra) |
| 396 |
} |
| 397 |
|
| 398 |
## Commands that generate plots, e.g., GraphViz (dot), Asymptote, and Ditaa |
| 399 |
eng_plot = function(options) { |
| 400 |
options$command = cmd = options$engine |
| 401 |
options$fig.ext = ext = dev2ext(options) |
| 402 |
opts = list( |
| 403 |
output = function(options, code, output, file) { |
| 404 |
extra = if (options$eval) { |
| 405 |
# move the generated plot (with a temp filename) to fig.path |
| 406 |
f1 = with_ext(file, ext) |
| 407 |
f2 = paste(fig_path(), ext, sep = '.') |
| 408 |
xfun::dir_create(dirname(f2)) |
| 409 |
unlink(f2) |
| 410 |
file.rename(f1, f2) |
| 411 |
options$fig.num = 1L; options$fig.cur = 1L |
| 412 |
run_hook_plot(f2, options) |
| 413 |
} |
| 414 |
engine_output(options, code, '', extra) |
| 415 |
}, |
| 416 |
# better default for ditaa: https://github.com/yihui/knitr/pull/2092 |
| 417 |
args1 = if (cmd == 'ditta') c('-s', 2, '-T', '-S', '-E'), |
| 418 |
args = function(code, file) { |
| 419 |
f2 = with_ext(file, ext) |
| 420 |
if (cmd == 'ditaa') return(c(file, f2)) |
| 421 |
if (cmd %in% c('dot', 'asy')) { |
| 422 |
c(file, c(dot = '-T', asy = '-f')[cmd], ext, '-o', f2) |
| 423 |
} |
| 424 |
}) |
| 425 |
options$engine.opts = merge_list(opts, options$engine.opts) |
| 426 |
eng_exec(options) |
| 427 |
} |
| 428 |
|
| 429 |
## Andre Simon's highlight |
| 430 |
eng_highlight = function(options) { |
| 431 |
# e.g. engine.opts can be '-S matlab -O latex' |
| 432 |
if (is.null(options$engine.opts)) options$engine.opts = '-S text' |
| 433 |
options$engine.opts[1L] = paste('-f', options$engine.opts[1L]) |
| 434 |
options$echo = FALSE; options$results = 'asis' # do not echo source code |
| 435 |
res = eng_interpreted(options) |
| 436 |
if (out_format('latex')) { |
| 437 |
highlight_header() |
| 438 |
sub('(.*)\\\\\\\\(.*)', '\\1\\2', res) |
| 439 |
} else res |
| 440 |
} |
| 441 |
|
| 442 |
## save the code |
| 443 |
eng_cat = function(options) { |
| 444 |
cat2 = function(..., file = '', sep = '\n', lang = NULL) { |
| 445 |
# do not write to stdout like the default behavior of cat() |
| 446 |
if (!identical(file, '')) cat(..., file = file, sep = sep) |
| 447 |
} |
| 448 |
if (options$eval) |
| 449 |
do.call(cat2, c(list(options$code), options$engine.opts)) |
| 450 |
|
| 451 |
options = set_lang(options, options$class.source) |
| 452 |
if (is.null(options$lang)) return('') |
| 453 |
engine_output(options, options$code, NULL) |
| 454 |
} |
| 455 |
|
| 456 |
## output the code without processing it |
| 457 |
eng_asis = function(options) { |
| 458 |
if (options$echo) one_string(options$code) |
| 459 |
} |
| 460 |
|
| 461 |
# write a block environment according to the output format |
| 462 |
eng_block = function(options) { |
| 463 |
if (isFALSE(options$echo)) return() |
| 464 |
code = one_string(options$code) |
| 465 |
to = pandoc_to() |
| 466 |
is_pandoc = !is.null(to) |
| 467 |
if (!is_pandoc) { |
| 468 |
# not in R Markdown v2 |
| 469 |
to = out_format() |
| 470 |
if (!(to %in% c('latex', 'html', 'markdown'))) to = NULL |
| 471 |
} |
| 472 |
if (is.null(to)) return(code) |
| 473 |
if (to == 'beamer') to = 'latex' |
| 474 |
if (is_html_output(to)) to = 'html' |
| 475 |
type = options$type |
| 476 |
if (is.null(type)) return(code) |
| 477 |
# convert the chunk content to HTML or LaTeX (ideally I only need to specify |
| 478 |
# the markdown extension, but it is not implemented yet for LaTeX: |
| 479 |
# https://github.com/jgm/pandoc/issues/2453) |
| 480 |
if (is_pandoc) code = pandoc_fragment(code, if (to == 'html') 'html4' else to) |
| 481 |
l1 = options$latex.options |
| 482 |
if (is.null(l1)) l1 = '' |
| 483 |
h2 = options$html.tag %n% 'div' |
| 484 |
h3 = options$html.before %n% '' |
| 485 |
h4 = options$html.after %n% '' |
| 486 |
# e.g. type = c(latex = 'marginfigure', html = 'marginnote') |
| 487 |
if (to %in% names(type)) type = type[to] |
| 488 |
# block level tags? this is an incomplete list, but should work for most cases |
| 489 |
if (to == 'html') if (h2 %in% c('div', 'p', 'blockquote')) { |
| 490 |
code = paste0('\n', code, '\n') |
| 491 |
} else { |
| 492 |
code = gsub('<p>', '<span style="display: block;">', code) |
| 493 |
code = gsub('</p>', '</span>', code) |
| 494 |
} |
| 495 |
switch( |
| 496 |
to, |
| 497 |
latex = sprintf('\\begin{%s}%s\n%s\n\\end{%s}', type, l1, code, type), |
| 498 |
html = sprintf('%s<%s class="%s">%s</%s>%s', h3, h2, type, code, h2, h4), |
| 499 |
code |
| 500 |
) |
| 501 |
} |
| 502 |
|
| 503 |
eng_block2 = function(options) { |
| 504 |
if (isFALSE(options$echo)) return() |
| 505 |
|
| 506 |
code = one_string(options$code); type = options$type |
| 507 |
if (is.null(type)) return(code) |
| 508 |
|
| 509 |
if (is.null(pandoc_to())) stop('The engine "block2" is for R Markdown only') |
| 510 |
|
| 511 |
l1 = options$latex.options |
| 512 |
if (is.null(l1)) l1 = '' |
| 513 |
# protect environment options because Pandoc may escape the characters like |
| 514 |
# {}; when encoded in integers, they won't be escaped, but will need to |
| 515 |
# restore them later; see bookdown:::restore_block2 |
| 516 |
if (l1 != '') l1 = paste( |
| 517 |
c('\\iffalse{', utf8ToInt(enc2utf8(l1)), '}\\fi{}'), collapse = '-' |
| 518 |
) |
| 519 |
h2 = options$html.tag %n% 'div' |
| 520 |
h3 = options$html.before %n% '' |
| 521 |
h4 = options$html.after %n% '' |
| 522 |
h5 = options$html.before2 %n% '' |
| 523 |
h6 = options$html.after2 %n% '' |
| 524 |
if (is_latex_output()) { |
| 525 |
h7 = h8 = '\n' |
| 526 |
} else { |
| 527 |
h7 = sprintf('<%s class="%s">', h2, type) |
| 528 |
h8 = sprintf('</%s>', h2) |
| 529 |
} |
| 530 |
|
| 531 |
sprintf( |
| 532 |
'\\BeginKnitrBlock{%s}%s%s%s%s%s%s%s%s\\EndKnitrBlock{%s}', |
| 533 |
type, l1, h3, h7, h5, code, h6, h8, h4, type |
| 534 |
) |
| 535 |
} |
| 536 |
|
| 537 |
# helper to create engines the wrap embedded html assets (e.g. css,js) |
| 538 |
eng_html_asset = function(prefix, postfix) { |
| 539 |
function(options) { |
| 540 |
out = if (options$eval && is_html_output()) { |
| 541 |
one_string(c(prefix, options$code, postfix)) |
| 542 |
} |
| 543 |
options$results = 'asis' |
| 544 |
engine_output(options, options$code, out) |
| 545 |
} |
| 546 |
} |
| 547 |
|
| 548 |
# include js in a script tag (ignore if not html output) |
| 549 |
eng_js = eng_html_asset('<script>', '</script>') |
| 550 |
|
| 551 |
# include css in a style tag (ignore if not html output) |
| 552 |
eng_css = eng_html_asset('<style type="text/css">', '</style>') |
| 553 |
|
| 554 |
# perform basic sql parsing to determine if a sql query is an update query |
| 555 |
is_sql_update_query = function(query) { |
| 556 |
query = one_string(query) |
| 557 |
# remove line comments |
| 558 |
query = gsub('^\\s*--.*\n', '', query) |
| 559 |
# remove multi-line comments |
| 560 |
if (grepl('^\\s*\\/\\*.*', query)) query = gsub('.*\\*\\/', '', query) |
| 561 |
grepl('^\\s*(INSERT|UPDATE|DELETE|CREATE|DROP|ALTER).*', query, ignore.case = TRUE) |
| 562 |
} |
| 563 |
|
| 564 |
# sql engine |
| 565 |
eng_sql = function(options) { |
| 566 |
# return chunk before interpolation eagerly to avoid connection option check |
| 567 |
if (isFALSE(options$eval) && !isTRUE(options$sql.show_interpolated)) { |
| 568 |
return(engine_output(options, options$code, '')) |
| 569 |
} |
| 570 |
|
| 571 |
# Return char vector of sql interpolation param names |
| 572 |
varnames_from_sql = function(conn, sql) { |
| 573 |
varPos = DBI::sqlParseVariables(conn, sql) |
| 574 |
if (length(varPos$start) > 0) { |
| 575 |
varNames = substring(sql, varPos$start, varPos$end) |
| 576 |
sub('^\\?', '', varNames) |
| 577 |
} |
| 578 |
} |
| 579 |
|
| 580 |
# Vectorized version of exists |
| 581 |
mexists = function(x, env = knit_global(), inherits = TRUE) { |
| 582 |
vapply(x, exists, logical(1), where = env, inherits = inherits) |
| 583 |
} |
| 584 |
|
| 585 |
# Interpolate a sql query based on the variables in an environment |
| 586 |
interpolate_from_env = function(conn, sql, env = knit_global(), inherits = TRUE) { |
| 587 |
names = unique(varnames_from_sql(conn, sql)) |
| 588 |
names_missing = names[!mexists(names, env, inherits)] |
| 589 |
if (length(names_missing) > 0) { |
| 590 |
stop("Object(s) not found: ", paste('"', names_missing, '"', collapse = ", ")) |
| 591 |
} |
| 592 |
|
| 593 |
args = if (length(names) > 0) setNames( |
| 594 |
mget(names, envir = env, inherits = inherits), names |
| 595 |
) |
| 596 |
|
| 597 |
do.call(DBI::sqlInterpolate, c(list(conn, sql), args)) |
| 598 |
} |
| 599 |
|
| 600 |
# extract options |
| 601 |
conn = options$connection |
| 602 |
if (is.character(conn)) conn = get(conn, envir = knit_global()) |
| 603 |
if (is.null(conn)) stop2( |
| 604 |
"The 'connection' option (DBI connection) is required for sql chunks." |
| 605 |
) |
| 606 |
varname = options$output.var |
| 607 |
max.print = options$max.print %n% (opts_knit$get('sql.max.print') %n% 10) |
| 608 |
if (is.na(max.print) || is.null(max.print)) |
| 609 |
max.print = -1 |
| 610 |
sql = one_string(options$code) |
| 611 |
params = options$params |
| 612 |
|
| 613 |
query = interpolate_from_env(conn, sql) |
| 614 |
if (isFALSE(options$eval)) return(engine_output(options, query, '')) |
| 615 |
|
| 616 |
data = tryCatch({ |
| 617 |
if (is_sql_update_query(query)) { |
| 618 |
DBI::dbExecute(conn, query) |
| 619 |
NULL |
| 620 |
} else if (is.null(varname) && max.print > 0) { |
| 621 |
# execute query -- when we are printing with an enforced max.print we |
| 622 |
# use dbFetch so as to only pull down the required number of records |
| 623 |
res = DBI::dbSendQuery(conn, query) |
| 624 |
data = DBI::dbFetch(res, n = max.print) |
| 625 |
DBI::dbClearResult(res) |
| 626 |
data |
| 627 |
|
| 628 |
} else { |
| 629 |
if (length(params) == 0) { |
| 630 |
DBI::dbGetQuery(conn, query) |
| 631 |
} else { |
| 632 |
# If params option is provided, parameters are not interplolated |
| 633 |
DBI::dbGetQuery(conn, sql, params = params) |
| 634 |
} |
| 635 |
} |
| 636 |
}, error = function(e) { |
| 637 |
if (!options$error) stop(e) |
| 638 |
e |
| 639 |
}) |
| 640 |
|
| 641 |
if (inherits(data, "error")) |
| 642 |
return(engine_output(options, query, one_string(data))) |
| 643 |
|
| 644 |
# create output if needed (we have data and we aren't assigning it to a variable) |
| 645 |
output = if (length(dim(data)) == 2 && ncol(data) > 0 && is.null(varname)) capture.output({ |
| 646 |
|
| 647 |
# apply max.print to data |
| 648 |
display_data = if (max.print == -1) data else head(data, n = max.print) |
| 649 |
|
| 650 |
# get custom sql print function |
| 651 |
sql.print = opts_knit$get('sql.print') |
| 652 |
|
| 653 |
# use kable for markdown |
| 654 |
if (!is.null(sql.print)) { |
| 655 |
options$results = 'asis' |
| 656 |
cat(sql.print(data)) |
| 657 |
} else if (out_format('markdown')) { |
| 658 |
|
| 659 |
# we are going to output raw markdown so set results = 'asis' |
| 660 |
options$results = 'asis' |
| 661 |
|
| 662 |
# force left alignment if the first column is an incremental id column |
| 663 |
is_id = function(x) { |
| 664 |
is.numeric(x) && length(x) > 1 && !anyNA(x) && all(diff(x) == 1) |
| 665 |
} |
| 666 |
if (is_id(display_data[[1]])) display_data[[1]] = as.character(display_data[[1]]) |
| 667 |
|
| 668 |
# wrap html output in a div so special styling can be applied |
| 669 |
add_div = is_html_output() && getOption('knitr.sql.html_div', TRUE) |
| 670 |
if (add_div) cat('<div class="knitsql-table">\n') |
| 671 |
|
| 672 |
# determine records caption |
| 673 |
caption = options$tab.cap |
| 674 |
if (is.null(caption)) { |
| 675 |
rows = nrow(data) |
| 676 |
rows_formatted = formatC(rows, format = "d", big.mark = ',') |
| 677 |
caption = if (max.print == -1 || rows < max.print) { |
| 678 |
paste(rows_formatted, "records") |
| 679 |
} else { |
| 680 |
paste("Displaying records 1 -", rows_formatted) |
| 681 |
} |
| 682 |
} |
| 683 |
# disable caption |
| 684 |
if (identical(caption, NA)) caption = NULL |
| 685 |
|
| 686 |
# print using kable |
| 687 |
print(kable(display_data, caption = caption)) |
| 688 |
|
| 689 |
# terminate div |
| 690 |
if (add_div) cat("\n</div>\n") |
| 691 |
|
| 692 |
# otherwise use tibble if it's available |
| 693 |
} else if (loadable('tibble')) { |
| 694 |
print(tibble::as_tibble(display_data), n = max.print) |
| 695 |
|
| 696 |
} else print(display_data) # fallback to standard print |
| 697 |
}) |
| 698 |
if (options$results == 'hide') output = NULL |
| 699 |
|
| 700 |
# assign varname if requested |
| 701 |
if (!is.null(varname)) assign(varname, data, envir = knit_global()) |
| 702 |
|
| 703 |
# reset query to pre-interpolated if not expanding |
| 704 |
if (!isTRUE(options$sql.show_interpolated)) query <- options$code |
| 705 |
|
| 706 |
# return output |
| 707 |
engine_output(options, query, output) |
| 708 |
} |
| 709 |
|
| 710 |
# go engine, added by @hodgesds https://github.com/yihui/knitr/pull/1330 |
| 711 |
eng_go = function(options) { |
| 712 |
f = wd_tempfile('code', '.go') |
| 713 |
write_utf8(code <- options$code, f) |
| 714 |
on.exit(unlink(f), add = TRUE) |
| 715 |
cmd = get_engine_path(options$engine.path, options$engine) |
| 716 |
|
| 717 |
fmt_args = sprintf('fmt %s', f) |
| 718 |
|
| 719 |
tryCatch( |
| 720 |
system2(cmd, fmt_args, stdout = TRUE, stderr = TRUE, env = options$engine.env), |
| 721 |
error = function(e) { |
| 722 |
if (!options$error) stop(e) |
| 723 |
} |
| 724 |
) |
| 725 |
|
| 726 |
run_args = sprintf(" run %s", f) |
| 727 |
|
| 728 |
extra = if (options$eval) { |
| 729 |
message('running: ', cmd, run_args) |
| 730 |
tryCatch( |
| 731 |
system2(cmd, run_args, stdout = TRUE, stderr = TRUE, env = options$engine.env), |
| 732 |
error = function(e) { |
| 733 |
if (!options$error) stop(e) |
| 734 |
'Error in executing go code' |
| 735 |
} |
| 736 |
) |
| 737 |
} |
| 738 |
|
| 739 |
if (options$results == 'hide') extra = NULL |
| 740 |
|
| 741 |
engine_output(options, code, extra) |
| 742 |
} |
| 743 |
|
| 744 |
# SASS / SCSS engine (contributed via https://github.com/yihui/knitr/pull/1666) |
| 745 |
# |
| 746 |
# Converts SASS / SCSS -> CSS (with same treatments as CSS engine) using either: |
| 747 |
# LibSass sass R package (https://github.com/rstudio/sass) when |
| 748 |
# + the package is installed |
| 749 |
# + engine.opts does not set package = FALSE (e.g. engine.opts = list(package = FALSE)) |
| 750 |
# + an explicit path to the executable is not provided through engine.path, or |
| 751 |
# dart-sass standalone executable (https://sass-lang.com/install) otherwise |
| 752 |
# |
| 753 |
# CSS output is compressed by default but formatting can be set through style in engine.opts |
| 754 |
# For the sass R package, valid styles are "compressed","expanded", "nested", and "compact" |
| 755 |
# For the executable, valid styles are "compressed" and "expanded" |
| 756 |
# Please refer to respective package / executable documentation for more details |
| 757 |
eng_sxss = function(options) { |
| 758 |
|
| 759 |
# early exit if evaluated output not requested |
| 760 |
options$results = 'asis' |
| 761 |
if (!options$eval) return(engine_output(options, options$code, '')) |
| 762 |
|
| 763 |
# create temporary file with input code |
| 764 |
f = wd_tempfile('code', paste0('.', options$engine)) |
| 765 |
xfun::write_utf8(options$code , f) |
| 766 |
on.exit(unlink(f), add = TRUE) |
| 767 |
|
| 768 |
# process provided engine options |
| 769 |
package = options$engine.opts$package %n% TRUE |
| 770 |
style = options$engine.opts$style %n% "compressed" |
| 771 |
cmd = get_engine_path(options$engine.path, "sass") |
| 772 |
|
| 773 |
use_package = loadable("sass") && package && cmd == "sass" |
| 774 |
|
| 775 |
style = match.arg(style, c("compressed", "expanded", if (use_package) c("compact", "nested"))) |
| 776 |
# convert sass/sxss -> css |
| 777 |
if (use_package) { |
| 778 |
message("Converting with the R package sass") |
| 779 |
|
| 780 |
sass_fun = options$engine.opts$sass_fun %n% sass::sass |
| 781 |
out = tryCatch( |
| 782 |
sass_fun(sass::sass_file(f), options = sass::sass_options(output_style = style)), |
| 783 |
error = function(e) { |
| 784 |
if (!options$error) stop(e) |
| 785 |
warning2(paste('Error in converting to CSS using sass R package:', e, sep = "\n")) |
| 786 |
NULL |
| 787 |
} |
| 788 |
) |
| 789 |
|
| 790 |
# remove final newline chars from output |
| 791 |
if (!is.null(out)) out = sub("\\n$", "", out) |
| 792 |
} else { |
| 793 |
message("Converting sass with ", cmd) |
| 794 |
style = paste0("--style=", style) |
| 795 |
|
| 796 |
# attempt execution of sass |
| 797 |
out = tryCatch( |
| 798 |
system2(cmd, args = c(f, style), stdout = TRUE, stderr = TRUE), |
| 799 |
error = function(e) { |
| 800 |
if (!options$error) stop2(e) |
| 801 |
warning2(paste('Error in converting to CSS using executable:', e, sep = "\n")) |
| 802 |
NULL |
| 803 |
} |
| 804 |
) |
| 805 |
|
| 806 |
# handle execution errors (status codes) |
| 807 |
if (!is.null(attr(out, 'status')) && !options$error) stop2(one_string(out)) |
| 808 |
} |
| 809 |
|
| 810 |
# wrap final output for correct rendering |
| 811 |
final_out = if (!is.null(out) && is_html_output(excludes = 'markdown')) { |
| 812 |
one_string(c('<style type="text/css">', out, '</style>')) |
| 813 |
} |
| 814 |
|
| 815 |
engine_output(options, options$code, final_out) |
| 816 |
} |
| 817 |
|
| 818 |
eng_bslib = function(options) { |
| 819 |
if (!loadable("bslib")) { |
| 820 |
stop2("The 'bslib' package must be installed in order for the knitr engine 'bslib' to work.") |
| 821 |
} |
| 822 |
if (!is.null(options$engine.opts$sass_fun)) { |
| 823 |
stop2("The 'bslib' knitr engine does not allow for customization of the Sass compilation function.") |
| 824 |
} |
| 825 |
func = sass::sass_partial |
| 826 |
formals(func)$bundle = quote(bslib::bs_global_get()) |
| 827 |
options$engine.opts$sass_fun = func |
| 828 |
eng_sxss(options) |
| 829 |
} |
| 830 |
|
| 831 |
# Target Markdown engine contributed by @wlandau |
| 832 |
# Thread: https://github.com/ropensci/targets/issues/503 |
| 833 |
# Usage: https://books.ropensci.org/targets/markdown.html |
| 834 |
# Docs: https://docs.ropensci.org/targets/reference/tar_engine_knitr.html |
| 835 |
eng_targets = function(options) { |
| 836 |
targets::tar_engine_knitr(options) |
| 837 |
} |
| 838 |
|
| 839 |
# an Eviews engine based on EviewsR |
| 840 |
eng_eviews = function(options) { |
| 841 |
# EviewsR can't be installed in lower versions of R, hence I can't declare |
| 842 |
# Suggests dependency in DESCRIPTION |
| 843 |
f = getFromNamespace('eng_eviews', 'EviewsR') |
| 844 |
f(options) |
| 845 |
} |
| 846 |
|
| 847 |
# a comment engine to return nothing |
| 848 |
eng_comment = function(options) {} |
| 849 |
|
| 850 |
# a verbatim engine that returns its chunk content verbatim |
| 851 |
eng_verbatim = function(options) { |
| 852 |
# change default for the cat engine |
| 853 |
options$eval = FALSE |
| 854 |
options = set_lang(options) |
| 855 |
eng_cat(options) |
| 856 |
} |
| 857 |
|
| 858 |
set_lang = function(options, default = 'default') { |
| 859 |
# specify the lang name in engine.opts = list(lang = ), or lang/language, |
| 860 |
# or class.source; if all are empty, use 'default' |
| 861 |
if (is.null(options$lang)) options$lang = options$engine.opts$lang %n% default |
| 862 |
options |
| 863 |
} |
| 864 |
|
| 865 |
# embed a file verbatim |
| 866 |
eng_embed = function(options) { |
| 867 |
# if `file` is empty, use `code` as the list of files |
| 868 |
if (is.null(f <- options$file)) { |
| 869 |
f = gsub('^["\']|["\']$', '', options$code) # in case paths are quoted |
| 870 |
if (length(f) == 0) return() |
| 871 |
options$code = xfun::read_all(f) |
| 872 |
} |
| 873 |
# use the filename extension as the default language name |
| 874 |
if (nchar(lang <- file_ext(f[1])) > 1) { |
| 875 |
lang = sub('^R', '', lang) # Rmd -> md, Rhtml -> html, etc. |
| 876 |
if (lang == 'nw') lang = 'tex' |
| 877 |
} |
| 878 |
options = set_lang(options, tolower(lang)) |
| 879 |
eng_verbatim(options) |
| 880 |
} |
| 881 |
|
| 882 |
# set engines for interpreted languages |
| 883 |
local({ |
| 884 |
for (i in c( |
| 885 |
'awk', 'bash', 'coffee', 'gawk', 'groovy', 'haskell', 'lein', 'mysql', |
| 886 |
'node', 'octave', 'perl', 'php', 'psql', 'Rscript', 'ruby', 'sas', |
| 887 |
'scala', 'sed', 'sh', 'stata', 'zsh' |
| 888 |
)) knit_engines$set(setNames(list(eng_interpreted), i)) |
| 889 |
}) |
| 890 |
|
| 891 |
# additional engines |
| 892 |
knit_engines$set( |
| 893 |
asis = eng_asis, |
| 894 |
asy = eng_plot, |
| 895 |
block = eng_block, |
| 896 |
block2 = eng_block2, |
| 897 |
bslib = eng_bslib, |
| 898 |
c = eng_shlib, |
| 899 |
cat = eng_cat, |
| 900 |
cc = eng_shlib, |
| 901 |
comment = eng_comment, |
| 902 |
css = eng_css, |
| 903 |
ditaa = eng_plot, |
| 904 |
dot = eng_plot, |
| 905 |
embed = eng_embed, |
| 906 |
eviews = eng_eviews, |
| 907 |
exec = eng_exec, |
| 908 |
fortran = eng_shlib, |
| 909 |
fortran95 = eng_shlib, |
| 910 |
go = eng_go, |
| 911 |
highlight = eng_highlight, |
| 912 |
js = eng_js, |
| 913 |
julia = eng_julia, |
| 914 |
python = eng_python, |
| 915 |
R = eng_r, |
| 916 |
Rcpp = eng_Rcpp, |
| 917 |
sass = eng_sxss, |
| 918 |
scss = eng_sxss, |
| 919 |
sql = eng_sql, |
| 920 |
stan = eng_stan, |
| 921 |
targets = eng_targets, |
| 922 |
tikz = eng_tikz, |
| 923 |
verbatim = eng_verbatim |
| 924 |
) |
| 925 |
|
| 926 |
cache_engines$set(python = cache_eng_python) |
| 927 |
|
| 928 |
get_engine = function(name) { |
| 929 |
fun = knit_engines$get(name) |
| 930 |
if (is.function(fun)) return(fun) |
| 931 |
warning( |
| 932 |
"Unknown language engine '", name, |
| 933 |
"' (must be registered via knit_engines$set())." |
| 934 |
) |
| 935 |
function(options) { |
| 936 |
engine_output(options, options$code, '') |
| 937 |
} |
| 938 |
} |
| 939 |
|
| 940 |
cache_engine = function(options) { |
| 941 |
cache_fun = cache_engines$get(options$engine) |
| 942 |
if (!is.function(cache_fun)) return() |
| 943 |
cache_fun(options) |
| 944 |
} |
| 945 |
|
| 946 |
# possible values for engines (for auto-completion in RStudio) |
| 947 |
opts_chunk_attr$engine = as.list(sort(c('R', names(knit_engines$get())))) |
| 948 |
opts_chunk_attr[c('engine.path', 'engine.opts')] = list('character', 'character') |