Debian Codegraph @

R/brew.R

raw
1 #' Brew in pandoc format
2 #'
3 #' This function behaves just like \code{brew} except for the \code{<\%=...\%>} tags, where \code{Pandoc.brew} first translate the R object found between the tags to Pandoc's markdown before passing to the \code{cat} function.
4 #'
5 #' This parser tries to be smart in some ways:
6 #'
7 #' \itemize{
8 #' \item a block (R commands between the tags) could return any value at any part of the block and there are no restrictions about the number of returned R objects
9 #' \item plots and images are grabbed in the document, rendered to a png file and \code{pander} method would result in a Pandoc's markdown formatted image link (so the image would be shown/included in the exported document). The images are put in \code{plots} directory in current \code{getwd()} or to the specified \code{output} file's directory.
10 #' \item all warnings/messages and errors are recorded in the blocks and returned in the document as a footnote
11 #' }
12 #'
13 #' Please see my Github page for details (\url{https://rapporter.github.io/pander/#brew-to-pandoc}) and examples (\url{https://rapporter.github.io/pander/#examples}).
14 #' @param file file path of the brew template. As this is passed to \code{readLines}, \code{file} could be an URL too, but not over SSL (for that latter \code{RCurl} would be needed).
15 #' @param output (optional) file path of the output file
16 #' @param convert string: format of required output document (besides Pandoc's markdown). Pandoc is called if set via \code{Pandoc.convert} and the converted document could be also opened automatically (see below).
17 #' @param open try to open converted document with operating system's default program
18 #' @param graph.name character string (default to \code{\%t} when \code{output} is set to \code{stdout} and \code{paste0(basename(output), '-\%n')} otherwise) passed to \code{\link{evals}}. Besides \code{\link{evals}}'s possible tags \code{\%i} is also available which would be replaced by the chunk number (and optionally an integer which would handle nested \code{brew} calls) and \code{\%I} with the order of the current expression.
19 #' @param graph.dir character string (default to \code{tempdir()} when \code{output} is set to \code{stdout} and \code{dirname(graph.name)} otherwise) passed to \code{\link{evals}}
20 #' @param graph.hi.res render high resolution images of plots? Default is \code{FALSE} except for HTML output.
21 #' @param text character vector (treated as the content of the \code{file}
22 #' @param envir environment where to \code{brew} the template
23 #' @param append should append or rather overwrite (default) the \code{output} markdown text file? Please note that this option only affects the markdown file and not the optionally created other formats.
24 #' @param ... additional parameters passed to \code{\link{Pandoc.convert}}
25 #' @note Only one of the input parameters (\code{file} or \code{text}) is to be used at once!
26 #' @export
27 #' @importFrom utils tail head capture.output
28 #' @return converted file name with full path if \code{convert} is set, none otherwise
29 #' @references \itemize{
30 #' \item Jeffrey Horner (2011). _brew: Templating Framework for Report Generation._ \url{https://cran.r-project.org/package=brew}
31 #' \item John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
32 #' }
33 #' @examples \dontrun{
34 #' text <- paste('# Header', '',
35 #' 'What a lovely list:\n<%=as.list(runif(10))%>',
36 #' 'A wide table:\n<%=mtcars[1:3, ]%>',
37 #' 'And a nice chart:\n\n<%=plot(1:10)%>', sep = '\n')
38 #' Pandoc.brew(text = text)
39 #' Pandoc.brew(text = text, output = tempfile(), convert = 'html')
40 #' Pandoc.brew(text = text, output = tempfile(), convert = 'pdf')
41 #'
42 #' ## pi is awesome
43 #' Pandoc.brew(text='<%for (i in 1:5) {%>\n Pi has a lot (<%=i%>) of power: <%=pi^i%><%}%>')
44 #'
45 #' ## package bundled examples
46 #' Pandoc.brew(system.file('examples/minimal.brew', package='pander'))
47 #' Pandoc.brew(system.file('examples/minimal.brew', package='pander'),
48 #' output = tempfile(), convert = 'html')
49 #' Pandoc.brew(system.file('examples/short-code-long-report.brew', package='pander'))
50 #' Pandoc.brew(system.file('examples/short-code-long-report.brew', package='pander'),
51 #' output = tempfile(), convert = 'html')
52 #'
53 #' ## brew returning R objects
54 #' str(Pandoc.brew(text='Pi equals to <%=pi%>.
55 #' And here are some random data:\n<%=runif(10)%>'))
56 #'
57 #' str(Pandoc.brew(text='# Header <%=1%>\nPi is <%=pi%> which is smaller then <%=2%>.
58 #' foo\nbar\n <%=3%>\n<%=mtcars[1:2,]%>'))
59 #'
60 #' str(Pandoc.brew(text='<%for (i in 1:5) {%>
61 #' Pi has a lot (<%=i%>) of power: <%=pi^i%><%}%>'))
62 #' }
63 Pandoc.brew <- function(file = stdin(), output = stdout(), convert = FALSE, open = TRUE,
64 graph.name, graph.dir, graph.hi.res = FALSE, text = NULL,
65 envir = parent.frame(), append = FALSE, ...) {
66
67 timer <- proc.time()
68 output.stdout <- deparse(substitute(output)) == 'stdout()'
69
70 if (identical(convert, FALSE)) {
71 open <- FALSE
72 } else {
73 if (output.stdout) {
74 stop('A file name should be provided while converting a document.')
75 }
76 }
77
78 if (!output.stdout) {
79 basedir <- dirname(output)
80 if (missing(graph.name)) {
81 graph.name <- paste0(basename(output), '-%n')
82 }
83 if (missing(graph.dir)) {
84 graph.dir <- file.path(basedir, 'plots')
85 }
86 } else {
87 if (missing(graph.name)) {
88 graph.name <- '%t'
89 }
90 if (missing(graph.dir)) {
91 graph.dir <- file.path(tempdir(), 'plots')
92 }
93 }
94
95 if (is.null(text)) {
96 text <- paste(readLines(file, warn = FALSE), collapse = '\n')
97 }
98
99 ## id of chunk
100 assign('cmdID', 0, envir = debug)
101 assign('chunkID', 0, envir = debug)
102 assign('nested', debug$nested + 1, envir = debug)
103 assign('nestedID', debug$nestedID + 1, envir = debug)
104
105 ## helper fn
106 showCode <- function(..., envir = parent.frame(), cache = evalsOptions('cache')) {
107
108 ## increment chunk ID
109 assign('chunkID', debug$chunkID + 1, envir = debug)
110
111 ## evaluate chunk
112 res <- evals(unlist(...), env = envir, graph.dir = graph.dir, graph.name = graph.name, hi.res = graph.hi.res)
113
114 ## format 'em
115 for (r in res) {
116
117 r.pander <- tryCatch(pander_return(r), error = function(e) e)
118 if (inherits(r.pander, 'error')) {
119 r.pander <- paste0('Internal `pander` error: `',
120 r.pander$message,
121 '` while running: `',
122 r$src,
123 '`\n\nPlease [report the issue](https://github.com/Rapporter/pander/issues/new) with a reproducible example to help developers fix this ASAP.') #nolint
124 }
125 r$output <- r.pander
126 cat(paste(r.pander, collapse = '\n'))
127
128 localstorage <- get('.storage', envir = envir)
129 localstorage.last <- tail(localstorage, 1)[[1]]
130 localstorage.last.text <- ifelse(is.null(localstorage.last$text$eval), '', localstorage.last$text$eval)
131
132 if ('image' %in% r$type
133 || length(r.pander) > 1
134 || grepl('\n$', localstorage.last.text)
135 || is.null(localstorage.last$text$eval)) {
136 type <- 'block'
137 } else {
138 type <- 'inline'
139 }
140
141 if (type == 'inline') {
142
143 localstorage[[length(localstorage)]]$text <- list(raw = paste0(localstorage.last$text$raw, paste0('<%=', r$src, '%>')), #nolint
144 eval = paste0(localstorage.last$text$eval, r.pander)) #nolint
145 localstorage[[length(localstorage)]]$chunks <- list(raw = c(localstorage.last$chunks$raw, paste0('<%=', r$src, '%>')), #nolint
146 eval = c(localstorage.last$chunks$eval, ifelse(length(r.pander) == 0, '', r.pander))) #nolint
147 localstorage[[length(localstorage)]]$msg <- list(messages = c(localstorage.last$msg$messages, r$msg$messages), #nolint
148 warnings = c(localstorage.last$msg$warnings, r$msg$warnings), #nolint
149 errors = c(localstorage.last$msg$errors, r$msg$errors)) #nolint
150
151 } else {
152 localstorage <- c(localstorage, list(list(type = 'block', robject = r)))
153 }
154
155 assign('.storage', localstorage, envir = envir)
156
157 }
158 }
159 assign('showCode', showCode, envir = envir)
160
161 assign('.storage', NULL, envir = envir)
162 res <- capture.output(brew(text = text, envir = envir))
163
164 ## remove absolute path from image links
165 if (!output.stdout) {
166 res <- gsub(sprintf(']\\(%s/', basedir), ']\\(', res, fixed = TRUE)
167 }
168
169 cat(remove.extra.newlines(paste(res, collapse = '\n')), '\n', file = output, append = append)
170
171 if (is.character(convert)) {
172 Pandoc.convert(output, format = convert, open = open, proc.time = as.numeric(proc.time() - timer)[3], ...)
173 }
174
175 ## there is no sense of chunkID outside of brew
176 assign('chunkID', NULL, envir = debug)
177 assign('cmdID', NULL, envir = debug)
178 assign('nested', debug$nested - 1, envir = debug)
179 if (debug$nested == 0) {
180 assign('nestedID', 0, envir = debug)
181 }
182
183 invisible(get('.storage', envir = envir))
184
185 }
186
187
188 ######################################################################################
189 # This is a forked/patched version of `brew` package made by Jeffrey Horner (c) 2007.
190 # Original sources can be found at: https://cran.r-project.org/package=brew
191 ######################################################################################
192
193 BRTEXT <- 1
194 BRCODE <- 2
195 BRCOMMENT <- 3
196 BRCATCODE <- 4
197 DELIM <- list()
198 DELIM[[BRTEXT]] <- c('', '')
199 DELIM[[BRCODE]] <- c('<%', '%>')
200 DELIM[[BRCOMMENT]] <- c('<%#', '%>')
201 DELIM[[BRCATCODE]] <- c('<%=', '%>')
202
203 #' Patched brew
204 #'
205 #' This is a forked/patched version of `brew` package made by Jeffrey Horner (c) 2007. See: \code{References} about the original version.
206 #'
207 #' This custom function can do more and also less compared to the original \code{brew} package. First of all the internal caching mechanism (and other, from \code{pander} package POV needless features) of `brew` is removed for some extra profits:
208 #' \itemize{
209 #' \item multiple R expressions can be passed between \code{<\%= ... \%>} tags,
210 #' \item the text of the file and also the evaluated R objects are (invisibly) returned in a structured list, which can be really useful while post-processing the results of `brew`.
211 #' }
212 #' @param text character vector
213 #' @param envir environment
214 #' @return \code{brew}ed document to \code{stdout} and raw results while evaluating the \code{text} in a structured list.
215 #' @note This function should be never called directly (use \code{brew::brew} instead) as being a helper function of \code{Pandoc.brew}.
216 #' @seealso \code{\link{Pandoc.brew}}
217 #' @references Jeffrey Horner (2011). _brew: Templating Framework for Report Generation._ \url{https://cran.r-project.org/package=brew}
218 #' @keywords internal
219 `brew` <- function(text = NULL, envir = parent.frame()) {
220
221 if (is.character(text) && nchar(text[1]) > 0) {
222 icon <- textConnection(text[1])
223 } else {
224 stop('Invalid input.')
225 }
226
227 if (!is.environment(envir)) {
228 stop('Invalid environment')
229 }
230
231 state <- BRTEXT
232 text <- code <- character(0)
233 textLen <- codeLen <- as.integer(0)
234 textStart <- as.integer(1)
235 line <- ''
236
237 while (TRUE) {
238 if (!nchar(line)){
239 line <- readLines(icon, 1)
240 if (length(line) != 1){
241 break
242 }
243 line <- paste(line, '\n', sep = '')
244 }
245 if (state == BRTEXT){
246
247 spl <- strsplit(line, DELIM[[BRCODE]], fixed = TRUE)[[1]]
248
249 ## Beginning markup found
250 if (length(spl) > 1){
251
252 if (nchar(spl[1])) {
253 text[textLen + 1] <- spl[1]
254 textLen <- textLen + 1
255 }
256 line <- paste(spl[-1], collapse = '<%')
257
258 ## We know we've found this so far, so go ahead and set up state.
259 state <- BRCODE
260
261 ## Now let's search for additional markup.
262 if (regexpr('^=', spl[2]) > 0){
263 state <- BRCATCODE
264 line <- sub('^=', '', line)
265 } else if (regexpr('^#', spl[2]) > 0){
266 state <- BRCOMMENT
267 }
268
269 if (textStart <= textLen) {
270 code[codeLen + 1] <- paste('showText(', textStart, ',', textLen, ')', sep = '')
271 codeLen <- codeLen + 1
272 textStart <- textLen + 1
273 }
274 } else {
275 text[textLen + 1] <- line
276 textLen <- textLen + 1
277 line <- ''
278 }
279 } else {
280 if (regexpr('%>', line, perl = TRUE) > 0){
281 spl <- strsplit(line, '%>', fixed = TRUE)[[1]]
282 line <- paste(spl[-1], collapse = '%>')
283
284 n <- nchar(spl[1])
285 ## test for '-' immediately preceding %> will strip trailing newline from line
286 if (n > 0) {
287 if (substr(spl[1], n, n) == '-') {
288 line <- substr(line, 1, nchar(line) - 1)
289 spl[1] <- substr(spl[1], 1, n - 1)
290 }
291 text[textLen + 1] <- spl[1]
292 textLen <- textLen + 1
293 }
294
295 ## We've found the end of a brew section, but we only care if the
296 ## section is a BRCODE or BRCATCODE. We just implicitly drop BRCOMMENT sections
297 if (state == BRCODE){
298 code[codeLen + 1] <- paste(text[textStart:textLen], collapse = '')
299 codeLen <- codeLen + 1
300 } else if (state == BRCATCODE){
301 code[codeLen + 1] <- paste0('showCode(',
302 deparse(paste(text[textStart:textLen], collapse = '\n')), ')')
303 codeLen <- codeLen + 1
304 }
305 textStart <- textLen + 1
306 state <- BRTEXT
307 } else if (regexpr('<%', line, perl = TRUE) > 0){
308 stop('Oops! Someone forgot to close a tag. We saw: ',
309 DELIM[[state]][1], ' and we need ',
310 DELIM[[state]][2])
311 } else {
312 text[textLen + 1] <- line
313 textLen <- textLen + 1
314 line <- ''
315 }
316 }
317 }
318 if (state == BRTEXT){
319 if (textStart <= textLen) {
320 code[codeLen + 1] <- paste('showText(', textStart, ',', textLen, ')', sep = '')
321 codeLen <- codeLen + 1
322 textStart <- textLen + 1
323 }
324 } else {
325 stop('Oops! Someone forgot to close a tag. We saw: ',
326 DELIM[[state]][1], ' and we need ',
327 DELIM[[state]][2], call. = FALSE)
328 }
329
330 showText <- function(from, to) {
331
332 localtexts <- text[from:to]
333 for (localtext in localtexts) {
334
335 cat(localtext)
336
337 if (grepl('^#+[ \t]+', localtext)) {
338 heading.level <- nchar(gsub('^(#{1,6})[ \t]+.*', '\\1', localtext))
339 localtext <- gsub('^#{1,6}[ \t]+', '', localtext)
340 type <- 'heading'
341 } else {
342 type <- 'text'
343 }
344
345 localstorage <- get('.storage', envir = envir)
346 localstorage.last <- tail(localstorage, 1)[[1]]
347 localstorage.last.text <- localstorage.last$text$eval
348 localstorage.last.type <- ifelse(is.null(localstorage.last$type), '', localstorage.last$type)
349
350 if (localstorage.last.type == 'block' & type == 'text' & localtext != '\n') {
351 localstorage.last.pander <- localstorage.last$robject$output
352
353 ## we had an inline chunk in the beginning of the line converted to block
354 if (!'image' %in% localstorage.last$robject$type && length(localstorage.last.pander) <= 1) {
355 localstorage <- c(localstorage[-length(localstorage)],
356 list(list(type = 'text',
357 text = list(
358 raw = paste0('<%=', localstorage.last$robject$src, '%>', localtext),
359 eval = paste0(localstorage.last.pander, localtext)),
360 chunks = list(
361 raw = paste0('<%=', localstorage.last$robject$src, '%>'),
362 eval = localstorage.last.pander
363 ),
364 msg = list(
365 messages = localstorage.last$robject$msg$messages,
366 warnings = localstorage.last$robject$msg$warnings,
367 errors = localstorage.last$robject$msg$errors
368 ))))
369 } else {
370 ## leave that block as is and add localtext as new
371 localstorage <- c(localstorage,
372 list(list(type = type,
373 text = list(raw = localtext, eval = localtext),
374 chunks = list(raw = NULL, eval = NULL),
375 msg = list(messages = NULL, warnings = NULL, errors = NULL))))
376 }
377
378 } else {
379
380 ## text continues
381 if (is.character(localstorage.last.text) &&
382 (type == 'text') &&
383 ifelse(localstorage.last.type == 'heading', !grepl('\n', localstorage.last.text), TRUE)) {
384 localstorage[[length(localstorage)]]$text <- list(raw = paste0(localstorage.last$text$raw, localtext), eval = paste0(localstorage.last.text, localtext)) #nolint
385 } else {
386 ## new text starts here
387 localstorage <- c(localstorage,
388 list(list(type = type,
389 text = list(raw = localtext, eval = localtext),
390 chunks = list(raw = NULL, eval = NULL),
391 msg = list(messages = NULL, warnings = NULL, errors = NULL))))
392 }
393 }
394
395 if (type == 'heading') {
396 localstorage[[length(localstorage)]]$level <- heading.level
397 }
398
399 assign('.storage', localstorage, envir = envir)
400
401 }
402
403 }
404
405 assign('showText', showText, envir = envir)
406
407 e <- tryCatch(eval(parse(text = code), envir = envir), error = function(e) e)
408
409 if (inherits(e, 'error')) {
410
411 msg <- e$message
412 assign('last', list(code = code, text = text, error = msg), envir = debug) # debug
413
414 brcodes <- code[!grepl('^show', code)]
415 if (length(brcodes) > 0) {
416 brcodes <- p(brcodes, wrap = '`')
417 if (grepl('[Uu]nexpected', msg)) {
418 stop(paste0('`',
419 sub('.*([Uu]nexpected [a-zA-Z0-9\\(\\)\'\\{\\} ]*)( at character|\n).*', '\\1', msg),
420 '` in your BRCODEs: ', brcodes), call. = FALSE)
421 } else {
422 stop(sprintf('Error (`%s`) in your BRCODEs: %s', msg, brcodes), call. = FALSE)
423 }
424 } else {
425
426 stop(paste0('Error: ', p(msg, wrap = '`')), call. = FALSE)
427 }
428 } else {
429 assign('last', list(code = code, text = text, result = e), envir = debug) # debug
430 }
431
432 invisible()
433
434 }