| 1 |
new_env = function(...) new.env(..., parent = emptyenv()) |
| 2 |
|
| 3 |
#' Parse R Markdown or R scripts |
| 4 |
#' |
| 5 |
#' Parse input into code chunks, inline code expressions, and text fragments: |
| 6 |
#' [crack()] is for parsing R Markdown, and [sieve()] is for R scripts. |
| 7 |
#' |
| 8 |
#' For R Markdown, a code chunk must start with a fence of the form ```` |
| 9 |
#' ```{lang} ````, where `lang` is the language name, e.g., `r` or `python`. The |
| 10 |
#' body of a code chunk can start with chunk options written in "pipe comments", |
| 11 |
#' e.g., `#| eval = TRUE, echo = FALSE` (the CSV syntax) or `#| eval: true` (the |
| 12 |
#' YAML syntax). An inline code fragment is of the form `` `{lang} source` `` |
| 13 |
#' embedded in Markdown text. |
| 14 |
#' @inheritParams mark |
| 15 |
#' @export |
| 16 |
#' @return A list of code chunks and text blocks: |
| 17 |
#' |
| 18 |
#' - Code chunks are of the form `list(source, type = "code_chunk", options, |
| 19 |
#' comments, ...)`: `source` is a character vector of the source code of a |
| 20 |
#' code chunk, `options` is a list of chunk options, and `comments` is a |
| 21 |
#' vector of pipe comments. |
| 22 |
#' |
| 23 |
#' - Text blocks are of the form `list(source, type = "text_block", ...)`. If |
| 24 |
#' the text block does not contain any inline code, `source` will be a |
| 25 |
#' character string (lines of text concatenated by line breaks), otherwise it |
| 26 |
#' will be a list with members that are either character strings (normal text |
| 27 |
#' fragments) or lists of the form `list(source, options, ...)` (`source` is |
| 28 |
#' the inline code, and `options` contains its options specified inside `` |
| 29 |
#' `{lang, ...}` ``). |
| 30 |
#' |
| 31 |
#' Both code chunks and text blocks have a list member named `lines` that |
| 32 |
#' stores their starting and ending line numbers in the input. |
| 33 |
#' @examples |
| 34 |
#' library(litedown) |
| 35 |
#' # parse R Markdown |
| 36 |
#' res = crack(c('```{r}\n1+1\n```', 'Hello, `pi` = `{r} pi` and `e` = `{r} exp(1)`!')) |
| 37 |
#' str(res) |
| 38 |
#' # evaluate inline code and combine results with text fragments |
| 39 |
#' txt = lapply(res[[2]]$source, function(x) { |
| 40 |
#' if (is.character(x)) x else eval(parse(text = x$source)) |
| 41 |
#' }) |
| 42 |
#' paste(unlist(txt), collapse = '') |
| 43 |
crack = function(input, text = NULL) { |
| 44 |
text = read_input(input, text); input = attr(text, 'input') |
| 45 |
xml = commonmark::markdown_xml(text, sourcepos = TRUE) |
| 46 |
rx_engine = '([a-zA-Z0-9_]+)' # only allow these characters for engine names |
| 47 |
r = paste0( |
| 48 |
'<(code|code_block) sourcepos="(\\d+):(\\d+)-(\\d+):(\\d+)"( info="[{]+', |
| 49 |
rx_engine, '[^"]*?[}]")? xml:space="[^>]*>([^<]*)<' |
| 50 |
) |
| 51 |
m = match_all(xml, r, perl = TRUE)[[1]] %|% matrix(character(), 9) |
| 52 |
# code blocks must have non-empty info strings |
| 53 |
m = m[, m[2, ] != 'code_block' | m[8, ] != '', drop = FALSE] |
| 54 |
|
| 55 |
res = list() |
| 56 |
# add a block of text and the line range info |
| 57 |
add_block = function(l1, l2, ...) { |
| 58 |
res[[length(res) + 1]] <<- list(source = text[l1:l2], ..., lines = c(l1, l2)) |
| 59 |
res |
| 60 |
} |
| 61 |
|
| 62 |
n = length(text) |
| 63 |
i = 1L # the possible start line number of text blocks |
| 64 |
for (j in which(m[2, ] == 'code_block')) { |
| 65 |
# start (3) and end (5) line numbers for code chunks |
| 66 |
pos = as.integer(m[c(3, 5), j]); i1 = pos[1]; i2 = pos[2] |
| 67 |
# add the possible text block before the current code chunk |
| 68 |
if (i1 > i) add_block(i, i1 - 1L, type = 'text_block') |
| 69 |
# add the code chunk |
| 70 |
add_block(i1, i2, info = m[8, j], type = 'code_chunk') |
| 71 |
i = i2 + 1L # the earliest line for the next text block is next line |
| 72 |
} |
| 73 |
# if there are lines remaining, they must be a text block |
| 74 |
if (i <= n) add_block(i, n, type = 'text_block') |
| 75 |
|
| 76 |
if (!length(m)) return(res) |
| 77 |
|
| 78 |
set_error_handler(input) |
| 79 |
|
| 80 |
m = m[, m[2, ] == 'code', drop = FALSE] |
| 81 |
# find out inline code `{lang} expr` |
| 82 |
rx_inline = '^\\s*[{](.+?)[}]\\s+(.+?)\\s*$' |
| 83 |
# look for `r expr` if `{lang}` not found (for compatibility with knitr) |
| 84 |
if (!any(j <- grepl(rx_inline, m[9, ])) && getOption('litedown.enable.knitr_inline', FALSE)) { |
| 85 |
rx_inline = '^(r) +(.+?)\\s*$' |
| 86 |
j = grepl(rx_inline, m[9, ]) |
| 87 |
} |
| 88 |
m = m[, j, drop = FALSE] |
| 89 |
n_start = uapply(res, function(x) x$lines[1]) # starting line numbers |
| 90 |
j = findInterval(m[3, ], n_start) # find which block each inline code belongs to |
| 91 |
for (i in seq_len(ncol(m))) { |
| 92 |
b = res[[j[i]]]; l = b$lines |
| 93 |
# column position is based on bytes instead of chars; needs to be adjusted to the latter |
| 94 |
pos = char_pos(text, as.integer(m[3:6, i])) |
| 95 |
i1 = pos[1]; i2 = pos[3] |
| 96 |
# commonmark::markdown_xml(sourcepos = TRUE) gives wrong column info when |
| 97 |
# the line has leading spaces (which are ignored), so doublecheck here (in |
| 98 |
# theory we also need to consider the case i1 != i2 but that's a little too |
| 99 |
# complicated and may be rare, too) |
| 100 |
if (i1 == i2 && grepl('^\\s+', ti <- text[i1])) { |
| 101 |
mi = restore_html(m[9, i]) |
| 102 |
if (substring(ti, pos[2], pos[4]) != mi) { |
| 103 |
p = base::gregexpr(mi, ti, fixed = TRUE)[[1]] |
| 104 |
if (length(p) > 1 || p < 1) { |
| 105 |
save_pos(c(i1, i2)); stop( |
| 106 |
'Unable to locate the inline code expression ', mi, |
| 107 |
'. Please file an issue to https://github.com/yihui/litedown/issues ', |
| 108 |
'with a minimal reproducible example.' |
| 109 |
) |
| 110 |
} |
| 111 |
pos[2] = p; pos[4] = p + attr(p, 'match.length') - 1 |
| 112 |
} |
| 113 |
} |
| 114 |
s = nchar(b$source) |
| 115 |
# calculate new position of code after we concatenate all lines of this block by \n |
| 116 |
b$col = c(b$col, c( |
| 117 |
sum(s[seq_len(i1 - l[1])] + 1) + pos[2], |
| 118 |
sum(s[seq_len(i2 - l[1])] + 1) + pos[4] |
| 119 |
)) |
| 120 |
b$pos = c(b$pos, pos) |
| 121 |
res[[j[i]]] = b |
| 122 |
} |
| 123 |
|
| 124 |
i1 = 0 # code chunk index |
| 125 |
# remove code fences, and extract code in text blocks |
| 126 |
for (j in seq_along(res)) { |
| 127 |
b = res[[j]] |
| 128 |
if (b$type == 'code_chunk') { |
| 129 |
code = b$source |
| 130 |
N = length(code) |
| 131 |
# a code block may be indented or inside a blockquote |
| 132 |
p = grep_sub('^([\t >]*)(`{3,}|~{3,}).*', '\\1\\2', code[1]) |
| 133 |
if (length(p) == 0) stop('Possibly malformed code block fence: ', code[1]) |
| 134 |
if (!grepl(sub('^[\t >]*', '', p), code[N])) stop( |
| 135 |
'The fences of the code block do not match:\n\n', code[1], '\n', code[N] |
| 136 |
) |
| 137 |
p = gsub('[`~]+$', '', p) |
| 138 |
if (p != '') { |
| 139 |
i = startsWith(code, p) |
| 140 |
# remove indentation or > |
| 141 |
code[i] = substr(code[i], nchar(p) + 1, nchar(code[i])) |
| 142 |
# trailing spaces in the prefix may have been trimmed: yihui/knitr#1446 |
| 143 |
code[!i] = gsub(gsub('(.+?)\\s+$', '^\\1', p), '', code[!i]) |
| 144 |
b$prefix = p |
| 145 |
} |
| 146 |
# possible comma-separated chunk options in header |
| 147 |
rx_opts = paste0('^(`{3,}|~{3,})\\s*([{]+)', rx_engine, '(.*?)\\s*[}]+\\s*$') |
| 148 |
o = match_one(code[1], rx_opts)[[1]] |
| 149 |
if (length(o)) { |
| 150 |
# if two or more `{` is used, we will write chunk fences to output |
| 151 |
if (nchar(o[3]) > 1) b$fences = c( |
| 152 |
sub('{{', '{', sub('}}\\s*$', '}', code[1]), fixed = TRUE), code[N] |
| 153 |
) |
| 154 |
o = if (o[5] != '') csv_options(o[5]) |
| 155 |
} |
| 156 |
code = code[-c(1, N)] # remove fences |
| 157 |
save_pos(b$lines) |
| 158 |
code = split_chunk(b$info, code) |
| 159 |
b[c('source', 'options', 'comments')] = code[c('code', 'options', 'src')] |
| 160 |
# starting line number of code |
| 161 |
b$code_start = b$lines[1] + 1L + length(b$comments) |
| 162 |
# default label is chunk-i (or parent-label-i for child documents) |
| 163 |
i1 = i1 + 1 |
| 164 |
# merge chunk options from header with pipe comment options |
| 165 |
b$options = merge_list(list( |
| 166 |
label = sprintf('%s-%d', (if (isTRUE(.env$child)) reactor('label')) %||% 'chunk', i1) |
| 167 |
), o, b$options) |
| 168 |
b$options$engine = b$info |
| 169 |
b$info = NULL # the info is stored in chunk options as `engine` |
| 170 |
} else if (length(p <- b$col) > 0) { |
| 171 |
p = matrix(p, nrow = 2) |
| 172 |
x = one_string(b$source) |
| 173 |
x1 = substring(x, p[1, ], p[2, ]) # code |
| 174 |
# then extract normal text |
| 175 |
p = rbind(p[1, ] - 1, p[2, ] + 1) |
| 176 |
p = matrix(c(1, p, nchar(x)), nrow = 2) |
| 177 |
x2 = substring(x, p[1, ], p[2, ]) # text |
| 178 |
# get rid of left-over backticks |
| 179 |
N = length(x2) |
| 180 |
x2[1] = gsub('`+$', '', x2[1]) # trailing ` of first |
| 181 |
x2[N] = gsub('^`+', '', x2[N]) # leading ` of last |
| 182 |
# ` at both ends for text in the middle |
| 183 |
if (N > 2) x2[2:(N - 1)] = gsub('^`+|`+$', '', x2[2:(N - 1)]) |
| 184 |
# see if the code is wrapped in $ $ |
| 185 |
d1 = substring(x2, nchar(x2), nchar(x2)) == '$' |
| 186 |
d2 = substring(x2, 1, 1) == '$' |
| 187 |
dollar = d1[-N] & d2[-1] |
| 188 |
# position of code c(row1, col1, row2, col2) |
| 189 |
pos = matrix(b$pos, nrow = 4) |
| 190 |
x = as.list(head(c(rbind(x2, c(x1, ''))), -1)) |
| 191 |
for (i in seq_len(N - 1)) { |
| 192 |
z = match_one(x1[i], rx_inline)[[1]][-1] |
| 193 |
p2 = pos[, i]; save_pos(p2) |
| 194 |
xi = list( |
| 195 |
source = z[2], pos = p2, |
| 196 |
options = csv_options(gsub('^([^,]+)', 'engine="\\1"', z[1])) |
| 197 |
) |
| 198 |
if (dollar[i]) xi$math = TRUE |
| 199 |
x[[2 * i]] = xi |
| 200 |
} |
| 201 |
b$source = x |
| 202 |
} else { |
| 203 |
b$source = paste(b$source, collapse = '\n') |
| 204 |
} |
| 205 |
b$pos = b$col = NULL # positions not useful anymore |
| 206 |
res[[j]] = b |
| 207 |
} |
| 208 |
res |
| 209 |
} |
| 210 |
|
| 211 |
set_error_handler = function(input) { |
| 212 |
opts = options(xfun.handle_error.loc_fun = get_loc) |
| 213 |
oenv = as.list(.env) |
| 214 |
exit_call(function() { options(opts); reset_env(oenv, .env) }) |
| 215 |
.env$input = input # store the input name for get_loc() |
| 216 |
} |
| 217 |
|
| 218 |
# convert byte position to character position |
| 219 |
char_pos = function(x, p) { |
| 220 |
x2 = x[p[c(1, 3)]] |
| 221 |
# no need to convert if no multibyte chars |
| 222 |
if (all(nchar(x2) == nchar(x2, 'bytes'))) return(p) |
| 223 |
p2 = p[c(2, 4)] |
| 224 |
Encoding(x2) = 'bytes' |
| 225 |
x2 = substr(x2, 1, p2 - 1) # go back one char in case current column is multibyte |
| 226 |
Encoding(x2) = 'UTF-8' |
| 227 |
p[c(2, 4)] = nchar(x2) + 1L # go forward by one char |
| 228 |
if (p2[2] == 0) p[4] = 0L # boundary case: \n before the closing backtick |
| 229 |
p |
| 230 |
} |
| 231 |
|
| 232 |
#' @details For R scripts, text blocks are extracted by removing the leading |
| 233 |
#' `#'` tokens. All other lines are treated as R code, which can optionally be |
| 234 |
#' separated into chunks by consecutive lines of `#|` comments (chunk options |
| 235 |
#' are written in these comments). If no `#'` or `#|` tokens are found in the |
| 236 |
#' script, the script will be divided into chunks that contain smallest |
| 237 |
#' possible complete R expressions. |
| 238 |
#' @note For simplicity, [sieve()] does not support inline code expressions. |
| 239 |
#' Text after `#'` is treated as pure Markdown. |
| 240 |
#' |
| 241 |
#' It is a pure coincidence that the function names `crack()` and `sieve()` |
| 242 |
#' weakly resemble Carson Sievert's name, but I will consider adding a class |
| 243 |
#' name `sievert` to the returned value of `sieve()` if Carson becomes the |
| 244 |
#' president of the United States someday, which may make the value |
| 245 |
#' radioactive and introduce a new programming paradigm named _Radioactive |
| 246 |
#' Programming_ (in case _Reactive Programming_ is no longer fun or cool). |
| 247 |
#' @rdname crack |
| 248 |
#' @export |
| 249 |
#' @examples |
| 250 |
#' |
| 251 |
#' # parse R code |
| 252 |
#' res = sieve(c("#' This is _doc_.", '', '#| eval=TRUE', '# this is code', '1 + 1')) |
| 253 |
#' str(res) |
| 254 |
sieve = function(input, text = NULL) { |
| 255 |
text = read_input(input, text); input = attr(text, 'input') |
| 256 |
n = length(text) |
| 257 |
r = run_range(grepl("^#'( .+| *)$", text), is_blank(text)) |
| 258 |
nc = ncol(r) |
| 259 |
|
| 260 |
# no #' or #|: split code into smallest expressions |
| 261 |
if (nc == 0 && !any(startsWith(text, '#| '))) { |
| 262 |
res = xfun::split_source(text, TRUE, TRUE) |
| 263 |
res = .mapply(function(code, label) { |
| 264 |
l = attr(code, 'lines') |
| 265 |
list( |
| 266 |
source = c(code), type = 'code_chunk', lines = l, code_start = l[1], |
| 267 |
options = list(engine = 'r', label = label) |
| 268 |
) |
| 269 |
}, res, sprintf('chunk-%d', seq_along(res))) |
| 270 |
return(res) |
| 271 |
} |
| 272 |
|
| 273 |
# split doc and code by #', and divide code by #| |
| 274 |
res = list() |
| 275 |
add_block = function(l1, l2, type = 'code_chunk', pipe = FALSE) { |
| 276 |
x = text[l1:l2] |
| 277 |
if (type == 'text_block') { |
| 278 |
el = list(source = one_string(sub("^#' ?", '', x))) |
| 279 |
} else { |
| 280 |
if (all(i <- is_blank(x))) return() |
| 281 |
# trim blank lines at both ends |
| 282 |
i2 = range(which(!i)) # first and last non-empty lines |
| 283 |
l1 = l1 + (i2[1] - 1) |
| 284 |
l2 = l2 - (length(i) - i2[2]) |
| 285 |
save_pos(c(l1, l2)) |
| 286 |
x = text[l1:l2] |
| 287 |
el = if (pipe) partition(x) else list(source = x) |
| 288 |
el$code_start = as.integer(l1) + length(el$comments) |
| 289 |
el$options$engine = 'r' |
| 290 |
} |
| 291 |
el$type = type |
| 292 |
el$lines = as.integer(c(l1, l2)) |
| 293 |
res[[length(res) + 1]] <<- el |
| 294 |
} |
| 295 |
partition = function(code) { |
| 296 |
code = split_chunk('r', code) |
| 297 |
set_names(code[c('code', 'options', 'src')], c('source', 'options', 'comments')) |
| 298 |
} |
| 299 |
# detect #| and split a block of code into chunks |
| 300 |
add_chunk = function(l1, l2) { |
| 301 |
x = text[l1:l2]; N = length(x) |
| 302 |
k = run_range(startsWith(x, '#| '))[1, ] |
| 303 |
if ((n <- length(k)) == 0) return(add_block(l1, l2)) |
| 304 |
if (k[1] > 1) { k = c(1, k); n = n + 1 } # make sure to scan from start |
| 305 |
for (i in seq_len(n)) { |
| 306 |
add_block(l1 - 1 + k[i], if (i == n) l2 else l1 - 1 + k[i + 1] - 1, pipe = TRUE) |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
set_error_handler(input) |
| 311 |
|
| 312 |
i = 1 |
| 313 |
for (j in seq_len(nc)) { |
| 314 |
i1 = r[1, j]; i2 = r[2, j] |
| 315 |
if (i1 > i) add_chunk(i, i1 - 1) |
| 316 |
add_block(i1, i2, type = 'text_block') |
| 317 |
i = i2 + 1 |
| 318 |
} |
| 319 |
if (i <= n) add_chunk(i, n) |
| 320 |
# add possibly missing chunk labels |
| 321 |
i = vapply(res, function(x) x$type == 'code_chunk', FALSE) |
| 322 |
res[i] = .mapply(function(x, label) { |
| 323 |
if (is.null(x$options$label)) x$options$label = label |
| 324 |
x |
| 325 |
}, res[i], sprintf('chunk-%d', seq_len(sum(i)))) |
| 326 |
res |
| 327 |
} |
| 328 |
|
| 329 |
# ranges of TRUE runs in a logical vector |
| 330 |
run_range = function(x, extend = NULL) { |
| 331 |
r = rle(x); l = r$lengths; i = r$values |
| 332 |
i2 = cumsum(l); i1 = i2 - l + 1 |
| 333 |
i1 = i1[i]; i2 = i2[i] |
| 334 |
# include adjacent blank lines, e.g., a blank line before or after #' should be doc |
| 335 |
if (!is.null(extend)) { |
| 336 |
k = extend[pmax(i1 - 1, 1)] # check if previous line is empty |
| 337 |
i1[k] = i1[k] - 1 |
| 338 |
k = extend[pmin(i2 + 1, length(extend))] # check if next line is empty |
| 339 |
i2[k] = i2[k] + 1 |
| 340 |
# merge adjacent runs, e.g., 1:2 and 2:4 -> 1:4 |
| 341 |
k = NULL |
| 342 |
if ((n <- length(i1)) > 1) { |
| 343 |
k = i2[1:(n - 1)] < i1[2:n] |
| 344 |
i1 = i1[c(TRUE, k)]; i2 = i2[c(k, TRUE)] |
| 345 |
} |
| 346 |
} |
| 347 |
rbind(i1, i2) |
| 348 |
} |
| 349 |
|
| 350 |
# convert knitr's inline `r code` to litedown's `{r} code` |
| 351 |
convert_knitr = function(input) { |
| 352 |
x = read_utf8(input) |
| 353 |
r = '(?<!(^``))(?<!(\n``))`r[ #]([^`]+)\\s*`' |
| 354 |
i = prose_index(x) |
| 355 |
x[i] = gsub(r, '`{r} \\3`', x[i], perl = TRUE) |
| 356 |
write_utf8(x, input) |
| 357 |
} |
| 358 |
|
| 359 |
#' Get the `fuse()` context |
| 360 |
#' |
| 361 |
#' A helper function to query the [fuse()] context (such as the input file path |
| 362 |
#' or the output format name) when called inside a code chunk. |
| 363 |
#' @param item The name of the context item. |
| 364 |
#' @return If the `item` is provided, return its value in the context. If |
| 365 |
#' `NULL`, the whole context (an environment) is returned. |
| 366 |
#' @export |
| 367 |
#' @examples |
| 368 |
#' litedown::get_context('input') |
| 369 |
#' litedown::get_context('format') |
| 370 |
#' names(litedown::get_context()) # all available items |
| 371 |
get_context = function(item = NULL) if (is.null(item)) .env else .env[[item]] |
| 372 |
|
| 373 |
# return a string to indicate the error location |
| 374 |
get_loc = function(label) { |
| 375 |
l = .env$source_pos; n = length(l) |
| 376 |
if (n == 4) l = sprintf('#%d:%d-%d:%d', l[1], l[2], l[3], l[4]) # row1:col1-row2:col2 |
| 377 |
if (n == 2) l = sprintf('#%d-%d', l[1], l[2]) # row1-row2 |
| 378 |
paste0(.env$input2 %|% .env$input, l, if (label != '') paste0(' [', label, ']')) |
| 379 |
} |
| 380 |
|
| 381 |
# save line numbers in .env to be used in error messages |
| 382 |
save_pos = function(x) .env$source_pos = x |
| 383 |
|
| 384 |
# line/col info for ANSI links |
| 385 |
link_pos = function() { |
| 386 |
l = .env$source_pos |
| 387 |
sprintf('line = %d:col = %d', l[1], if (length(l) == 4) l[2] else 1) |
| 388 |
} |
| 389 |
|
| 390 |
# get the execution order of code/text blocks via the `order` option (lower |
| 391 |
# values indicate earlier execution) |
| 392 |
block_order = function(res, N = length(res)) { |
| 393 |
check = function(b, env) { |
| 394 |
if (is.null(o <- b$options[['order']])) return(NA) |
| 395 |
if (is_lang(o)) o = eval(o, env) |
| 396 |
if (length(o) == 1 && is.numeric(o)) return(o) |
| 397 |
save_pos(b$pos %||% b$lines) |
| 398 |
stop("The chunk option 'order' must be either NULL or a number.", call. = FALSE) |
| 399 |
} |
| 400 |
x = seq_len(N); e = new.env(parent = fuse_env()); e$N = N |
| 401 |
for (i in x) { |
| 402 |
b = res[[i]]; e$i = i |
| 403 |
if (b$type == 'code_chunk') { |
| 404 |
if (!is.na(o <- check(b, e))) x[i] = o |
| 405 |
} else if (is.list(b$source)) { |
| 406 |
# use the first found `order` option in all inline expressions |
| 407 |
for (s in b$source) if (is.list(s) && !is.na(o <- check(s, e))) { |
| 408 |
x[i] = o; break |
| 409 |
} |
| 410 |
} |
| 411 |
} |
| 412 |
order(x) |
| 413 |
} |
| 414 |
|
| 415 |
#' @description The function `fuse()` runs code from code chunks and inline code |
| 416 |
#' expressions in R Markdown, interweaves the results with the rest of text in |
| 417 |
#' the input to intermediate Markdown output (which is similar to what |
| 418 |
#' `knitr::knit()` does), and renders the Markdown output through `mark()` to |
| 419 |
#' the final output format, such as HTML or LaTeX (similar to |
| 420 |
#' `rmarkdown::render()`). It also works on R scripts in a way similar to |
| 421 |
#' `knitr::spin()`. The function `fiss()` extracts code from the input, and is |
| 422 |
#' similar to `knitr::purl()`. |
| 423 |
#' @rdname mark |
| 424 |
#' @param envir An environment in which the code is to be evaluated. It can be |
| 425 |
#' accessed via [fuse_env()] inside [fuse()]. |
| 426 |
#' @param quiet If `TRUE`, do not show the progress bar. If `FALSE`, the |
| 427 |
#' progress bar will be shown after a number of seconds, which can be set via |
| 428 |
#' a global [option][options] `litedown.progress.delay` (the default is `2`). |
| 429 |
#' THe progress bar output can be set via a global option |
| 430 |
#' `litedown.progress.output` (the default is [stderr()]). |
| 431 |
#' @note For `fuse()`, you can generate the intermediate Markdown output via |
| 432 |
#' `output = '.md'` or `output = 'markdown'` without further calling `mark()`. |
| 433 |
#' @seealso [sieve()], for the syntax of R scripts to be passed to [fuse()]. |
| 434 |
#' @export |
| 435 |
#' @examples |
| 436 |
#' library(litedown) |
| 437 |
#' doc = c('```{r}', '1 + 1', '```', '', '$\\pi$ = `{r} pi`.') |
| 438 |
#' fuse(doc) |
| 439 |
#' fuse(doc, '.tex') |
| 440 |
#' fiss(doc) |
| 441 |
fuse = function(input, output = NULL, text = NULL, envir = parent.frame(), quiet = FALSE) { |
| 442 |
text = read_input(input, text); input = attr(text, 'input') |
| 443 |
# determine if the input is R or R Markdown |
| 444 |
if (r_input <- is_R(input, text)) { |
| 445 |
blocks = sieve(input, text) |
| 446 |
yaml = yaml_body(blocks[[1]]$source)$yaml |
| 447 |
} else { |
| 448 |
blocks = crack(input, text) |
| 449 |
yaml = yaml_body(text)$yaml |
| 450 |
} |
| 451 |
full = is_output_full(output) |
| 452 |
format = detect_format(output, yaml) |
| 453 |
output = auto_output(input, output, format) |
| 454 |
if (!is.null(output_base <- output_path(input, output))) |
| 455 |
output_base = sans_ext(output_base) |
| 456 |
|
| 457 |
opts = reactor() |
| 458 |
# clean up the figure folder on exit if it's empty |
| 459 |
on.exit(del_empty_dir({ |
| 460 |
if (dir.exists(fig.dir <- opts$fig.path)) fig.dir else dirname(fig.dir) |
| 461 |
}), add = TRUE) |
| 462 |
|
| 463 |
# restore and clean up some objects on exit |
| 464 |
opts2 = as.list(opts); on.exit(reactor(opts2), add = TRUE) |
| 465 |
oenv = as.list(.env); on.exit(reset_env(oenv, .env), add = TRUE) |
| 466 |
|
| 467 |
# set working directory if unset |
| 468 |
if (is_file(input) && is.null(opts$wd)) opts$wd = dirname(normalizePath(input)) |
| 469 |
|
| 470 |
# store output dir so we can calculate relative paths for plot files later |
| 471 |
.env$wd_out = normalize_path( |
| 472 |
if (is.null(output_base)) { |
| 473 |
if (is.character(.env$wd_out)) .env$wd_out else '.' |
| 474 |
} else dirname(output_base) |
| 475 |
) |
| 476 |
# store the environment and output format |
| 477 |
.env$global = envir; .env$format = format |
| 478 |
|
| 479 |
# set default device to 'cairo_pdf' for LaTeX output, and 'png' for other formats |
| 480 |
if (is.null(opts$dev)) { |
| 481 |
opts$dev = if (format == 'latex') 'cairo_pdf' else 'png' |
| 482 |
} |
| 483 |
# set default figure and cache paths |
| 484 |
set_path = function(name) { |
| 485 |
# fig.path = output__files/ if `output` is a path, otherwise use |
| 486 |
# litedown__files/ (we don't use _files because of rstudio/rmarkdown#2550) |
| 487 |
if (is.null(p <- opts[[name]])) p = aux_path(output_base %||% 'litedown', name) |
| 488 |
slash = endsWith(p, '/') |
| 489 |
# make sure path is absolute so it will be immune to setwd() (in code chunks) |
| 490 |
if (is_rel_path(p)) { |
| 491 |
p = file.path(getwd(), p) |
| 492 |
# preserve trailing slash because file.path() removes it on Windows |
| 493 |
if (slash) p = sub('/*$', '/', p) |
| 494 |
} |
| 495 |
opts[[name]] = p |
| 496 |
} |
| 497 |
set_path('fig.path'); set_path('cache.path') |
| 498 |
|
| 499 |
.env$input = input |
| 500 |
if (is_file(input)) .env$full_input = normalizePath(input) |
| 501 |
res = .fuse(blocks, input, quiet) |
| 502 |
|
| 503 |
# save timing data if necessary |
| 504 |
timing_data() |
| 505 |
|
| 506 |
# keep the markdown output if keep_md = TRUE is set in YAML output format |
| 507 |
if (is_output_file(output) && isTRUE(yaml_field(yaml, format, 'keep_md'))) { |
| 508 |
write_utf8(res, with_ext(output, '.md')) |
| 509 |
} |
| 510 |
fuse_output(input, output, res, full) |
| 511 |
} |
| 512 |
|
| 513 |
# default fig/cache path |
| 514 |
aux_path = function(base = sans_ext(file), type, file) { |
| 515 |
paste0(base, c(fig.path = '__files/', cache.path = '__cache/')[type]) |
| 516 |
} |
| 517 |
fig_path = function(path) aux_path(, 'fig.path', path) |
| 518 |
|
| 519 |
# if output = '.md' or 'markdown', no need for further mark() conversion |
| 520 |
fuse_output = function(input, output, res, full = NULL) { |
| 521 |
if (is.character(output) && grepl('[.]md$|^markdown$', output)) { |
| 522 |
if (is_output_file(output)) { |
| 523 |
write_utf8(res, output) |
| 524 |
} else raw_string(res) |
| 525 |
} else { |
| 526 |
if (isTRUE(full)) attr(output, 'full') = TRUE |
| 527 |
mark(input, output, res) |
| 528 |
} |
| 529 |
} |
| 530 |
|
| 531 |
#' @rdname mark |
| 532 |
#' @export |
| 533 |
fiss = function(input, output = '.R', text = NULL) { |
| 534 |
text = read_input(input, text); input = attr(text, 'input') |
| 535 |
output = auto_output(input, output, NULL) |
| 536 |
blocks = crack(input, text) |
| 537 |
# TODO: what should we do for non-R code? also consider eval=FALSE and error=TRUE |
| 538 |
res = uapply(blocks, function(b) { |
| 539 |
if (b$type == 'code_chunk' && !isFALSE(b$options$purl) && b$options$engine == 'r') |
| 540 |
c(b$source, '') |
| 541 |
}) |
| 542 |
if (is_output_file(output)) write_utf8(res, output) else raw_string(res) |
| 543 |
} |
| 544 |
|
| 545 |
.fuse = function(blocks, input, quiet) { |
| 546 |
n = length(blocks) |
| 547 |
nms = vapply(blocks, function(x) x$options[['label']] %||% '', character(1)) |
| 548 |
names(blocks) = nms |
| 549 |
|
| 550 |
# a simple progress indicator: we need to know how many spaces we need to wipe |
| 551 |
# out previous progress text of the form: |
| 552 |
# xxx% | input_file#line1-line2 [label] |
| 553 |
# ...4..3 1 1 .2 1 |
| 554 |
p_len = 4 + 3 + sum(nchar(input)) + 1 + |
| 555 |
(sum(nchar(sprintf('%d', blocks[[n]]$lines))) + 1) + 2 + max(nchar(nms)) + 1 |
| 556 |
p_clr = paste0('\r', strrep(' ', p_len), '\r') # a string to clear the progress |
| 557 |
p_out = getOption('litedown.progress.output', stderr()) |
| 558 |
p_yes = FALSE; t0 = Sys.time(); td = getOption('litedown.progress.delay', 2) |
| 559 |
p_bar = function(x) { |
| 560 |
if (!quiet && (p_yes || Sys.time() - t0 > td)) { |
| 561 |
cat(x, sep = '', file = p_out) |
| 562 |
p_yes <<- TRUE |
| 563 |
} |
| 564 |
} |
| 565 |
# if error occurs, print error location with a clickable file link |
| 566 |
k = 0 # when exiting, k should be n + 1 |
| 567 |
on_error = function() { |
| 568 |
if (k > n) return() # blocks have been successfully fused |
| 569 |
p_bar(p_clr) |
| 570 |
ansi_link(input) |
| 571 |
message('Quitting from ', get_loc(nms[k])) |
| 572 |
} |
| 573 |
# suppress tidyverse progress bars and use cairo for bitmap devices (for |
| 574 |
# smaller plot files and possible parallel execution) |
| 575 |
opt = options(rstudio.notebook.executing = TRUE, bitmapType = bitmap_type()) |
| 576 |
on.exit({ options(opt); on_error() }, add = TRUE) |
| 577 |
|
| 578 |
# the chunk option `order` determines the execution order of chunks |
| 579 |
o = block_order(blocks, n) |
| 580 |
res = character(n) |
| 581 |
for (i in seq_len(n)) { |
| 582 |
k = o[i]; b = blocks[[k]]; save_pos(b$lines) |
| 583 |
p_bar(c(as.character(round((i - 1)/n * 100)), '%', ' | ', get_loc(nms[k]))) |
| 584 |
# record timing if requested |
| 585 |
if (!isFALSE(time <- timing_path())) t1 = Sys.time() |
| 586 |
res[k] = if (b$type == 'code_chunk') { |
| 587 |
one_string(fuse_code(b, blocks)) |
| 588 |
} else { |
| 589 |
one_string(fuse_text(b), '') |
| 590 |
} |
| 591 |
if (!isFALSE(time)) record_time(Sys.time() - t1, b$lines, nms[k]) |
| 592 |
p_bar(p_clr) |
| 593 |
} |
| 594 |
k = n + 1 |
| 595 |
res |
| 596 |
} |
| 597 |
|
| 598 |
# add ANSI link on input path if supported |
| 599 |
ansi_link = function(x) { |
| 600 |
if (length(x) && isTRUE(as.logical(Sys.getenv('RSTUDIO_CLI_HYPERLINKS')))) |
| 601 |
.env$input2 = sprintf( |
| 602 |
'\033]8;%s;file://%s\a%s\033]8;;\a', link_pos(), normalize_path(x), x |
| 603 |
) |
| 604 |
} |
| 605 |
|
| 606 |
# use options(bitmapType = 'cairo') for bitmap devices on macOS if possible |
| 607 |
bitmap_type = function() { |
| 608 |
# xquartz has to be installed for cairo to work (I don't know why) |
| 609 |
if (xfun::is_macos() && capabilities('cairo') && Sys.which('xquartz') != '') |
| 610 |
'cairo' else .Options$bitmapType |
| 611 |
} |
| 612 |
|
| 613 |
time_frame = function(s = NA_character_, l = integer(), lab = NA_character_, t = NA_real_) { |
| 614 |
data.frame(source = s, line1 = l[1], line2 = l[2], label = lab, time = t) |
| 615 |
} |
| 616 |
|
| 617 |
record_time = function(x, lines, label) { |
| 618 |
x = as.numeric(x) |
| 619 |
gc(FALSE) |
| 620 |
d = time_frame(.env$input %||% '#text', lines, label, x) |
| 621 |
.env$time = append(.env$time, list(d)) |
| 622 |
} |
| 623 |
|
| 624 |
#' Get the timing data of code chunks and text blocks in a document |
| 625 |
#' |
| 626 |
#' Timing can be enabled via the chunk option `time = TRUE` (e.g., set |
| 627 |
#' [litedown::reactor]`(time = TRUE)` in the first code chunk). After it is |
| 628 |
#' enabled, the execution time for code chunks and text blocks will be recorded. |
| 629 |
#' This function can be called to retrieve the timing data later in the document |
| 630 |
#' (e.g., in the last code chunk). |
| 631 |
#' @param threshold A number (time in seconds) to subset data with. Only rows |
| 632 |
#' with time above this threshold are returned. |
| 633 |
#' @param sort Whether to sort the data by time in the decreasing order. |
| 634 |
#' @param total Whether to append the total time to the data. |
| 635 |
#' @note By default, the data will be cleared after each call of [fuse()] and |
| 636 |
#' will not be available outside [fuse()]. To store the data persistently, you |
| 637 |
#' can set the `time` option to a file path. This is necessary if you want to |
| 638 |
#' get the timing data for multiple input documents (such as all chapters of a |
| 639 |
#' book). Each document needs to point the `time` option to the same path. |
| 640 |
#' When you do not need timing any more, you will need to delete this file by |
| 641 |
#' yourself. |
| 642 |
#' @return A data frame containing input file paths, line numbers, chunk labels, |
| 643 |
#' and time. If no timing data is available, `NULL` is returned. |
| 644 |
#' @export |
| 645 |
timing_data = function(threshold = 0, sort = TRUE, total = TRUE) { |
| 646 |
d = .env$time |
| 647 |
if (!is.null(d)) d = do.call(rbind, d) |
| 648 |
|
| 649 |
if (is.character(path <- timing_path())) { |
| 650 |
if (file_exists(path)) { |
| 651 |
d2 = readRDS(path) |
| 652 |
if (length(input <- .env$input)) d2 = subset(d2, source != input) |
| 653 |
d = rbind(d2, d) |
| 654 |
} |
| 655 |
saveRDS(d, path) |
| 656 |
} |
| 657 |
if (is.null(d)) return(invisible(d)) |
| 658 |
|
| 659 |
total = if (total) sum(d$time) |
| 660 |
# add edit links in the roam() mode |
| 661 |
if (is_roaming() && !all(i <- d$source == '#text')) { |
| 662 |
d$source = ifelse(i, '', sprintf( |
| 663 |
'%s [✎](?path=%s&line=%d)', d$source, URLencode(d$source, TRUE), d$line1 |
| 664 |
)) |
| 665 |
} |
| 666 |
d = d[d$time > threshold, ] |
| 667 |
if (sort) d = d[order(d$time, decreasing = TRUE), ] |
| 668 |
if (!is.null(total)) d = rbind(d, time_frame('Total', t = total)) |
| 669 |
d |
| 670 |
} |
| 671 |
|
| 672 |
timing_path = function() { |
| 673 |
p = xfun::env_option('litedown.time') |
| 674 |
if (is.character(p) && tolower(p) %in% c('true', 'false')) p = as.logical(p) |
| 675 |
if (is.logical(p) || (is.character(p) && p != '')) p else reactor('time') |
| 676 |
} |
| 677 |
|
| 678 |
# an internal function for RStudio IDE to recognize the custom knit function |
| 679 |
# when users hit the Knit button |
| 680 |
knit = function(input, ...) fuse(input, envir = parent.frame()) |
| 681 |
|
| 682 |
fuse_code = function(x, blocks) { |
| 683 |
# merge local chunk options into global options |
| 684 |
old = reactor(x$options); on.exit(reactor(old), add = TRUE) |
| 685 |
opts = reactor() |
| 686 |
|
| 687 |
# delayed assignment to evaluate a chunk option only when it is actually used |
| 688 |
lapply(setdiff(names(opts), 'order'), function(i) { |
| 689 |
# skip the `order` option since it needs to be eval()ed in block_order() |
| 690 |
if (i != 'order' && is_lang(o <- opts[[i]])) |
| 691 |
delayedAssign(i, eval(o, fuse_env()), environment(), opts) |
| 692 |
}) |
| 693 |
# set the working directory before evaluating anything else |
| 694 |
change_wd(opts$wd) |
| 695 |
|
| 696 |
# fuse child documents (empty the `child` option to avoid infinite recursion) |
| 697 |
if (length(opts$child)) return(uapply(reactor(child = NULL)$child, function(.) { |
| 698 |
child = .env$child; .env$child = TRUE; on.exit(.env$child <- child) |
| 699 |
fuse(., output = 'markdown', envir = fuse_env(), quiet = TRUE) |
| 700 |
})) |
| 701 |
|
| 702 |
lab = opts$label; lang = opts$engine |
| 703 |
|
| 704 |
# the source code could be from chunk options 'file' or 'code' |
| 705 |
test_source = function(name) { |
| 706 |
if (length(opts[[name]]) == 0) return(FALSE) |
| 707 |
if (cond <- length(x$source) > 0) warning( |
| 708 |
"The chunk option '", name, "' is ignored for the non-empty chunk:\n\n", |
| 709 |
one_string(x$source) |
| 710 |
) |
| 711 |
!cond |
| 712 |
} |
| 713 |
if (test_source('file')) { |
| 714 |
x$source = read_all(opts$file) |
| 715 |
} else if (test_source('code')) { |
| 716 |
x$source = opts$code |
| 717 |
} else { |
| 718 |
# use code from other chunks of the same label |
| 719 |
labs = if (length(x$source) == 0) which(names(blocks) == lab) |
| 720 |
if (length(labs)) x$source = uapply(blocks[labs], `[[`, 'source') |
| 721 |
} |
| 722 |
|
| 723 |
# resolve inline chunk references and do code interpolation |
| 724 |
x$source = fill_source(x$source, opts$fill, blocks) |
| 725 |
|
| 726 |
res = if (isFALSE(opts$eval)) list(new_source(x$source)) else { |
| 727 |
if (is.function(eng <- engines(lang))) eng(x) else list( |
| 728 |
new_source(x$source), |
| 729 |
new_warning(sprintf("The engine '%s' is not supported.", lang)) |
| 730 |
) |
| 731 |
} |
| 732 |
|
| 733 |
if (!opts$include) return('') |
| 734 |
|
| 735 |
# if the engine result contains new chunk options, apply the new options, and |
| 736 |
# make sure they will be properly restored via `old` on exit |
| 737 |
if (length(opts_new <- attr(res, 'options'))) { |
| 738 |
old2 = reactor(opts_new) |
| 739 |
for (i in setdiff(names(old2), names(old))) old[i] = old2[i] |
| 740 |
} |
| 741 |
|
| 742 |
# decide the number of backticks to wrap up output |
| 743 |
fence = xfun::make_fence(c(unlist(res), x$fences)) |
| 744 |
|
| 745 |
# deal with figure alt text, captions, and environment |
| 746 |
env = opts$fig.env; alt = opts$fig.alt; cap = opts$fig.cap |
| 747 |
att = if (is.null(att <- opts$attr.plot)) '' else paste0('{', att, '}') |
| 748 |
if (is.null(alt)) alt = cap |
| 749 |
p1 = Filter(function(x) !is_plot(x), res) |
| 750 |
p2 = Filter(is_plot, res) |
| 751 |
p3 = unlist(p2) # vector of plot paths |
| 752 |
# get the relative path of the plot directory |
| 753 |
fig.dir = if (length(p3)) tryCatch( |
| 754 |
sub('^[.]/', '', paste0(dirname(relative_path(p3[1], .env$wd_out)), '/')), |
| 755 |
error = function(e) NULL |
| 756 |
) |
| 757 |
|
| 758 |
# record plot paths so they can be cleaned up if option embed_cleanup = true; |
| 759 |
# however, when cache = true, we shouldn't clean up plots since they won't be |
| 760 |
# regenerated next time (then they won't be found) |
| 761 |
if (!isTRUE(opts$cache)) .env$plot_files = c(.env$plot_files, p3) |
| 762 |
# recycle alt and attributes for all plots |
| 763 |
pn = length(p3) |
| 764 |
if (pn && is.null(alt)) { |
| 765 |
# reminder about missing alt text if this option is set to TRUE |
| 766 |
if (getOption('litedown.fig.alt', FALSE)) message( |
| 767 |
"\nPlease provide a 'fig.alt' option to the code chunk at ", get_loc(lab) |
| 768 |
) |
| 769 |
alt = '' |
| 770 |
} |
| 771 |
alt = rep(alt, length.out = pn) |
| 772 |
att = rep(att, length.out = pn) |
| 773 |
# if figure caption is provided, merge all plots in one env |
| 774 |
if (pn && length(cap)) res = c(xfun:::merge_record(p1), list(new_plot(p3))) |
| 775 |
i = 0 # plot counter |
| 776 |
|
| 777 |
res_show = opts$results # normalize the 'results' option |
| 778 |
if (is.logical(res_show)) res_show = if (res_show) 'markup' else 'hide' |
| 779 |
|
| 780 |
l1 = x$code_start # starting line number of the whole code chunk |
| 781 |
# filter the results if desired |
| 782 |
if (!is.null(opts$filter)) res = match.fun(opts$filter)(res) |
| 783 |
# generate markdown output |
| 784 |
out = lapply(res, function(x) { |
| 785 |
type = grep_sub('^record_', '', class(x))[1] |
| 786 |
if (is.na(type)) type = 'output' |
| 787 |
if (type == 'source') { |
| 788 |
if (!opts$echo) return() |
| 789 |
l2 = attr(x, 'lines')[1] # starting line number of a code block |
| 790 |
x = one_string(x) |
| 791 |
if (opts$strip.white) x = trim_blank(x) |
| 792 |
} |
| 793 |
asis = if (type %in% c('output', 'asis')) { |
| 794 |
if (res_show == 'hide') return() |
| 795 |
any(c(res_show, type) == 'asis') |
| 796 |
} else FALSE |
| 797 |
if (type == 'warning' && !isTRUE(opts$warning)) return() |
| 798 |
if (type == 'message' && !isTRUE(opts$message)) return() |
| 799 |
if (type == 'plot') { |
| 800 |
n = length(x); i2 = i + seq_len(n); i <<- i + n |
| 801 |
img = sprintf( |
| 802 |
'%s', alt[i2], |
| 803 |
if (is.null(fig.dir)) x else gsub('^.*/', fig.dir, x), att[i2] |
| 804 |
) |
| 805 |
add_cap(img, cap, lab, opts$cap.pos, env) |
| 806 |
} else { |
| 807 |
a = opts[[paste0('attr.', type)]] |
| 808 |
if (type == 'source') { |
| 809 |
# use engine name as class name when `a` is not provided |
| 810 |
if (is.null(a)) a = paste0('.', lang) |
| 811 |
# add line numbers |
| 812 |
if (is_roaming()) a = c(a, lineno_attr(NA, l1 + l2 - 1)) |
| 813 |
} else { |
| 814 |
if (type == 'message') x = sub('\n$', '', x) |
| 815 |
if (!asis) { |
| 816 |
opt2 = attr(x, 'opts') |
| 817 |
cmt = opts$comment %||% opt2$comment %||% '#> ' |
| 818 |
if (cmt != '') { |
| 819 |
x = split_lines(x) |
| 820 |
x = paste0(cmt, x) # comment out text output |
| 821 |
} |
| 822 |
if (is.null(a)) if (!is.null(a <- opt2$attr)) a = c(a, '.plain') |
| 823 |
} |
| 824 |
} |
| 825 |
if (asis) { |
| 826 |
if (is.null(a)) x else fenced_div(x, a) |
| 827 |
} else fenced_block(x, a, fence) |
| 828 |
} |
| 829 |
}) |
| 830 |
out = dropNULL(out) |
| 831 |
|
| 832 |
# collapse a code block without attributes into previous adjacent code block |
| 833 |
# (also try to collapse for results = 'hide') |
| 834 |
collapse = isTRUE(opts$collapse) || res_show == 'hide' |
| 835 |
if (collapse && (n <- length(out)) > 1) { |
| 836 |
i1 = 1; k = NULL # indices of elements to be removed from `out` |
| 837 |
for (i in 2:n) { |
| 838 |
if (i - i1 > 1) i1 = i - 1 # make sure blocks are adjacent |
| 839 |
o1 = out[[i1]]; n1 = length(o1); e1 = o1[n1] |
| 840 |
# previous block should have a closing fence ```+ |
| 841 |
if (n1 < 3 || !grepl('^```+$', e1)) next |
| 842 |
o2 = out[[i]] |
| 843 |
if (continue_block(o1[2], e1, head(o2, 2))) { |
| 844 |
out[[i]] = c(o1[-n1], o2[-(1:2)]) |
| 845 |
k = c(k, i1) # merge previous block into current and remove previous |
| 846 |
} |
| 847 |
} |
| 848 |
if (length(k)) out = out[-k] |
| 849 |
} |
| 850 |
|
| 851 |
a = opts$attr.chunk |
| 852 |
if (length(x$fences) == 2) { |
| 853 |
# add a class name to the chunk output so we can style it differently |
| 854 |
a = c(a, '.fenced-chunk') |
| 855 |
out = add_fences(out, x, fence) |
| 856 |
} |
| 857 |
out = unlist(out) |
| 858 |
if (!is.null(a)) out = fenced_div(out, a) |
| 859 |
# if first line of chunk output is empty, remove it (the chunk should have had |
| 860 |
# an empty line before it in the source) |
| 861 |
if (length(out) && out[1] == '') out = out[-1] |
| 862 |
# add prefix (possibly indentation and > quote chars) |
| 863 |
if (!is.null(x$prefix)) out = gsub('^|(?<=\n)', x$prefix, out, perl = TRUE) |
| 864 |
out |
| 865 |
} |
| 866 |
|
| 867 |
# resolve `<label>` to chunk source, and evaluate `{code}` to string (to |
| 868 |
# interpolate original source) |
| 869 |
fill_source = function(x, fill, blocks) { |
| 870 |
if (isFALSE(fill)) return(x) |
| 871 |
x = fill_label(x, blocks) |
| 872 |
fill_code(x, fill) |
| 873 |
} |
| 874 |
|
| 875 |
fill_label = function(x, blocks) { |
| 876 |
r = '`<(.+?)>`' |
| 877 |
for (i in grep(r, x)) { |
| 878 |
ind = sub('^(\\s*).*', '\\1', x[i]) # possible indent |
| 879 |
x[i] = match_replace(x[i], r, function(z) { |
| 880 |
labs = sub(r, '\\1', z) # chunk label |
| 881 |
j = labs %in% names(blocks) |
| 882 |
if (any(j)) z[j] = uapply(blocks[labs[j]], function(b) { |
| 883 |
s = b$source |
| 884 |
if ((n <- length(s)) > 0) { |
| 885 |
paste0(c('', rep(ind, n - 1)), s, collapse = '\n') |
| 886 |
} else '' |
| 887 |
}) |
| 888 |
z |
| 889 |
}) |
| 890 |
} |
| 891 |
# recursion for possible more `<label>` markers |
| 892 |
if (is.null(i)) x else fill_label(split_lines(x), blocks) |
| 893 |
} |
| 894 |
|
| 895 |
fill_code = function(x, fill) { |
| 896 |
r = '`\\{(.+?)}`' |
| 897 |
match_replace(x, r, function(z) { |
| 898 |
code = sub(r, '\\1', z) |
| 899 |
uapply(code, function(s) { |
| 900 |
v = eval_code(s) |
| 901 |
if (is.function(fill)) v = fill(v) |
| 902 |
one_string(v) |
| 903 |
}) |
| 904 |
}) |
| 905 |
} |
| 906 |
|
| 907 |
# temporarily change the working directory inside a function call |
| 908 |
change_wd = function(dir) { |
| 909 |
if (is.character(dir)) { |
| 910 |
owd = setwd(dir); exit_call(function() setwd(owd)) |
| 911 |
} |
| 912 |
} |
| 913 |
|
| 914 |
# add caption to an element (e.g., figure/table) |
| 915 |
add_cap = function(x, cap, lab, pos, env, type = 'fig') { |
| 916 |
if (length(cap) == 0 || length(lab) == 0) return(x) |
| 917 |
cap = fenced_div(add_ref(lab, type, cap), '.caption') |
| 918 |
pos = pos %||% 'bottom' |
| 919 |
x = if (pos == 'top') c(cap, '', x) else c(x, '', cap) |
| 920 |
fenced_div(x, c(sub('^[.]?', '.', env), sprintf('#%s:%s', type, lab))) |
| 921 |
} |
| 922 |
|
| 923 |
# if original chunk header contains multiple curly braces (e.g., ```{{lang}}), |
| 924 |
# include chunk fences in the output (and also pipe comments if exist) |
| 925 |
add_fences = function(out, x, fence) { |
| 926 |
# remove last line of pipe comments if empty |
| 927 |
if ((n <- length(o <- x$comments)) > 1 && o[n] == '') o = o[-n] |
| 928 |
fences = list(c(x$fences[1], o), x$fences[2]) |
| 929 |
append(lapply(fences, fenced_block, c('.md', '.code-fence'), fence), out, 1) |
| 930 |
} |
| 931 |
|
| 932 |
# attributes for code blocks with line numbers |
| 933 |
lineno_attr = function(lang = NA, start = 1, auto = TRUE) c( |
| 934 |
if (!is.na(lang)) paste0('.', sub('^[rq]md$', 'md', tolower(lang))), |
| 935 |
'.line-numbers', if (auto) '.auto-numbers', sprintf('data-start="%d"', start) |
| 936 |
) |
| 937 |
|
| 938 |
# two blocks are continuous if first 2 elements of next block are '' and |
| 939 |
# previous block's closing or opening fence (after removing data-start attribute) |
| 940 |
continue_block = function(e1_open, e1_end, e2) { |
| 941 |
if (length(e2) != 2 || e2[1] != '') return(FALSE) |
| 942 |
if ((e2_open <- e2[2]) == e1_end) return(TRUE) |
| 943 |
e3 = sub(' data-start="[0-9]+"', '', c(e1_open, e2_open)) |
| 944 |
if (e3[1] == e3[2]) return(TRUE) |
| 945 |
# remove attributes of message blocks and see if they can be collapsed |
| 946 |
sub(' \\{[.]plain [.](message|warning|error)}', '', e2_open) == e1_end |
| 947 |
} |
| 948 |
|
| 949 |
new_source = function(x) { |
| 950 |
len = length(x) |
| 951 |
structure(new_record(x, 'source'), lines = if (len) c(1L, len) else c(0L, 0L)) |
| 952 |
} |
| 953 |
new_output = function(x) new_record(x, 'output') |
| 954 |
new_warning = function(x) new_record(x, 'warning') |
| 955 |
new_plot = function(x) new_record(x, 'plot') |
| 956 |
new_asis = function(x, raw = FALSE) { |
| 957 |
res = new_record(x, 'asis') |
| 958 |
if (raw) raw_string(res) else res |
| 959 |
} |
| 960 |
|
| 961 |
# interleave text and plot output, e.g., t t t p p p -> t p t p t p, or t t t t |
| 962 |
# p p -> t t p t t p |
| 963 |
interleave = function(res) { |
| 964 |
p = match(c('record_output', 'record_plot'), sapply(res, function(x) class(x)[1])) |
| 965 |
if (any(is.na(p))) { |
| 966 |
warning('Both text and plot output must be present in results to be interleaved.') |
| 967 |
return(res) |
| 968 |
} |
| 969 |
x1 = res[[p[1]]]; n1 = length(x1) |
| 970 |
x2 = res[[p[2]]]; n2 = length(x2) |
| 971 |
n = n1 / n2 |
| 972 |
if (n < 1) return(res) |
| 973 |
if (n1 %% n2 != 0) stop( |
| 974 |
'Length of text output (', n1, ') is not multiple of the number of plots (', n2, ').' |
| 975 |
) |
| 976 |
# interleave text and plot output: one (chunk of) text followed by one plot |
| 977 |
mix = unlist(lapply(seq_len(n2), function(i) { |
| 978 |
list(new_output(x1[(i - 1) * n + 1:n]), new_plot(x2[i])) |
| 979 |
}), recursive = FALSE) |
| 980 |
append(res[-p], mix, p[1] - 1) |
| 981 |
} |
| 982 |
|
| 983 |
#' Mark a character vector as raw output |
| 984 |
#' |
| 985 |
#' This function should be called inside a code chunk, and its effect is the |
| 986 |
#' same as the chunk option `results = "asis"`. The input character vector will |
| 987 |
#' be written verbatim to the output (and interpreted as Markdown). |
| 988 |
#' @param x A character vector (each element will be treated as a line). |
| 989 |
#' @param format An output format name, e.g., `html` or `latex`. If provided, |
| 990 |
#' `x` will be wrapped in a fenced code block, e.g., ```` ```{=html}````. |
| 991 |
#' @return A character vector with a special class to indicate that it should be |
| 992 |
#' treated as raw output. |
| 993 |
#' @export |
| 994 |
#' @examples |
| 995 |
#' litedown::raw_text(c('**This**', '_is_', '[Markdown](#).')) |
| 996 |
#' litedown::raw_text('<b>Bold</b>', 'html') |
| 997 |
#' litedown::raw_text('\\textbf{Bold}', 'latex') |
| 998 |
raw_text = function(x, format = NULL) { |
| 999 |
if (length(fmt <- sprintf('=%s', format)) == 1) x = fenced_block(x, fmt) |
| 1000 |
new_asis(x, TRUE) |
| 1001 |
} |
| 1002 |
|
| 1003 |
is_plot = function(x) inherits(x, 'record_plot') |
| 1004 |
|
| 1005 |
fuse_text = function(x) { |
| 1006 |
if (is.character(src <- x$source)) return(one_string(src)) |
| 1007 |
res = lapply(src, function(s) { |
| 1008 |
if (is.character(s)) s else exec_inline(s) |
| 1009 |
}) |
| 1010 |
unlist(res) |
| 1011 |
} |
| 1012 |
|
| 1013 |
exec_inline = function(x) { |
| 1014 |
save_pos(x$pos) |
| 1015 |
o = reactor(x$options); on.exit(reactor(o), add = TRUE) |
| 1016 |
opts = reactor() |
| 1017 |
if (isFALSE(opts$eval)) return('') |
| 1018 |
change_wd(opts$wd) |
| 1019 |
lang = x$options$engine |
| 1020 |
if (is.function(eng <- engines(lang))) { |
| 1021 |
one_string(eng(x, inline = TRUE)) |
| 1022 |
} else { |
| 1023 |
warning("The inline engine '", lang, "' is not supported.") |
| 1024 |
sprintf('`{%s} %s`', lang, x$source) |
| 1025 |
} |
| 1026 |
} |
| 1027 |
|
| 1028 |
fmt_inline = function(x, ...) { |
| 1029 |
if (is.numeric(x) && length(x) == 1 && !inherits(x, 'AsIs')) |
| 1030 |
sci_num(x, ...) else as.character(x) |
| 1031 |
} |
| 1032 |
|
| 1033 |
# change scientific notation to LaTeX math |
| 1034 |
sci_num = function(x, math = NULL) { |
| 1035 |
opts = reactor() |
| 1036 |
s = x != 0 && abs(log10(abs(x))) >= opts$power |
| 1037 |
x = format(signif(x, opts$signif), scientific = s) |
| 1038 |
r = '^(-)?([0-9.]+)e([-+])0*([0-9]+)$' |
| 1039 |
s = grepl(r, x) |
| 1040 |
if (s) { |
| 1041 |
n = match_one(x, r)[[1]] |
| 1042 |
x = sprintf( |
| 1043 |
'%s%s10^{%s%s}', n[2], if (n[3] == '1') '' else paste(n[3], '\\times '), |
| 1044 |
if (n[4] == '+') '' else n[4], n[5] |
| 1045 |
) |
| 1046 |
} |
| 1047 |
if (is.na(d <- opts$dollar)) d = s && !isTRUE(math) |
| 1048 |
if (d) paste0('$', x, '$') else x |
| 1049 |
} |
| 1050 |
|
| 1051 |
# similar to the base R options() interface but for litedown options / engines / |
| 1052 |
# ..., and is based on environments, which are *mutable* |
| 1053 |
new_opts = function() { |
| 1054 |
# global chunk options |
| 1055 |
.opts = structure(new_env(), class = c('litedown_env', 'environment')) |
| 1056 |
|
| 1057 |
opt_get = function(x, drop = length(x) == 1) { |
| 1058 |
vs = mget(x, .opts, ifnotfound = list(NULL)) |
| 1059 |
if (drop) vs[[1]] else vs |
| 1060 |
} |
| 1061 |
# setter: fun(opt = val); getter: fun('opt') |
| 1062 |
function(...) { |
| 1063 |
v = list(...) |
| 1064 |
n = length(v) |
| 1065 |
if (n == 0) return(.opts) |
| 1066 |
if (is.null(nms <- names(v))) { |
| 1067 |
if (all(vapply(v, is.character, TRUE))) return(opt_get(unlist(v))) |
| 1068 |
if (n > 1) warning( |
| 1069 |
'When not all unnamed arguments are character, only the first argument is used (', |
| 1070 |
n, ' were received).' |
| 1071 |
) |
| 1072 |
if (is.null(nms <- names(v <- v[[1]])) || any(nms == '')) stop( |
| 1073 |
'When the first unnamed argument is not character, it must be a named list.' |
| 1074 |
) |
| 1075 |
} |
| 1076 |
if (any(nms == '')) stop('All arguments must be either named or unnamed.') |
| 1077 |
old = opt_get(nms, drop = FALSE) |
| 1078 |
for (i in nms) assign(i, v[[i]], envir = .opts) |
| 1079 |
invisible(old) |
| 1080 |
} |
| 1081 |
} |
| 1082 |
|
| 1083 |
#' Get and set chunk options |
| 1084 |
#' |
| 1085 |
#' Chunk options are stored in an environment returned by `reactor()`. Option |
| 1086 |
#' values can be queried by passing their names to `reactor()`, and set by |
| 1087 |
#' passing named values. |
| 1088 |
#' @param ... Named values (for setting) or unnamed values (for getting). |
| 1089 |
#' @return With no arguments, `reactor()` returns an environment that stores the |
| 1090 |
#' options, which can also be used to get or set options. For example, with |
| 1091 |
#' `opts = reactor()`, `opts$name` returns an option value, and `opts$name = |
| 1092 |
#' value` sets an option to a value. |
| 1093 |
#' |
| 1094 |
#' With named arguments, `reactor()` sets options and returns a list of their |
| 1095 |
#' old values (e.g., `reactor(echo = FALSE, fig.width = 8)`). The returned |
| 1096 |
#' list can be passed to `reactor()` later to restore the options. |
| 1097 |
#' |
| 1098 |
#' With unnamed arguments, `reactor()` returns option values after received |
| 1099 |
#' option names as input. If one name is received, its value is returned |
| 1100 |
#' (e.g., `reactor('echo')`). If multiple names are received, a named list of |
| 1101 |
#' values is returned (e.g., `reactor(c('echo', 'fig.width'))`). A special |
| 1102 |
#' case is that if only one unnamed argument is received and it takes a list |
| 1103 |
#' of named values, the list will be used to set options, e.g., |
| 1104 |
#' `reactor(list(echo = FALSE, fig.width = 8))`, which is equivalent to |
| 1105 |
#' `reactor(echo = FALSE, fig.width = 8)`. |
| 1106 |
#' @export |
| 1107 |
#' @examples |
| 1108 |
#' # get options |
| 1109 |
#' litedown::reactor('echo') |
| 1110 |
#' litedown::reactor(c('echo', 'fig.width')) |
| 1111 |
#' |
| 1112 |
#' # set options |
| 1113 |
#' old = litedown::reactor(echo = FALSE, fig.width = 8) |
| 1114 |
#' litedown::reactor(c('echo', 'fig.width')) |
| 1115 |
#' litedown::reactor(old) # restore options |
| 1116 |
#' |
| 1117 |
#' # use the environment directly |
| 1118 |
#' opts = litedown::reactor() |
| 1119 |
#' opts$echo |
| 1120 |
#' mget(c('echo', 'fig.width'), opts) |
| 1121 |
#' ls(opts) # built-in options |
| 1122 |
reactor = new_opts() |
| 1123 |
reactor( |
| 1124 |
eval = TRUE, echo = TRUE, fill = TRUE, results = TRUE, comment = NULL, |
| 1125 |
warning = TRUE, message = TRUE, error = NA, include = TRUE, |
| 1126 |
strip.white = TRUE, collapse = FALSE, order = 0, |
| 1127 |
attr.source = NULL, attr.output = NULL, attr.plot = NULL, attr.chunk = NULL, |
| 1128 |
attr.message = '.plain .message', attr.warning = '.plain .warning', attr.error = '.plain .error', |
| 1129 |
cache = FALSE, cache.path = NULL, |
| 1130 |
dev = NULL, dev.args = NULL, fig.path = NULL, fig.ext = NULL, fig.keep = TRUE, |
| 1131 |
fig.width = 7, fig.height = 7, fig.dim = NULL, fig.cap = NULL, fig.alt = NULL, fig.env = '.figure', |
| 1132 |
tab.cap = NULL, tab.env = '.table', cap.pos = NULL, |
| 1133 |
print = NULL, print.args = NULL, time = FALSE, |
| 1134 |
code = NULL, file = NULL, child = NULL, purl = TRUE, |
| 1135 |
wd = NULL, |
| 1136 |
signif = 3, power = 6, dollar = NA |
| 1137 |
) |
| 1138 |
|
| 1139 |
eval_code = function(code, error = NA) { |
| 1140 |
expr = parse_only(code) |
| 1141 |
if (is.na(error)) eval(expr, fuse_env()) else tryCatch( |
| 1142 |
eval(expr, fuse_env()), error = function(e) if (error) e$message else '' |
| 1143 |
) |
| 1144 |
} |
| 1145 |
|
| 1146 |
# the R engine |
| 1147 |
eng_r = function(x, inline = FALSE, ...) { |
| 1148 |
opts = reactor() |
| 1149 |
if (inline) { |
| 1150 |
res = eval_code(x$source, opts$error) |
| 1151 |
return(fmt_inline(res, x$math)) |
| 1152 |
} |
| 1153 |
args = reactor( |
| 1154 |
'fig.path', 'fig.ext', 'fig.keep', 'dev', 'dev.args', 'message', 'warning', 'error', |
| 1155 |
'cache', 'print', 'print.args', 'verbose' |
| 1156 |
) |
| 1157 |
if (is.character(args$fig.path)) args$fig.path = paste0(args$fig.path, opts$label) |
| 1158 |
size = list(width = opts$fig.width, height = opts$fig.height) |
| 1159 |
# if fig.dim is provided, override fig.width and fig.height |
| 1160 |
if (length(dm <- opts$fig.dim) == 2) size[] = as.list(dm) |
| 1161 |
# map chunk options to record() argument names |
| 1162 |
names(args)[1:3] = c('dev.path', 'dev.ext', 'dev.keep') |
| 1163 |
args = dropNULL(args) |
| 1164 |
args$dev.args = merge_list(size, opts$dev.args) |
| 1165 |
args$cache = list( |
| 1166 |
path = if (args$cache) opts$cache.path, vars = opts$cache.vars, |
| 1167 |
hash = opts$cache.hash, extra = opts$cache.extra, keep = opts$cache.keep, |
| 1168 |
id = opts$label, rw = opts$cache.rw |
| 1169 |
) |
| 1170 |
do.call(xfun::record, c(list(code = x$source, envir = fuse_env()), args)) |
| 1171 |
} |
| 1172 |
|
| 1173 |
# the Markdown engine: echo Markdown source verbatim, and also output it as-is |
| 1174 |
eng_md = function(x, inline = FALSE, ...) { |
| 1175 |
s = x$source |
| 1176 |
if (inline) { |
| 1177 |
f = unlist(match_all(s, '`+')) # how many backticks to quote the text? |
| 1178 |
f = if (length(f)) paste0('`', max(f)) else '`' |
| 1179 |
one_string(c(f, s, f, s), ' ') |
| 1180 |
} else list(new_source(s), new_asis(s)) |
| 1181 |
} |
| 1182 |
|
| 1183 |
# the Mermaid engine: put code in ```mermaid and add caption if necessary |
| 1184 |
eng_mermaid = function(x, inline = FALSE, ...) { |
| 1185 |
code = fenced_block(src <- x$source, 'mermaid') |
| 1186 |
opts = reactor() |
| 1187 |
code = add_cap(code, opts$fig.cap, opts$label, opts$cap.pos, opts$fig.env) |
| 1188 |
if (inline) one_string(c(code, '')) else { |
| 1189 |
list(new_source(src), new_asis(code)) |
| 1190 |
} |
| 1191 |
} |
| 1192 |
|
| 1193 |
# embed a file verbatim |
| 1194 |
eng_embed = function(x, ...) { |
| 1195 |
s = x$source; opts = reactor() |
| 1196 |
# if chunk option `file` is empty, use source code as the list of files |
| 1197 |
if (is.null(f <- opts$file)) { |
| 1198 |
f = gsub('^["\']|["\']$', '', s) # in case paths are quoted |
| 1199 |
if (length(f) == 0) return() |
| 1200 |
s = read_all(f) |
| 1201 |
} |
| 1202 |
opts_new = list(comment = '') # don't comment out file content |
| 1203 |
# use the filename extension as the default language name |
| 1204 |
if (is.null(opts$attr.output) && nchar(lang <- file_ext(f[1])) > 1) { |
| 1205 |
lang = sub('^R', '', lang) # Rmd -> md, Rhtml -> html, etc. |
| 1206 |
if (lang == 'nw') lang = 'tex' |
| 1207 |
opts_new$attr.output = paste0('.', lang) |
| 1208 |
} |
| 1209 |
structure(list(new_output(s)), options = opts_new) |
| 1210 |
} |
| 1211 |
|
| 1212 |
eng_html = function(x, inline = FALSE, html = NULL) { |
| 1213 |
out = fenced_block(html, '=html') |
| 1214 |
if (inline) one_string(c(out, '')) else list(new_source(x$source), new_asis(out)) |
| 1215 |
} |
| 1216 |
|
| 1217 |
eng_css = function(x, inline = FALSE, ...) { |
| 1218 |
if (is.character(h <- reactor('href'))) { |
| 1219 |
res = sprintf('<link rel="stylesheet" href="%s">', h) |
| 1220 |
if (inline) one_string(res) else list(new_asis(res)) |
| 1221 |
} else { |
| 1222 |
eng_html(x, inline, c('<style type="text/css">', x$source, '</style>')) |
| 1223 |
} |
| 1224 |
} |
| 1225 |
|
| 1226 |
eng_js = function(x, inline = FALSE, ...) { |
| 1227 |
opts = reactor() |
| 1228 |
a = list(type = opts$type, src = opts$src) |
| 1229 |
for (i in c('type', 'src')) a[[i]] = a[[i]] # remove NULL |
| 1230 |
if (is.character(s <- a$src)) { |
| 1231 |
if (!isFALSE(opts$defer)) a['defer'] = list(NULL) |
| 1232 |
res = html_tag('script', NULL, a) |
| 1233 |
if (inline) one_string(res) else list(new_asis(res)) |
| 1234 |
} else { |
| 1235 |
if (identical(a$type, 'module')) a$defer = NULL |
| 1236 |
eng_html(x, inline, html_tag('script', html_value(x$source), a)) |
| 1237 |
} |
| 1238 |
} |
| 1239 |
|
| 1240 |
#' Language engines |
| 1241 |
#' |
| 1242 |
#' Get or set language engines for evaluating code chunks and inline code. |
| 1243 |
#' |
| 1244 |
#' An engine function should have three arguments: |
| 1245 |
#' |
| 1246 |
#' - `x`: An element in the [crack()] list (a code chunk or a text block). |
| 1247 |
#' |
| 1248 |
#' - `inline`: It indicates if `x` is from a code chunk or inline code. |
| 1249 |
#' |
| 1250 |
#' - `...`: Currently unused but recommended for future compatibility (more |
| 1251 |
#' arguments might be passed to the function). |
| 1252 |
#' |
| 1253 |
#' The function should return a character value. |
| 1254 |
#' @inheritParams reactor |
| 1255 |
#' @return The usage is similar to [reactor()]: `engines('LANG')` returns an |
| 1256 |
#' engine function for the language `LANG`, and `engines(LANG = function(x, |
| 1257 |
#' inline = FALSE, ...) {})` sets the engine for a language. |
| 1258 |
#' @export |
| 1259 |
#' @examples |
| 1260 |
#' litedown::engines() # built-in engines |
| 1261 |
engines = new_opts() |
| 1262 |
engines( |
| 1263 |
r = eng_r, md = eng_md, mermaid = eng_mermaid, embed = eng_embed, |
| 1264 |
css = eng_css, js = eng_js |
| 1265 |
) |
| 1266 |
|
| 1267 |
#' @export |
| 1268 |
print.litedown_env = function(x, ...) { |
| 1269 |
str(as.list(x, all.names = TRUE, sorted = TRUE), ...) |
| 1270 |
invisible(x) |
| 1271 |
} |