From c42f97fc96c433645f2dcdbd8039b8bf7dda0a6c Mon Sep 17 00:00:00 2001 From: Jake Barlow Date: Sun, 4 Oct 2020 16:26:18 +1100 Subject: [PATCH 1/2] custom table of contents Allows a custom TOC file to be specified in _bookdown.yml, so component rmd files (and the order of) can be specified. Is mutually exclusive with other build options (e.g. rmd_subdir). Additionally, when used in the gitbook style: - Can define "headers" in the TOC without an associated page, which are styled appropriately - Can insert custom dividers between TOC elements - Can set page names in TOC to be different from the actual page name (the H1 header) - Best results seen/designed seen when _output.yml has toc_depth: 1 and split_by: rmd --- DESCRIPTION | 3 +- NAMESPACE | 1 + R/gitbook.R | 42 ++++++++++++- R/utils.R | 93 +++++++++++++++++++++------- inst/resources/gitbook/css/style.css | 2 +- 5 files changed, 117 insertions(+), 24 deletions(-) diff --git a/DESCRIPTION b/DESCRIPTION index c26af0e95..e8f8c43bc 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -63,7 +63,8 @@ Imports: knitr (>= 1.22), rmarkdown (>= 2.3.5), xfun (>= 0.13), - tinytex (>= 0.12) + tinytex (>= 0.12), + stringr (>= 1.2.0) Suggests: htmlwidgets, rstudioapi, diff --git a/NAMESPACE b/NAMESPACE index 66150a3ce..a468c3b70 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -36,6 +36,7 @@ export(tufte_html_book) export(word_document2) import(stats) import(utils) +import(stringr) importFrom(xfun,in_dir) importFrom(xfun,read_utf8) importFrom(xfun,same_path) diff --git a/R/gitbook.R b/R/gitbook.R index 09fce6ca5..a11a80baa 100644 --- a/R/gitbook.R +++ b/R/gitbook.R @@ -174,7 +174,46 @@ gitbook_toc = function(x, cur, config) { i2 = find_token(x, '') x[i1] = ''; x[i2] = '' if (i2 - i1 < 2) return(x) + + #Changed to allow for toc length to change over the course of the function + prior = x[1:i1] toc = x[(i1 + 1):(i2 - 1)] + post = x[i2:length(x)] + + if(is.character(rmarkdown:::yaml_load_file('_bookdown.yml')[['custom_toc']])){ + toc_frame <- readRDS("toc.Rds") + #First add in divisions and headers + for(i in (1:nrow(toc_frame))){ + if(toc_frame[i,6] == "HEADING"){ + toc <- append(toc, paste('
  • ', toc_frame[i,4], '
  • ', sep=""), i) + } else if(toc_frame[i,6] == "BREAK"){ + toc <- append(toc, '
  • ', i) + } + } + + #Check that the in length difference is due to the leading and trailing