| 1 |
# functions extracted from knitr and to be reused in other packages like litedown |
| 2 |
|
| 3 |
#' Parse comma-separated chunk options |
| 4 |
#' |
| 5 |
#' For \pkg{knitr} and R Markdown documents, code chunk options can be written |
| 6 |
#' using the comma-separated syntax (e.g., `opt1=value1, opt2=value2`). This |
| 7 |
#' function parses these options and returns a list. If an option is not named, |
| 8 |
#' it will be treated as the chunk label. |
| 9 |
#' @param x The chunk options as a string. |
| 10 |
#' @return A list of chunk options. |
| 11 |
#' @export |
| 12 |
#' @examples |
| 13 |
#' xfun::csv_options('foo, eval=TRUE, fig.width=5, echo=if (TRUE) FALSE') |
| 14 |
csv_options = function(x) { |
| 15 |
x = one_string(x) |
| 16 |
res = handle_error( |
| 17 |
eval(parse_only(paste('alist(', quote_label(x), ')'))), |
| 18 |
function(loc) { |
| 19 |
if (loc != '') loc = paste(' at lines', loc) |
| 20 |
c( |
| 21 |
sprintf('Invalid syntax for chunk options%s:\n', loc), x, |
| 22 |
'\nPlease see documentation at https://yihui.org/knitr/options/.\n' |
| 23 |
) |
| 24 |
} |
| 25 |
) |
| 26 |
idx = which(names(res) == '') # which option is not named? |
| 27 |
# remove empty options |
| 28 |
j = NULL |
| 29 |
for (i in idx) if (identical(res[[i]], alist(,)[[1]])) j = c(j, i) |
| 30 |
if (length(j)) res[j] = NULL |
| 31 |
idx = if (is.null(names(res)) && length(res) == 1L) 1L else which(names(res) == '') |
| 32 |
if ((n <- length(idx)) > 1L || (length(res) > 1L && is.null(names(res)))) stop( |
| 33 |
'Invalid chunk options: ', x, |
| 34 |
"\n\nAll options must be of the form 'tag=value' except for the chunk label." |
| 35 |
) |
| 36 |
if (is.null(res$label)) { |
| 37 |
if (n == 0L) res$label = '' else names(res)[idx] = 'label' |
| 38 |
} |
| 39 |
if (!is.character(res$label)) |
| 40 |
res$label = gsub(' ', '', as.character(as.expression(res$label))) |
| 41 |
if (res$label == '') res$label = NULL |
| 42 |
res |
| 43 |
} |
| 44 |
|
| 45 |
# quote the chunk label if necessary |
| 46 |
quote_label = function(x) { |
| 47 |
x = gsub('^\\s*,?', '', x) |
| 48 |
if (grepl('^\\s*[^\'"](,|\\s*$)', x)) { |
| 49 |
# <<a,b=1>>= ---> <<'a',b=1>>= |
| 50 |
x = gsub('^\\s*([^\'"])(,|\\s*$)', "'\\1'\\2", x) |
| 51 |
} else if (grepl('^\\s*[^\'"](,|[^=]*(,|\\s*$))', x)) { |
| 52 |
# <<abc,b=1>>= ---> <<'abc',b=1>>= |
| 53 |
x = gsub('^\\s*([^\'"][^=]*)(,|\\s*$)', "'\\1'\\2", x) |
| 54 |
} |
| 55 |
x |
| 56 |
} |
| 57 |
|
| 58 |
# comment characters for various languages |
| 59 |
comment_chars = list( |
| 60 |
`#` = c('awk', 'bash', 'coffee', 'gawk', 'julia', 'octave', 'perl', 'powershell', 'python', 'r', 'ruby', 'sed', 'stan'), |
| 61 |
'//' = c('asy', 'cc', 'csharp', 'd3', 'dot', 'fsharp', 'go', 'groovy', 'java', 'js', 'node', 'ojs', 'Rcpp', 'sass', 'scss', 'scala'), |
| 62 |
`%%` = c('mermaid'), |
| 63 |
`%` = c('matlab', 'tikz'), |
| 64 |
`/* */` = c('c', 'css'), |
| 65 |
`* ;` = c('sas'), |
| 66 |
`--` = c('haskell', 'lua', 'mysql', 'psql', 'sql'), |
| 67 |
`!` = c('fortran', 'fortran95'), |
| 68 |
`*` = c('stata') |
| 69 |
) |
| 70 |
# reshape it using the language name as the index, i.e., from list(char = lang) |
| 71 |
# to list(lang = char) |
| 72 |
comment_chars = local({ |
| 73 |
res = list(apl = '\u235D') |
| 74 |
for (i in names(comment_chars)) { |
| 75 |
chars = comment_chars[[i]] |
| 76 |
res = c(res, setNames(rep(list(strsplit(i, ' ')[[1]]), length(chars)), chars)) |
| 77 |
} |
| 78 |
res[order(names(res))] |
| 79 |
}) |
| 80 |
|
| 81 |
get_option_comment = function(engine) { |
| 82 |
char = comment_chars[[engine]] %||% '#' |
| 83 |
s1 = paste0(char[[1]], '| ') |
| 84 |
s2 = ifelse(length(char) > 1, char[[2]], '') |
| 85 |
list(start = s1, end = s2) |
| 86 |
} |
| 87 |
|
| 88 |
#' Divide chunk options from the code chunk body |
| 89 |
#' |
| 90 |
#' Chunk options can be written in special comments (e.g., after `#|` for R code |
| 91 |
#' chunks) inside a code chunk. This function partitions these options from the |
| 92 |
#' chunk body. |
| 93 |
#' @param engine The name of the language engine (to determine the appropriate |
| 94 |
#' comment character). |
| 95 |
#' @param code A character vector (lines of code). |
| 96 |
#' @param strict If `FALSE`, allow chunk options to be written after `#|` even |
| 97 |
#' if `#` is not the comment character of the engine (e.g., when `engine = |
| 98 |
#' 'js'`), otherwise throw an error if `#|` is detected but `#` is not the |
| 99 |
#' comment character. |
| 100 |
#' @param ... Arguments to be passed to [yaml_load()]. |
| 101 |
#' @return A list with the following items: |
| 102 |
#' |
| 103 |
#' - `options`: The parsed options (if there are any) as a list. |
| 104 |
#' - `src`: The part of the input that contains the options. |
| 105 |
#' - `code`: The part of the input that contains the code. |
| 106 |
#' |
| 107 |
#' @note Chunk options must be written on _continuous_ lines (i.e., all lines |
| 108 |
#' must start with the special comment prefix such as `#|`) at the beginning |
| 109 |
#' of the chunk body. |
| 110 |
#' @export |
| 111 |
#' @examples |
| 112 |
#' # parse yaml-like items |
| 113 |
#' yaml_like = c("#| label: mine", "#| echo: true", "#| fig.width: 8", "#| foo: bar", "1 + 1") |
| 114 |
#' writeLines(yaml_like) |
| 115 |
#' xfun::divide_chunk("r", yaml_like) |
| 116 |
#' |
| 117 |
#' # parse CSV syntax |
| 118 |
#' csv_like = c("#| mine, echo = TRUE, fig.width = 8, foo = 'bar'", "1 + 1") |
| 119 |
#' writeLines(csv_like) |
| 120 |
#' xfun::divide_chunk("r", csv_like) |
| 121 |
divide_chunk = function(engine, code, strict = FALSE, ...) { |
| 122 |
res = list(options = NULL, src = NULL, code = code) |
| 123 |
# mask out empty blocks |
| 124 |
if (length(code) == 0) return(res) |
| 125 |
|
| 126 |
opt_comment = get_option_comment(engine) |
| 127 |
s1 = opt_comment$start |
| 128 |
s2 = opt_comment$end |
| 129 |
|
| 130 |
# check for option comments |
| 131 |
i1 = startsWith(code, s1) |
| 132 |
# if "commentChar| " is not found, try "#| " instead |
| 133 |
if (!i1[1] && s1 != '#| ') { |
| 134 |
i1 = startsWith(code, '#| ') |
| 135 |
if (strict && i1[1]) stop2( |
| 136 |
"The chunk options should start with '", s1, "' instead of '#| '", |
| 137 |
if (s2 != '') c(", and end with '", s2, "'"), '.' |
| 138 |
) |
| 139 |
s1 = '#| '; s2 = '' |
| 140 |
} |
| 141 |
# must have at least one matched line at the beginning |
| 142 |
if (!i1[[1]]) return(res) |
| 143 |
|
| 144 |
# end of the pipe comment block |
| 145 |
n2 = if (s2 == '') { |
| 146 |
i2 = TRUE |
| 147 |
if (all(i1)) length(code) else which.min(i1) - 1 # which.min() finds first FALSE |
| 148 |
} else { |
| 149 |
i2 = endsWith(trimws(code, 'right'), s2) |
| 150 |
if (i2[1]) which.min(i2) - 1 else which.max(i2) |
| 151 |
} |
| 152 |
|
| 153 |
# divide into yaml and code |
| 154 |
i = 1:n2; src = code[i]; code = code[-i] |
| 155 |
|
| 156 |
# extract meta from comments, then parse it |
| 157 |
c1 = nchar(s1) * i1[i] + 1 |
| 158 |
c2 = nchar(src) - if (s2 == '') 0 else nchar(s2) * i2[i] |
| 159 |
meta = substr(src, c1, c2) |
| 160 |
# see if the metadata looks like YAML or CSV |
| 161 |
if (grepl('^[^ :]+:($|\\s)', meta[1])) { |
| 162 |
meta = yaml_load(meta, envir = FALSE, ...) |
| 163 |
if (!is.list(meta) || length(names(meta)) == 0) { |
| 164 |
warning('Invalid YAML option format in chunk: \n', one_string(meta), '\n') |
| 165 |
meta = list() |
| 166 |
} |
| 167 |
} else { |
| 168 |
meta = csv_options(meta) |
| 169 |
} |
| 170 |
|
| 171 |
# normalize field name 'id' to 'label' if provided |
| 172 |
meta$label = unlist(meta[c('label', 'id')])[[1]] |
| 173 |
meta$id = NULL |
| 174 |
|
| 175 |
# extract code |
| 176 |
if (length(code) > 0 && is_blank(code[[1]])) { |
| 177 |
code = code[-1] |
| 178 |
src = c(src, '') |
| 179 |
} |
| 180 |
|
| 181 |
list(options = meta, src = src, code = code) |
| 182 |
} |
| 183 |
|
| 184 |
# change chunk option `tag=value` to `tag = value`, i.e., add spaces around = |
| 185 |
chunk_spaces = function(dir = '.', pattern = '[.]Rmd$') { |
| 186 |
for (f in list.files(dir, pattern, full.names = TRUE, recursive = TRUE)) |
| 187 |
process_file(f, function(x) { |
| 188 |
i = grep('^\\s*(> )*(#[|] |```+\\s*\\{)', x) |
| 189 |
x[i] = gsub('(?<! )=', ' =', x[i], perl = TRUE) |
| 190 |
x[i] = gsub('=(?! )', '= ', x[i], perl = TRUE) |
| 191 |
x |
| 192 |
}) |
| 193 |
} |