When I use rmarkdown package to make an Rmd into an md I can include a 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:
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)
.
Is there a better approach to make the md toc link to the sections?
I have this as a GitHub repo if it's easier but here's a 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?
Assume the source is 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With