Debian Codegraph @

R/show_source.R

raw
1 set_show_source_hooks <- function() {
2 width <- 40
3
4 set_show_source_opts_hook(width)
5 set_show_source_source_hook()
6 }
7
8 # Defines a `show_source` knitr option. If this chunk option is set,
9 # the code should be a single function (use ::: for internal functions).
10 # The code will be replaced by the function definition, and not evaluated.
11 set_show_source_opts_hook <- function(width) {
12 force(width)
13
14 show_source_opts_hook <- function(options) {
15 qualified_fun_name <- options$code
16 fun_name <- gsub("^.*:::", "", qualified_fun_name)
17
18 fun <- eval(parse(text = fun_name))
19 code <- deparse(fun, control = "useSource")
20
21 options$code <- paste0(fun_name, " <- ", paste0(code, collapse = "\n"))
22 options$eval <- FALSE
23 # Store for later reuse by source hook
24 options$show_source <- qualified_fun_name
25 options
26 }
27
28 knitr::opts_hooks$set(show_source = show_source_opts_hook)
29 }
30
31 # show_source chunks are included in a <details> tag.
32 set_show_source_source_hook <- function() {
33 # Need to use a closure here to daisy-chain hooks and to keep state
34
35 old_source_hook <- knitr::knit_hooks$get("source")
36
37 show_source_source_hook <- function(x, options) {
38 x <- old_source_hook(x, options)
39 if (is.null(options$show_source)) {
40 return(x)
41 }
42
43 qualified_fun_name <- options$show_source
44 fun_name <- gsub("^.*:::", "", qualified_fun_name)
45
46 paste0(
47 "<details><summary>Source code of <code>",
48 qualified_fun_name, "()</code></summary>",
49 x, "</details>\n"
50 )
51 }
52
53 knitr::knit_hooks$set(source = show_source_source_hook)
54 }