我认为你需要修改钩子:https://yihui.name/knitr/hooks/
我给你一些例子。了解它的工作原理后,您可以添加自己的修改。
在源代码前添加vspace
要修改的钩子:
```{r setup_source, include=FALSE}
hook_source_def = knitr::knit_hooks$get('source')
knitr::knit_hooks$set(source = function(x, options) {
if (!is.null(options$vspaceecho)) {
begin <- paste0("\\vspace{", options$vspaceecho, "}")
stringr::str_c(begin, hook_source_def(x, options))
} else {
hook_source_def(x, options)
}
})
```
如何调用这个修改:
```{r vspace, vspaceecho='2cm', echo=TRUE}
summary(cars)
```
在 R 输出后添加 vspace
要修改的钩子
```{r setup_output, include=FALSE}
hook_output_def = knitr::knit_hooks$get('output')
knitr::knit_hooks$set(output = function(x, options) {
if (!is.null(options$vspaceout)) {
end <- paste0("\\vspace{", options$vspaceout, "}")
stringr::str_c(hook_output_def(x, options), end)
} else {
hook_output_def(x, options)
}
})
```
如何调用这个修改:
```{r vspaceafter, vspaceout='1cm'}
summary(cars)
```
在图形前后添加vspace
您可以创建一个新环境来嵌入图形。这需要添加一个技巧,让 pandoc 忽略 \begin 和 \end,否则 pandoc 不会将环境中的代码视为 markdown 语法。
创建要在 YAML 中调用的外部 tex 文件
里面有这段文字
\newenvironment{plotspace}[1]{#1}
% -- command for pandoc trick with \begin and \end -- %
\newcommand{\nopandoc}[1]{#1}
在 YAML 中调用 tex 文件
output:
pdf_document:
keep_tex: yes
include:
in_header: header.tex
要包含在代码中的钩子函数
hook_plot_def = knitr::knit_hooks$get('plot')
knitr::knit_hooks$set(plot = function(x, options) {
if (!is.null(options$vspaceplot)) {
begin <- paste0("\\nopandoc{\\begin{plotspace}}\n\\vspace{", options$vspaceplot, "}\n")
end <- paste0("\n\\vspace{", options$vspaceplot, "}\n\\nopandoc{\\end{plotspace}}")
stringr::str_c(begin, hook_plot_def(x, options), end)
} else {
hook_plot_def(x, options)
}
})
怎么称呼它
```{r plotvspace, vspaceplot='2em', fig.cap='Figure with vspace'}
plot(cars)
```
在更新环境中检索阴影
当您尝试更新 Shaded 环境时,您可以在附加的 header.tex 文件中执行以下操作。
\renewenvironment{Shaded}
{
\vspace{2cm}%
\begin{snugshade}%
}{%
\end{snugshade}%
\vspace{5cm}%
}