RMD, 通常目次とサイドバー目次を両方掲載できるか調査中


普通は両方掲載できないので、片方は自分で生成する。

TOC抽出まではうまくいくが、RMD上でうまく実行できるようにするのが難しい。

Step1
RMDをまずmarkdownに変換する。こちらでは通常の目次を生成するようにする。
得られたmarkdownから通常の目次を抽出する。

Step2
RMDに通常目次を埋め込む
Step1~2はRMDのチャンク内で実行することとする。

Step3
サイドバー目次を生成する設定でRMDをコンパイルする。

res <- getTOC_str("o.Rmd")
> cat(res)
  - [はじめに](#はじめに)
      - [aa](#aa)
      - [漢字 P@\_/](#漢字-p_)
  - [R Markdown](#r-markdown)
  - [Including Plots](#including-plots)> 
writeMD_withoutChunk <- function(rmd_path, out_path){
    # number_sections=TRUEは, html_documentでないと使えない。
    #----
    fmt <- github_document(html_preview=F, toc=T)  
    fmt$knitr$opts_chunk$include=F
    rmarkdown::render(rmd_path, fmt, out_path)
}


getTOC_str <- function(rmd_path){
    tmp_path <- tempfile(fileext = ".md")
    writeMD_withoutChunk(rmd_path, tmp_path)

    lines <- readLines(tmp_path, encoding="UTF-8")
    #-------
    blank_flags     <- (lines=="")
    blank_positions <- which(blank_flags)
    at_blank1 <- blank_positions[1]
    at_blank2 <- blank_positions[2]

    rng <- seq(at_blank1+1, at_blank2-1)
    toc_lines <- lines[rng]
    toc_str   <- stringr::str_c(toc_lines, collapse="\n")
    return(toc_str)
}