【问题标题】:Linked table of contents (toc) in md using rmarkdown使用 rmarkdown 在 md 中链接目录 (toc)
【发布时间】:2015-05-02 01:09:06
【问题描述】:

当我使用 rmarkdown 包将 Rmd 制作成 md 时,我可以通过以下方式包含目录:

  md_document:
    toc: true  

但它们没有链接。现在我可以在使用render 之后使用我创建的这个函数手动执行此操作:

rmarkdown::render("README.Rmd", "all") 

md_toc <- function(path = {(x <- dir())[tools::file_ext(x) == "md"]}){
    x <- suppressWarnings(readLines(path))
    inds <- 1:(which(!grepl("^\\s*-", x))[1] - 1)
    temp <- gsub("(^[ -]+)(.+)", "\\1", x[inds])
    content <- gsub("^[ -]+", "", x[inds])
    x[inds] <- sprintf("%s[%s](#%s)", temp, content, 
        gsub("[;/?:@&=+$,]", "", gsub("\\s", "-", tolower(content))))
    cat(paste(x, collapse = "\n"), file = path)
}

md_toc()

它的工作原理是读回文件并手动插入格式为[Section 1](#section-1) 的链接。

有没有更好的方法让 md toc 链接到这些部分?

如果更简单,我将其作为 GitHub repo,但这是 MWE Rmd:

---
title: "testing_Rmd"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
  html_document:
    toc: true
    theme: journal
    number_sections: true
  pdf_document:
    toc: true
    number_sections: true
  md_document:
    toc: true      
---


# Section 1

Stuff

# Section 2

More Stuff

## Random Stuff A

1 + 2

## Random Stuff B

```{r}
1 + 2
```

# Conclusion

【问题讨论】:

    标签: r r-markdown


    【解决方案1】:

    在 pandoc 讨论组的 a post 工作,会 喜欢这个作品吗?

    假设源是 testTOC.Rmd...

    ```{r mdTOC, echo=FALSE}
    mdTOC <- grepl("markdown", knitr::opts_knit$get("rmarkdown.pandoc.to") )
    ```
    
    ```{r, engine='bash', results='asis',echo=FALSE, eval=mdTOC}
    # toc-template.txt is somewhere in the path and only contains a single line:: $toc$
    pandoc --template=toc-template.txt --toc --to html --from markdown testTOC.Rmd |\
    pandoc --to markdown --from html
    ```
    

    输出::

    -   [Section 1](#section-1)
    -   [Section 2](#section-2)
        -   [Random Stuff A](#random-stuff-a)
        -   [Random Stuff B](#random-stuff-b)
    -   [Conclusion](#conclusion)
    

    因此,您需要在 YAML 标头中设置 toc: false 以免重复。

    【讨论】:

      猜你喜欢
      • 2019-07-14
      • 2018-06-30
      • 2015-03-24
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 2014-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多