chunk-options.R 2.08 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
# These settings control the behavior of all chunks in the novice R materials.
# For example, to generate the lessons with all the output hidden, simply change
# `results` from "markup" to "hide".
# For more information on available chunk options, see
# http://yihui.name/knitr/options#chunk_options

library("knitr")

fix_fig_path <- function(pth) file.path("..", pth)

11
12
13
14
15
16
17
18
19
20
21
22

## We set the path for the figures globally below, so if we want to
## customize it for individual episodes, we can append a prefix to the
## global path. For instance, if we call knitr_fig_path("01-") in the
## first episode of the lesson, it will generate the figures in
## `fig/rmd-01-`
knitr_fig_path <- function(prefix) {
    new_path <- paste0(opts_chunk$get("fig.path"),
                      prefix)
    opts_chunk$set(fig.path = new_path)
}

23
24
## We use the rmd- prefix for the figures generated by the lssons so
## they can be easily identified and deleted by `make clean-rmd`.  The
25
26
27
28
## working directory when the lessons are generated is the root so the
## figures need to be saved in fig/, but when the site is generated,
## the episodes will be one level down. We fix the path using the
## `fig.process` option.
29

30
opts_chunk$set(tidy = FALSE, results = "markup", comment = NA,
31
               fig.align = "center", fig.path = "fig/rmd-",
32
33
34
35
               fig.process = fix_fig_path)

# The hooks below add html tags to the code chunks and their output so that they
# are properly formatted when the site is built.
36

37
hook_in <- function(x, options) {
38
  stringr::str_c("\n\n~~~\n",
39
                 paste0(x, collapse="\n"),
40
                 "\n~~~\n{: .r}\n\n")
41
42
43
}

hook_out <- function(x, options) {
44
  x <- gsub("\n$", "", x)
45
46
47
48
49
50
  stringr::str_c("\n\n~~~\n",
                   paste0(x, collapse="\n"),
                 "\n~~~\n{: .output}\n\n")
}

hook_error <- function(x, options) {
51
  x <- gsub("\n$", "", x)
52
53
54
55
56
57
58
  stringr::str_c("\n\n~~~\n",
                 paste0(x, collapse="\n"),
                 "\n~~~\n{: .error}\n\n")
}

knit_hooks$set(source = hook_in, output = hook_out, warning = hook_error,
               error = hook_error, message = hook_out)