如何独立于书本中的主要文本来控制代码块的字体大小和行拉伸?

时间:2018-12-21 15:42:57

标签: r latex r-markdown bookdown

使用bookdown输出一个.pdf文档,index.Rmd中的YAML当前看起来像这样:

--- 
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
---

如何独立于正文控制fontsizelinestretch的代码块? This answer提供了一种控制字体大小而不是行距的解决方案。

1 个答案:

答案 0 :(得分:2)

here的想法相同,但是现在我们只是更改了源代码挂钩:

```{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)
})
```

现在,您也可以将其他答案中的ifelse语句复制并粘贴到此钩子中,并且您可以控制这两个钩子。

完整示例:

---
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