您可以在 css 文件或在 YAML 中使用 in_header 调用的 tex 文件中创建所需的样式,具体取决于您的输出。
然后创建一个 R 函数,将这种样式应用于您的文本。
定义所需样式的css文件
.Courier {
font-family: Courier New, Courier, monospace;
}
latex 文件来定义所需的样式
如果你的输出只有 LateX,你可以将这些命令直接放在你的文档中。
\newenvironment{Courier}{\ttfamily}{\par}
% Trick to avoid pandoc escaping texte between \begin and \end
\newcommand{\nopandoc}[1]{#1}
用于包含在块中的长文本输出的样式格式函数
这些函数适用于 HTML 或 LateX/PDF 输出:
```{r, echo=FALSE}
beginStyleFmt <- function(textstyle, type = "span") {
outputFormat <- knitr:::pandoc_to()
if (outputFormat %in% c('latex', 'beamer')) {
if (type %in% c("div", "p")) {
paste0("\\nopandoc{\\begin{", textstyle, "}}\n")
} else {
paste0("\\nopandoc{\\", textstyle, "{")
}
} else if (outputFormat == 'html') {
paste0("<", type, " class='", textstyle, "'>")
} else {
""
}
}
endStyleFmt <- function(textstyle, type = "span") {
outputFormat <- knitr:::pandoc_to()
if (outputFormat %in% c('latex', 'beamer')) {
if (type %in% c("div", "p")) {
paste0("\n\\nopandoc{\\end{", textstyle, "}}")
} else {
paste0("}}")
}
} else if (outputFormat == 'html') {
paste0("</", type, ">")
} else {
""
}
}
```
文档中的代码块
如果您在文本文件中有一些类似 markdown 的语法,例如 # Title,它将被读取为 markdown 语法。但是标题之间的文本将在 Courier 中。如果您不希望您的文本被视为降价语法,您可以删除 beginStyleFmt 中的 \\nopandoc{ 和 endStyleFmt 函数中对应的 }。
`r beginStyleFmt("Courier", type = "div")`
```{r comment='', echo=FALSE, results='asis'}
cat(readLines('/filepath/filename.out'), sep = '\n')
```
`r endStyleFmt("Courier", type = "div")`