Search code examples
rmarkdownr-markdowntableofcontents

How can I specify at which level the toc will be expanded in an Rmd report?


When generating an Rmarkdown .html document, is it possible to selectivey choose the default section of the table of contents at which it will be displayed? I have an ongoing Rmd report which is updated regularly, and I would like the previous toc sections to be available but collapsed and only the latest (or explicitly indicated section) expanded.

---
title: "Main document"
date: "16 March 2018"
output: 
  html_document:
    mode: selfcontained
    toc: true
    toc_float: true
    toc_depth: 2
---

```{r child = 'document1.Rmd'}
```

```{r child = 'document2.Rmd'}
```

```{r child = 'document3.Rmd'}
```

Solution

  • You can use a tiny JavaScript program that uses the window.location property.

    Here's a reproducible Rmd opening the subsection 2.1:

    ---
    title: "Document"
    date: "16 March 2018"
    output: 
      html_document:
        mode: selfcontained
        toc: true
        toc_float: true
        toc_depth: 2
    ---
    # Section 1
    ## Subsection 1.1
    
    ## Subsection 1.2
    
    # Section 2
    ## Subsection 2.1
    
    ## Subsection 2.2
    
    ```{js echo=FALSE}
    window.location.href='#subsection_21';
    ```
    

    In order to adapt this example to your document:

    1. Open the HTML document in a browser, select the targeted section and read the browser address bar. The address ends with #section_title_or_something_like_that. Note this id.

    2. Copy the js chunk of the example at the very end of your main Rmd file. Replace
      #subsection_21 with the previous id (#section_title_or_something_like_that).

    3. Knit your main document! That's done.


    If you want to avoid raw JavaScript in your main Rmd file, you also can include theses lines in a script.html file (do not forget to adapt the id):

    <script type="text/javascript">
    window.location.href='#subsection_21';
    </script>
    

    Then, includes this script.html file in your document using:

    ---
    title: "Document"
    date: "16 March 2018"
    output: 
      html_document:
        mode: selfcontained
        toc: true
        toc_float: true
        toc_depth: 2
        includes:
          after_body: "script.html"
    ---
    # Section 1
    ## Subsection 1.1
    
    ## Subsection 1.2
    
    # Section 2
    ## Subsection 2.1
    
    ## Subsection 2.2