| 1 |
#' Spin goat's hair into wool |
| 2 |
#' |
| 3 |
#' This function takes a specially formatted R script and converts it to a |
| 4 |
#' literate programming document. By default normal text (documentation) should |
| 5 |
#' be written after the roxygen comment (\code{#'}) and code chunk options are |
| 6 |
#' written after \code{#|} or \code{#+} or \code{# \%\%} or \code{# ----}. |
| 7 |
#' |
| 8 |
#' Obviously the goat's hair is the original R script, and the wool is the |
| 9 |
#' literate programming document (ready to be knitted). |
| 10 |
#' @param hair Path to the R script. The script must be encoded in UTF-8 if it |
| 11 |
#' contains multibyte characters. |
| 12 |
#' @param knit Logical; whether to compile the document after conversion. |
| 13 |
#' @param report Logical; whether to generate a report for \file{Rmd}, |
| 14 |
#' \file{Rnw} and \file{Rtex} output. Ignored if \code{knit = FALSE}. |
| 15 |
#' @param text A character vector of code, as an alternative way to provide the |
| 16 |
#' R source. If \code{text} is not \code{NULL}, \code{hair} will be ignored. |
| 17 |
#' @param envir Environment for \code{\link{knit}()} to evaluate the code. |
| 18 |
#' @param format Character; the output format. The default is R Markdown. |
| 19 |
#' @param doc A regular expression to identify the documentation lines; by |
| 20 |
#' default it follows the roxygen convention, but it can be customized, e.g. |
| 21 |
#' if you want to use \code{##} to denote documentation, you can use |
| 22 |
#' \code{'^##\\\\s*'}. |
| 23 |
#' @param inline A regular expression to identify inline R expressions; by |
| 24 |
#' default, code of the form \code{\{\{code\}\}} on its own line is treated as |
| 25 |
#' an inline expression. |
| 26 |
#' @param comment A pair of regular expressions for the start and end delimiters |
| 27 |
#' of comments; the lines between a start and an end delimiter will be |
| 28 |
#' ignored. By default, the delimiters are \verb{/*} at the beginning of a |
| 29 |
#' line, and \verb{*/} at the end, following the convention of C comments. |
| 30 |
#' @param precious logical: whether intermediate files (e.g., \code{.Rmd} files |
| 31 |
#' when \code{format} is \code{"Rmd"}) should be preserved. The default is |
| 32 |
#' \code{FALSE} if \code{knit} is \code{TRUE} and the input is a file. |
| 33 |
#' @author Yihui Xie, with the original idea from Richard FitzJohn (who named it |
| 34 |
#' as \code{sowsear()} which meant to make a silk purse out of a sow's ear) |
| 35 |
#' @return If \code{text} is \code{NULL}, the path of the final output document, |
| 36 |
#' otherwise the content of the output. |
| 37 |
#' @note If the output format is \code{Rnw} and no document class is specified |
| 38 |
#' in roxygen comments, this function will automatically add the |
| 39 |
#' \code{article} class to the LaTeX document so that it is complete and can |
| 40 |
#' be compiled. You can always specify the document class and other LaTeX |
| 41 |
#' settings in roxygen comments manually. |
| 42 |
#' |
| 43 |
#' When the output format is \code{Rmd}, it is compiled to HTML via |
| 44 |
#' \code{\link{knit2html}()}, which uses R Markdown v1 instead of v2. If you |
| 45 |
#' want to use the latter, you should call |
| 46 |
#' \code{rmarkdown::\link[rmarkdown]{render}()} instead. Similarly, if the |
| 47 |
#' output format is \code{qmd}, you need to render the output with Quarto. |
| 48 |
#' @export |
| 49 |
#' @seealso \code{\link{stitch}} (feed a template with an R script) |
| 50 |
#' @references \url{https://yihui.org/knitr/demo/stitch/} |
| 51 |
spin = function( |
| 52 |
hair, knit = TRUE, report = TRUE, text = NULL, envir = parent.frame(), |
| 53 |
format = c('Rmd', 'Rnw', 'Rhtml', 'Rtex', 'Rrst', 'qmd'), |
| 54 |
doc = "^#+'[ ]?", inline = '^[{][{](.+)[}][}][ ]*$', |
| 55 |
comment = c("^[# ]*/[*]", "^.*[*]/ *$"), precious = !knit && is.null(text) |
| 56 |
) { |
| 57 |
|
| 58 |
format = match.arg(format) |
| 59 |
x = if (nosrc <- is.null(text)) read_utf8(hair) else split_lines(text) |
| 60 |
stopifnot(length(comment) == 2L) |
| 61 |
c1 = grep(comment[1], x); c2 = grep(comment[2], x) |
| 62 |
if (length(c1) != length(c2)) |
| 63 |
stop('comments must be put in pairs of start and end delimiters') |
| 64 |
# remove comments |
| 65 |
if (length(c1)) x = x[-unique(unlist(mapply(seq, c1, c2, SIMPLIFY = FALSE)))] |
| 66 |
|
| 67 |
# remove multiline string literals and symbols (note that this ignores lines with spaces at their |
| 68 |
# beginnings, assuming doc and inline regex don't match these lines anyway) |
| 69 |
is_matchable = function(x) { |
| 70 |
# if code can't be parsed, assume all lines are matchable |
| 71 |
p = tryCatch(parse(text = x, keep.source = TRUE), error = function(e) NULL) |
| 72 |
n = length(x) |
| 73 |
if (is.null(p)) return(rep(TRUE, n)) |
| 74 |
d = getParseData(p) |
| 75 |
seq_len(n) %in% d[d$col1 == 1, 'line1'] |
| 76 |
} |
| 77 |
matchable = is_matchable(x) |
| 78 |
|
| 79 |
# .Rmd/.qmd need to be treated specially |
| 80 |
is_md = grepl('^[Rq]md$', format) |
| 81 |
p = if (is_md) .fmt.rmd(x) else .fmt.pat[[tolower(format)]] |
| 82 |
|
| 83 |
# turn {{expr}} into inline expressions, e.g. `r expr` or \Sexpr{expr} |
| 84 |
if (any(i <- matchable & grepl(inline, x))) x[i] = gsub(inline, p[4], x[i]) |
| 85 |
|
| 86 |
r = rle((matchable & grepl(doc, x)) | i) # inline expressions are treated as doc instead of code |
| 87 |
n = length(r$lengths); txt = vector('list', n); idx = c(0L, cumsum(r$lengths)) |
| 88 |
|
| 89 |
for (i in seq_len(n)) { |
| 90 |
block = x[seq(idx[i] + 1L, idx[i + 1])] |
| 91 |
txt[[i]] = if (r$values[i]) { |
| 92 |
# normal text; just strip #' |
| 93 |
sub(doc, '', block) |
| 94 |
} else { |
| 95 |
# R code; #+/- indicates chunk options |
| 96 |
block = strip_white(block) # rm white lines in beginning and end |
| 97 |
if (!length(block)) next |
| 98 |
|
| 99 |
rc = '^(#|--)+(\\+| %%| ----+| @knitr)(.*?)\\s*-*\\s*$' |
| 100 |
j1 = grep(rc, block) |
| 101 |
# pipe comments (#|) should start a code chunk if they are not preceded by |
| 102 |
# chunk opening tokens |
| 103 |
j2 = setdiff(pipe_comment_start(block), j1 + 1) |
| 104 |
|
| 105 |
if (length(j3 <- c(j1, j2))) { |
| 106 |
block[j1] = paste0(p[1], gsub(rc, '\\3', block[j1]), p[2]) |
| 107 |
block[j2] = paste0(p[1], p[2], '\n', block[j2]) |
| 108 |
|
| 109 |
# close each chunk if there are multiple chunks in this block |
| 110 |
if (any(j3 > 1)) { |
| 111 |
j = j3[j3 > 1] |
| 112 |
block[j] = paste0(p[3], '\n', block[j]) |
| 113 |
} |
| 114 |
} |
| 115 |
if (!startsWith(block[1L], p[1L])) { |
| 116 |
block = c(paste0(p[1L], p[2L]), block) |
| 117 |
} |
| 118 |
c('', block, p[3L], '') |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
txt = unlist(txt) |
| 123 |
is_tex = grepl('^R(nw|tex)$', format) |
| 124 |
# make it a complete TeX document if document class not specified |
| 125 |
if (report && is_tex && !any(grepl('^\\s*\\\\documentclass', txt))) { |
| 126 |
txt = c('\\documentclass{article}', '\\begin{document}', txt, '\\end{document}') |
| 127 |
} |
| 128 |
if (nosrc) { |
| 129 |
outsrc = with_ext(hair, format) |
| 130 |
write_utf8(txt, outsrc) |
| 131 |
txt = NULL |
| 132 |
} else outsrc = NULL |
| 133 |
if (!knit) return(txt %n% outsrc) |
| 134 |
|
| 135 |
out = if (report) { |
| 136 |
if (is_md) { |
| 137 |
knit2html(outsrc, text = txt, envir = envir) |
| 138 |
} else if (!is.null(outsrc) && is_tex) { |
| 139 |
knit2pdf(outsrc, envir = envir) |
| 140 |
} |
| 141 |
} else knit(outsrc, text = txt, envir = envir) |
| 142 |
|
| 143 |
if (!precious && !is.null(outsrc)) file.remove(outsrc) |
| 144 |
invisible(out) |
| 145 |
} |
| 146 |
|
| 147 |
.fmt.pat = list( |
| 148 |
rnw = c('<<', '>>=', '@', '\\\\Sexpr{\\1}'), |
| 149 |
rhtml = c('<!--begin.rcode', '', 'end.rcode-->', '<!--rinline \\1 -->'), |
| 150 |
rtex = c('% begin.rcode', '', '% end.rcode', '\\\\rinline{\\1}'), |
| 151 |
rrst = c('.. {r', '}', '.. ..', ':r:`\\1`') |
| 152 |
) |
| 153 |
|
| 154 |
# determine how many backticks we need to wrap code blocks and inline code |
| 155 |
.fmt.rmd = function(x) { |
| 156 |
x = one_string(x) |
| 157 |
l = attr(gregexpr('`+', x)[[1]], 'match.length') |
| 158 |
l = max(l, 0) |
| 159 |
if (length(l) > 0) { |
| 160 |
i = strrep('`', l + 1) |
| 161 |
b = strrep('`', max(l + 1, 3)) |
| 162 |
} else { |
| 163 |
i = '`' |
| 164 |
b = '```' |
| 165 |
} |
| 166 |
c(paste0(b, '{r'), '}', b, paste0(i, 'r \\1 ', i)) |
| 167 |
} |
| 168 |
|
| 169 |
# find the position of the starting `#|` in a consecutive block of `#|` comments |
| 170 |
pipe_comment_start = function(x) { |
| 171 |
i = startsWith(x, '#| ') |
| 172 |
r = rle(i) |
| 173 |
l = r$lengths |
| 174 |
j = cumsum(l) - l + 1 |
| 175 |
j[r$values] |
| 176 |
} |
| 177 |
|
| 178 |
#' Spin a child R script |
| 179 |
#' |
| 180 |
#' This function is similar to \code{\link{knit_child}()} but is used in R |
| 181 |
#' scripts instead. When the main R script is not called via |
| 182 |
#' \code{\link{spin}()}, this function simply executes the child script via |
| 183 |
#' \code{\link{sys.source}()}, otherwise it calls \code{\link{spin}()} to spin |
| 184 |
#' the child script into a source document, and uses \code{\link{knit_child}()} |
| 185 |
#' to compile it. You can call this function in R code, or using the syntax of |
| 186 |
#' inline R expressions in \code{\link{spin}()} (e.g. |
| 187 |
#' \code{{{knitr::spin_child('script.R')}}}). |
| 188 |
#' @param input Filename of the input R script. |
| 189 |
#' @param format Passed to \code{format} in \code{spin()}. If not |
| 190 |
#' provided, it will be guessed from the current knitting process. |
| 191 |
#' @return A character string of the knitted R script. |
| 192 |
#' @export |
| 193 |
spin_child = function(input, format) { |
| 194 |
if (!isTRUE(getOption('knitr.in.progress'))) |
| 195 |
return(sys.source(input, parent.frame())) |
| 196 |
fmt = if (missing(format)) { |
| 197 |
if (is.null(fmt <- out_format())) |
| 198 |
stop('spin_child() must be called in a knitting process') |
| 199 |
.spin.fmt = c( |
| 200 |
'latex' = 'Rnw', 'sweave' = 'Rnw', 'listings' = 'Rnw', |
| 201 |
'html' = 'Rhtml', 'markdown' = 'Rmd' |
| 202 |
) |
| 203 |
if (is.na(fmt <- .spin.fmt[fmt])) |
| 204 |
stop('the document format ', fmt, ' is not supported yet') |
| 205 |
fmt |
| 206 |
} else format |
| 207 |
asis_output(knit_child( |
| 208 |
text = spin(text = read_utf8(input), knit = FALSE, report = FALSE, format = fmt), |
| 209 |
quiet = TRUE |
| 210 |
)) |
| 211 |
} |