Search code examples
rlatexr-markdownbookdown

How can I control fontsize and linestretch of code chunks independently from the main text in bookdown?


Using bookdown to output a .pdf document the YAML within the index.Rmd looks like this currently:

--- 
title: "My title"
author:
  - 'me'

output:
  bookdown::pdf_document2:
    includes:
      in_header: latex/preamble.tex
    keep_tex: yes

site: bookdown::bookdown_site
documentclass: book
geometry: "left=3.5cm, right=2.5cm, top=2.5cm, bottom=2.5cm"
fontsize: 12pt
linestretch: 1.5
bibliography: [packages.bib, referencias.bib]
linkcolor: NavyBlue
biblio-style: apalike
link-citations: yes
toc-depth: 2
lof: True
lot: True
---

How can I control fontsize and linestretch of code chunks independently from the main text? This answer provides a solution to control font size, but not line spacing.


Solution

  • It's is the same idea as here but now we just alter the source hook:

    ```{r setup, include=FALSE}
    def.source.hook  <- knitr::knit_hooks$get("source")
    knitr::knit_hooks$set(source = function(x, options) {
      x <- def.source.hook(x, options)  # apply default source hook
      ifelse(!is.null(options$linestretch),  # if linestretch is not NULL, apply linestretch
             paste0("\\linespread{", options$linestretch,"}\n", x, "\n\n\\linespread{1}"),  # reset linestretch after the chunk!
             x)
    })
    ```
    

    Now you can copy and paste the ifelse statement from the other answer into this hook as well and you can control both.

    Full example:

    ---
    title: "Linestretch"
    date: "20 December 2018"
    header-includes:
      - \usepackage{lipsum}
    output: 
      bookdown::pdf_document2:
        keep_tex: true
    linestretch: "`r (lstr <- 1.5)`" 
    ---
    
    ```{r setup, include=FALSE}
    knitr::opts_chunk$set(eval = F)
    def.source.hook  <- knitr::knit_hooks$get("source")
    knitr::knit_hooks$set(source = function(x, options) {
      x <- def.source.hook(x, options)
      x <- ifelse(!is.null(options$linestretch), 
                  paste0("\\linespread{", options$linestretch,"}\n", x, "\n\n\\linespread{", lstr,"}"), 
                  x)
      ifelse(!is.null(options$size), 
             paste0("\\", options$size,"\n\n", x, "\n\n \\normalsize"), 
             x)
    })
    ```
    
    ## R Markdown
    
    \lipsum[30]
    
    
    ```{r, linestretch = 1, size="Large"}
    head(mtcars)
    head(mtcars)
    ```
    
    
    \lipsum[30]
    

    enter image description here