2015-05-02 16 views
17

Khi tôi sử dụng rmarkdown gói để thực hiện một RMD thành một md tôi có thể bao gồm một toc qua:Liên Kết mục lục (TOC) trong md sử dụng rmarkdown

md_document: 
    toc: true 

Nhưng họ không liên kết. Bây giờ tôi có thể làm điều này bằng tay sau khi sử dụng render sử dụng chức năng này, tôi tạo ra:

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

Nó hoạt động bằng cách đọc các tập tin trở lại và tự chèn các liên kết với các hình thức [Section 1](#section-1).

Có cách tiếp cận tốt hơn để làm cho liên kết md liên kết với các phần không?

Tôi có điều này như một GitHub repo nếu nó dễ dàng hơn nhưng đây là một 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 

Trả lời

1

Làm việc từ a post trong nhóm thảo luận pandoc, sẽ một cái gì đó như tác phẩm này với bạn?

Giả nguồn là 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 
``` 

Đầu ra ::

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

Vì vậy, bạn muốn thiết lập toc: false trong YAML tiêu đề để không lặp lại nó.

Các vấn đề liên quan