2015-05-02 12 views
17

Wenn ich rmarkdown Paket verwenden, um eine Rmd in ein md machen ich eine toc über können sein:verlinkte Inhaltsverzeichnis (toc) in md mit rmarkdown

md_document: 
    toc: true 

Aber sie sind nicht verbunden. Jetzt kann ich dies tun manuell nach der Verwendung von render Verwendung dieser Funktion I erstellt:

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() 

Es funktioniert, indem Sie die Datei wieder in das Lesen und die Verknüpfungen manuell mit dem Formular [Section 1](#section-1) einsetzen.

Gibt es einen besseren Ansatz, um die MD-TOC-Verbindung zu den Abschnitten herzustellen?

Ich habe dies als GitHub repo wenn es einfacher ist, aber hier ist ein 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 

Antwort

1

Arbeiten von a post in der pandoc Diskussionsgruppe wäre für Sie etwas wie diese Arbeit?

Angenommen, die Quelle testTOC.Rmd ist ...

```{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 
``` 

Ausgänge ::

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

So würden Sie toc: false im Header YAML einstellen wollen nicht, sie zu wiederholen.

Verwandte Themen