有人打开pandoc GitHub 存储库上关于此的问题 https://github.com/jgm/pandoc/issues/3145几年前,以及我们可以找到解决方法 https://github.com/jgm/pandoc/issues/3145#issuecomment-302787889: 为 LaTeX 制作同义词\begin{}
and \end{}
。因此,要在 R Markdown 中使用它,我们只需将它们放入header-includes
:
---
title: "Stack Overflow Answer"
author: "duckmayr"
date: "5/9/2020"
output:
pdf_document:
keep_tex: true
header-includes:
- \let\Begin\begin
- \let\End\end
---
\Begin{center}
**should be bold text**
\End{center}
乳胶输出:
... Many initial lines skipped ...
\let\Begin\begin
\let\End\end
\title{Stack Overflow Answer}
\author{duckmayr}
\date{5/9/2020}
\begin{document}
\maketitle
\begin{center}
\textbf{should be bold text}
\end{center}
\end{document}
PDF输出:
更新:使用类似的东西怎么样?kable()
?
处理使用类似的事情kable()
在 R 块中results='asis'
,我们需要修复输出kable()
;也就是说,我们需要改变它的\begin{}
and \end{}
标签到\Begin{}
and \End{}
,我们还需要确保我们最终不会转换\\
序列到textbackslash{}
s。我们的做法如下:
---
title: "Untitled"
output:
pdf_document:
keep_tex: true
df_print: kable
header-includes:
- \let\Begin\begin
- \let\End\end
- \newcommand{\Newrow}{\\}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, results='hide', message=FALSE, warning=FALSE)
library(kableExtra)
allow_markdown <- function(tex) {
tex <- gsub("begin", "Begin", tex) ## fix \begin{} tags
tex <- gsub("\\\\end", "\n\\\\End", tex) ## fix \end{} tags
tex <- gsub("\\\\\\\\", "\\\\Newrow\n", tex) ## fix new row \\
return(tex)
}
```
```{r test2, results='asis'}
kable(data.frame(x=c("**bold text**")),"latex")
```
```{r test3, results='asis'}
allow_markdown(kable(data.frame(x=c("**bold text**")), "latex"))
```
我们在标题中添加了一个新的 LaTeX 命令\newcommand{\Newrow}{\\}
这样我们就可以安全地添加\\
而不将它们转换为\textbackslash{}
。这是必要的,因为我们如何欺骗 pandoc 来处理环境中的 markdown\Begin
and \End
.
我们还添加了一个 R 函数来修复 LaTeX 输出kable()
修复开始和结束标签以及新行\\
人物。
然后我们得到以下 LaTeX 和 PDF 输出:
[header omitted]
\begin{document}
\maketitle
\begin{tabular}{l}
\hline
x\\
\hline
**bold text**\\
\hline
\end{tabular}
\begin{tabular}{l}
\hline
x\\
\hline
\textbf{bold text}\\
\hline
\end{tabular}
\end{document}