5

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.

J. Mini
  • 1,868
  • 1
  • 9
  • 38
  • No, but if you are setting up an HTML document, you can add a floating table of contents to make it easier to go to the specific section you wish: https://bookdown.org/yihui/rmarkdown/html-document.html#floating-toc – Phil Jul 31 '21 at 23:21
  • @Phil I've tried a similar fix. I'm working in .md at the moment. The preview is html, but the automatically generated links in the table of contents don't move the preview when clicked. It seems that the HTML that is generated for these links isn't preserving the capital letters in the section titles. The relevant parts of my header are `output: github_document: toc: true number_sections: true` – J. Mini Jul 31 '21 at 23:24
  • `xaringan` Rmarkdown Slides allow live preview this with [Infinite Moon Reader](https://yihui.org/en/2019/02/ultimate-inf-mr/). AFAIK this isn't available for standard R Markdown. – Waldi Aug 03 '21 at 20:28
  • Maybe Rstudio's [visual R markdown editing mode](https://rstudio.github.io/visual-markdown-editing/?_ga=2.191384938.1723911530.1628024238-1980107839.1620336500) is what you are looking for? – nniloc Aug 03 '21 at 20:59
  • @nniloc That's handy, but I specifically want to be able to view the preview. – J. Mini Aug 04 '21 at 17:47
  • Infinite Moon Reader can be used for normal R Markdown. But the feature that the preview jumps to the cursor location does not work. Still you can scroll to a location and the view will remain there after re-knitting. – JBGruber Aug 05 '21 at 07:43

1 Answers1

7

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 = "")
```
the-mad-statter
  • 5,650
  • 1
  • 10
  • 20