Debian Codegraph @

R/html_notebook.R

raw
1 #' Convert to an HTML notebook
2 #'
3 #' Format for converting from R Markdown to an HTML notebook.
4 #'
5 #' See the \href{https://rmarkdown.rstudio.com/r_notebook_format.html}{online
6 #' documentation} for additional details on using the \code{html_notebook}
7 #' format.
8 #' @inheritParams html_document
9 #' @param output_source Define an output source for \R chunks (ie,
10 #' outputs to use instead of those produced by evaluating the
11 #' underlying \R code). See \code{\link{html_notebook_output}} for
12 #' more details.
13 #' @param self_contained Produce a standalone HTML file with no external
14 #' dependencies. Defaults to \code{TRUE}. In notebooks, setting this to
15 #' \code{FALSE} is not recommended, since the setting does not apply to
16 #' embedded notebook output such as plots and HTML widgets.
17 #' @importFrom evaluate evaluate
18 #' @export
19 html_notebook <- function(toc = FALSE,
20 toc_depth = 3,
21 toc_float = FALSE,
22 number_sections = FALSE,
23 fig_width = 7,
24 fig_height = 5,
25 fig_retina = 2,
26 fig_caption = TRUE,
27 code_folding = "show",
28 theme = "default",
29 highlight = "textmate",
30 highlight_downlit = FALSE,
31 math_method = "default",
32 mathjax = "default",
33 extra_dependencies = NULL,
34 css = NULL,
35 includes = NULL,
36 md_extensions = NULL,
37 pandoc_args = NULL,
38 output_source = NULL,
39 self_contained = TRUE,
40 ...)
41 {
42 # some global state that is captured in pre_knit
43 exit_actions <- list()
44 on_exit <- function() {
45 for (action in exit_actions)
46 try(action())
47 }
48
49 paged_table_html_asis = function(x) {
50 knitr::asis_output(
51 paged_table_html(x)
52 )
53 }
54
55 # define pre_knit hook
56 pre_knit <- function(input, ...) {
57
58 if (is.function(output_source)) {
59
60 # pull out 'output_source'
61 validate_output_source(output_source)
62
63 # force knitr labeling (required for uniqueness of labels + cache coherence)
64 knitr.duplicate.label <- getOption("knitr.duplicate.label")
65 if (identical(knitr.duplicate.label, "allow")) {
66 warning("unsetting 'knitr.duplicate.label' for duration of render")
67 options(knitr.duplicate.label = "deny")
68 exit_actions <<- c(exit_actions, function() {
69 options(knitr.duplicate.label = knitr.duplicate.label)
70 })
71 }
72
73 # force default unnamed chunk labeling scheme (for cache coherence)
74 unnamed.chunk.label <- knitr::opts_knit$get("unnamed.chunk.label")
75 if (!identical(unnamed.chunk.label, "unnamed-chunk")) {
76 warning("reverting 'unnamed.chunk.label' to 'unnamed-chunk' for duration of render")
77 knitr::opts_knit$set(unnamed.chunk.label = "unnamed-chunk")
78 exit_actions <<- c(exit_actions, function() {
79 knitr::opts_knit$set(unnamed.chunk.label = unnamed.chunk.label)
80 })
81 }
82
83 # if our output_source comes with a pre_knit hook, evaluate that
84 output_source_pre_knit <- attr(output_source, "pre_knit", exact = TRUE)
85 if (is.function(output_source_pre_knit))
86 try(output_source_pre_knit())
87
88 # track knit context
89 chunk_options <- list()
90
91 # use an 'include' hook to track chunk options (any
92 # 'opts_hooks' hook will do; we just want this to be called
93 # on entry to any chunk)
94 include_hook <- knitr::opts_hooks$get("include")
95 exit_actions <<- c(exit_actions, function() {
96 knitr::opts_hooks$set(
97 include = if (is.null(include_hook)) {
98 function(options) options
99 } else {
100 include_hook
101 }
102 )
103 })
104
105 knitr::opts_hooks$set(include = function(options) {
106
107 # save context
108 chunk_options <<- options
109
110 # force R engine (so that everything goes through evaluate
111 # hook and hence 'output_source')
112 options$engine <- "R"
113 options$engine.opts <- NULL
114
115 # disable caching
116 options$cache <- FALSE
117
118 # call original hook
119 if (is.function(include_hook))
120 include_hook(options)
121 else
122 options
123 })
124
125 # set up evaluate hook (override any pre-existing evaluate hook)
126 evaluate_hook <- knitr::knit_hooks$get("evaluate")
127 exit_actions <<- c(exit_actions, function() {
128 knitr::knit_hooks$set(evaluate = evaluate_hook)
129 })
130
131 knitr::knit_hooks$set(evaluate = function(code, ...) {
132 chunk_options <- merge_render_context(chunk_options)
133 context <- list2env(chunk_options)
134 output <- output_source(code, context, ...)
135 as_evaluate_output(output, context, ...)
136 })
137 }
138
139 # set large max.print for knitr sql engine (since we will give
140 # it a scrolling treatment)
141 knit_sql_max_print <- knitr::opts_knit$get('sql.max.print');
142 if (is.null(knit_sql_max_print)) {
143 knitr::opts_knit$set(sql.max.print = 1000)
144 exit_actions <<- c(exit_actions, function() {
145 knitr::opts_knit$set(sql.max.print = knit_sql_max_print)
146 })
147 }
148
149 # set sql.print to use paged tables
150 knit_sql_print <- knitr::opts_knit$get('sql.print');
151 if (is.null(knit_sql_print)) {
152 knitr::opts_knit$set(sql.print = paged_table_html)
153 exit_actions <<- c(exit_actions, function() {
154 knitr::opts_knit$set(sql.print = knit_sql_print)
155 })
156 }
157 }
158
159 # pre-processor adds kable-scroll argument to give scrolling treatment for
160 # data frames (which are printed via kable by default)
161 pre_processor <- function(metadata, input_file, runtime, knit_meta, files_dir,
162 output_dir) {
163 args <- c()
164 args <- c(args, pandoc_variable_arg("kable-scroll", "1"))
165 args
166 }
167
168 # post-processor to rename output file if necessary
169 post_processor <- function(metadata, input_file, output_file, clean, verbose) {
170
171 # rename to .nb.html if necessary
172 nb_output_file <- output_file
173 if (!ends_with_bytes(output_file, ".nb.html")) {
174 nb_output_file <- gsub("\\.html$", ".nb.html", output_file)
175 file.rename(output_file, nb_output_file)
176 }
177
178 nb_output_file
179 }
180
181 # these arguments to html_document are fixed so we need to
182 # flag them as invalid for users
183 fixed_args <- c("keep_md", "template", "lib_dir", "dev")
184 forwarded_args <- names(list(...))
185 for (arg in forwarded_args) {
186 if (arg %in% fixed_args)
187 stop("The ", arg, " option is not valid for the html_notebook format.")
188 }
189
190 # add dependencies
191 extra_dependencies <- append(extra_dependencies,
192 list(html_dependency_pagedtable()))
193
194 # Change default value of highlight theme if downlit is to be used
195 if (highlight_downlit && missing(highlight)) highlight <- "default"
196
197 # generate actual format
198 base_format <- html_document(toc = toc,
199 toc_depth = toc_depth,
200 toc_float = toc_float,
201 number_sections = number_sections,
202 fig_width = fig_width,
203 fig_height = fig_height,
204 fig_retina = fig_retina,
205 fig_caption = fig_caption,
206 code_folding = code_folding,
207 theme = theme,
208 highlight = highlight,
209 highlight_downlit = highlight_downlit,
210 math_method = math_method,
211 mathjax = mathjax,
212 extra_dependencies = extra_dependencies,
213 css = css,
214 includes = includes,
215 md_extensions = md_extensions,
216 pandoc_args = pandoc_args,
217 self_contained = self_contained,
218 # options forced for notebooks
219 dev = "png",
220 code_download = TRUE,
221 keep_md = FALSE,
222 template = "default",
223 lib_dir = NULL,
224 ...)
225
226 rmarkdown::output_format(
227 knitr = html_notebook_knitr_options(),
228 pandoc = NULL,
229 df_print = paged_table_html_asis,
230 pre_knit = pre_knit,
231 pre_processor = pre_processor,
232 post_processor = post_processor,
233 base_format = base_format,
234 on_exit = on_exit
235 )
236 }
237
238 #' Parse an HTML Notebook
239 #'
240 #' Parse an HTML notebook, retrieving annotation information
241 #' related to generated outputs in the document, as well as the
242 #' original R Markdown source document.
243 #'
244 #' See the \href{https://rmarkdown.rstudio.com/r_notebook_format.html}{online
245 #' documentation} for additional details on using the \code{html_notebook}
246 #' format.
247 #' @param path The path to an R Notebook file (with extension \code{.nb.html}).
248 #' @export
249 parse_html_notebook <- function(path) {
250
251 contents <- read_utf8(path)
252
253 re_comment <- "^\\s*<!--\\s*rnb-([^-]+)-(begin|end)\\s*([^\\s-]+)?\\s*-->\\s*$"
254 re_document <- "^<div id=\"rmd-source-code\">([^<]+)<\\/div>$"
255
256 rmd_contents <- NULL
257 builder <- list_builder()
258
259 for (row in seq_along(contents)) {
260 line <- contents[[row]]
261
262 # extract document contents
263 matches <- gregexpr(re_document, line, perl = TRUE)[[1]]
264 if (!identical(c(matches), -1L)) {
265 start <- c(attr(matches, "capture.start"))
266 end <- start + c(attr(matches, "capture.length")) - 1
267 decoded <- rawToChar(xfun::base64_decode(substring(line, start, end)))
268 rmd_contents <- strsplit(decoded, "\\r?\\n", perl = TRUE)[[1]]
269 next
270 }
271
272 # extract information from comment
273 matches <- gregexpr(re_comment, line, perl = TRUE)[[1]]
274 if (identical(c(matches), -1L))
275 next
276
277 starts <- c(attr(matches, "capture.start"))
278 ends <- starts + c(attr(matches, "capture.length")) - 1
279 strings <- substring(line, starts, ends)
280
281 n <- length(strings)
282 if (n < 2)
283 stop("invalid rnb comment")
284
285 # decode comment information and update stack
286 data <- list(row = row,
287 label = strings[[1]],
288 state = strings[[2]])
289
290 # add metadata if available
291 if (n >= 3 && nzchar(strings[[3]]))
292 data[["meta"]] <- base64_decode_object(strings[[3]])
293 else
294 data["meta"] <- list(NULL)
295
296 # append
297 builder$append(data)
298 }
299
300 annotations <- builder$data()
301
302 # extract header content
303 head_start <- grep("^\\s*<head>\\s*$", contents, perl = TRUE)[[1]]
304 head_end <- grep("^\\s*</head>\\s*$", contents, perl = TRUE)[[1]]
305
306 list(source = contents,
307 rmd = rmd_contents,
308 header = contents[head_start:head_end],
309 annotations = annotations)
310 }
311
312 html_notebook_annotated_output <- function(output, label, meta = NULL) {
313 before <- if (is.null(meta)) {
314 sprintf("\n<!-- rnb-%s-begin -->\n", label)
315 } else {
316 meta <- base64_encode_object(meta)
317 sprintf("\n<!-- rnb-%s-begin %s -->\n", label, meta)
318 }
319 after <- sprintf("\n<!-- rnb-%s-end -->\n", label)
320 pasted <- paste(before, output, after, sep = "\n")
321 knitr::asis_output(pasted)
322 }
323
324 html_notebook_annotated_knitr_hook <- function(label, hook, meta = NULL) {
325 force(list(label, hook, meta))
326 function(x, ...) {
327
328 # call regular hooks and annotate output
329 output <- hook(x, ...)
330
331 # generate output
332 meta <- if (is.function(meta)) meta(x, output, ...)
333 html_notebook_annotated_output(output, label, meta)
334 }
335 }
336
337 html_notebook_knitr_options <- function() {
338
339 # save original hooks (restore after we've stored requisite
340 # hooks in our output format)
341 saved_hooks <- get_knitr_hook_list()
342 on.exit(set_knitr_hook_list(saved_hooks), add = TRUE)
343
344 # use 'render_markdown()' to get default hooks
345 knitr::render_markdown()
346
347 # store original hooks and annotate in format
348 orig_knit_hooks <- knitr::knit_hooks$get()
349
350 # generic hooks for knitr output
351 hook_names <- c("source", "chunk", "plot", "text", "output",
352 "warning", "error", "message", "error")
353
354 meta_hooks <- list(
355 source = html_notebook_text_hook,
356 output = html_notebook_text_hook,
357 warning = html_notebook_text_hook,
358 message = html_notebook_text_hook,
359 error = html_notebook_text_hook
360 )
361
362 knit_hooks <- lapply(hook_names, function(hook_name) {
363 html_notebook_annotated_knitr_hook(hook_name,
364 orig_knit_hooks[[hook_name]],
365 meta_hooks[[hook_name]])
366 })
367 names(knit_hooks) <- hook_names
368
369 # use a custom 'chunk' hook that ensures that html comments
370 # do not get indented
371 chunk_hook <- knitr::knit_hooks$get("chunk")
372 knit_hooks$chunk <- function(x, options) {
373
374 # update chunk line
375 context <- render_context()
376 context$chunk.index <- context$chunk.index + 1
377
378 # call original hook
379 output <- chunk_hook(x, options)
380
381 # clean up indentation for html
382 if (!is.null(options$indent)) {
383 output <- gsub("\n\\s*<!-- rnb-", "\n<!-- rnb-", output, perl = TRUE)
384 }
385
386 # write annotated output
387 html_notebook_annotated_output(output, "chunk")
388 }
389
390 opts_chunk <- list(render = html_notebook_render_hook,
391 comment = NA)
392
393 # return as knitr options
394 rmarkdown::knitr_options(knit_hooks = knit_hooks,
395 opts_chunk = opts_chunk)
396 }
397
398 html_notebook_text_hook <- function(input, output, ...) {
399 list(data = input)
400 }
401
402 html_notebook_render_hook <- function(x, ...) {
403 output <- knitr::knit_print(x, ...)
404 if (inherits(x, "htmlwidget"))
405 return(notebook_render_html_widget(output))
406 output
407 }
408
409 prepare_evaluate_output <- function(output, ...) {
410 UseMethod("prepare_evaluate_output")
411 }
412
413 #' @export
414 prepare_evaluate_output.htmlwidget <- function(output, ...) {
415 widget <- knitr::knit_print(output)
416 meta <- attr(widget, "knit_meta")
417 asis <- knitr::asis_output(c(widget))
418 annotated <- html_notebook_annotated_output(asis, "htmlwidget", meta)
419 attr(annotated, "knit_meta") <- meta
420 annotated
421 }
422
423 #' @export
424 prepare_evaluate_output.knit_asis <- function(output, ...) {
425 output
426 }
427
428 #' @export
429 prepare_evaluate_output.list <- function(output, ...) {
430 lapply(output, prepare_evaluate_output)
431 }
432
433 #' @export
434 prepare_evaluate_output.default <- function(output, ...) {
435 output
436 }
437
438 as_evaluate_output <- function(output, context, ...) {
439 prepared <- prepare_evaluate_output(output)
440 if (!is.list(prepared))
441 prepared <- list(prepared)
442 prepared
443 }
444
445 validate_output_source <- function(output_source) {
446
447 # error message to report
448 required_signature <- "function(code, context, ...) {}"
449 prefix <- "'output_source' should be a function with signature"
450 error_msg <- sprintf("%s '%s'", prefix, required_signature)
451
452 # ensure function
453 if (!is.function(output_source)) stop2(error_msg)
454
455 # check formals
456 fmls <- names(formals(output_source))
457 if (length(fmls) < 3) stop2(error_msg)
458
459 if (!("..." %in% fmls)) stop2(error_msg)
460
461 TRUE
462 }