Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linked table of contents (toc) in md using rmarkdown

Tags:

r

r-markdown

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
like image 339
Tyler Rinker Avatar asked May 02 '15 01:05

Tyler Rinker


1 Answers

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.

like image 186
Thell Avatar answered Sep 20 '22 18:09

Thell