Search code examples
rr-markdownrstudiopreview

Can R Markdown be made to preview from anywhere other than the start of the document?


I'm currently writing something in R Markdown. Whenever I Knit the document, RStudio's preview takes me back to the very beginning of the document. Is there a way to make this new preview display a location closer to where I've been working by default? For example, can I make it preview at a location near where my cursor for typing is?

The comments have suggested a number of workarounds. So far, my best is to just type the section number of the section where I'm working in to the search bar that RStudio's preview window provides. I'd click on the relevant entry in the table of contents, but I use output: github_document: toc: true number_sections: true, which is waiting on a patch to its numbered tables of contents.


Solution

  • Not quite as simple as you had in mind, but it is possible to use javascript to control what section of an html document is displayed:

    ---
    title: "Untitled"
    output: html_document
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(echo = FALSE)
    ```
    
    ```{js}
    location.hash = "#goto";
    ```
    
    ```{r, results='asis'}
    cat(sprintf("# %s\n\nSection text here.\n\n", 1:10), sep = "")
    ```
    
    # GOTO
    
    Scroll Here
    
    ```{r, results='asis'}
    cat(sprintf("# %s\n\nSection text here.\n\n", 11:20), sep = "")
    ```