[英]Linked table of contents (toc) in md using rmarkdown
When I use rmarkdown package to make an Rmd into an md I can include a toc via: 当我使用rmarkdown软件包将Rmd转换为md时,我可以包含一个toc via:
md_document:
toc: true
But they are not linked. 但他们没有联系。 Now I can do this manually after using
render
using this function I created: 现在我可以使用我创建的这个函数在使用
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()
It works by reading the file back in and manually inserting the links with the form [Section 1](#section-1)
. 它的工作原理是读回文件并手动插入表格
[Section 1](#section-1)
。
Is there a better approach to make the md toc link to the sections? 有没有更好的方法来使md toc链接到这些部分?
I have this as a GitHub repo if it's easier but here's a MWE Rmd: 我有这个作为GitHub回购,如果它更容易,但这是一个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
Working from a post in the pandoc discussion group, would something like this work for you? 在pandoc讨论组的帖子中工作,这样的事情对你有用吗?
Assume the source is testTOC.Rmd... 假设源是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
```
Outputs:: 输出::
- [Section 1](#section-1)
- [Section 2](#section-2)
- [Random Stuff A](#random-stuff-a)
- [Random Stuff B](#random-stuff-b)
- [Conclusion](#conclusion)
So you'd want to set toc: false
in the header YAML to not repeat it. 所以你想在标题YAML中设置
toc: false
以不重复它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.