rpdflatexr-markdownline-spacing

Avoid double spacing in Rmarkdown pdf (within chunk)


I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.

I have quickly found this thread which resolves the issue on how to double space with the following code.

header-includes:
    - \usepackage{setspace}\doublespacing

However, the double spacing also apply to code chunks which I would prefer them to be single space. I know I could add something like \singlespacing before and after the chunks, but since I use many chucks, is there a cleverer way?

It there a way to avoid the double spacing produced by \doublespacing in code chunks?


EDIT

Here is a reproducible example.

---
output: pdf_document
header-includes:
  - \usepackage{setspace}\doublespacing
---

I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.

```{r}
# This chuck is also double spaced
# But I would prefer it to be single spaces
```

enter image description here


Solution

  • Rmarkdown defines a Shaded environment, which is used to set these code snippets. You can patch it to automatically add \singlespace:

    ---
    output: 
      pdf_document:
        keep_tex: true
    header-includes:
      - \usepackage{setspace}\doublespacing
      - \usepackage{etoolbox}
      - \AtBeginEnvironment{Shaded}{\singlespace}
    ---
    
    I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.
    
    ```{r}
    # This chuck is also double spaced
    # But I would prefer it to be single spaces
    ```
    I am trying to make my own APA7 style Rmarkdown template (with pdf output). Feel pretty good so far. The only thing left for me to fix is the double spacing in code chunks.
    

    enter image description here