knitr 中的 R 代码换行符和主题

knitr 中的 R 代码换行符和主题

hpesoj626 提供了两个很好的最小工作示例,说明如何获得knitr 中的 R 代码换行和代码突出显示。我想知道是否可以使用 Yihui 的针织主题在这两个例子中,是否都存在这种情况?如果存在,那么原因是什么?

下面是我个人比较喜欢的示例代码(我language=R在设置块中的主题标签之间添加了三行,并highlight = FALSE在文档中的块中删除了它):

\documentclass[twocolumn]{article}

\usepackage{listings}
\usepackage{inconsolata}

\lstset{breaklines=true,showstringspaces=false,language=R}

<<setup, include=FALSE, cache=FALSE>>=
opts_chunk$set(fig.path = 'figure/listings-')
options(replace.assign = TRUE, width=60)
render_listings()
################################################
# not part of hpesoj626's example and not working:
opts_chunk$set(fig.path = 'figure/listings-')
opts_knit$set( out.format="latex" )
################################################
@

\title{Function listings with linebreaks and code highlighting}

\begin{document}
\maketitle

Two ways of printing the code.

<<tidy=TRUE>>=
theFunction <- function(x) {
  tmp <- "A really long string that should be line-broken but it would be nice to also see code highlighting colors. The function is in the real code sourced, but for the sake of easier reproducibility, it is written here instead."
}

theFunction
@

\end{document} 

我想知道是否有可能将 knitr 主题集成到这个最小的工作示例中,类似于 Michael 所建议的这里

opts_knit$set( out.format="latex" )
knit_theme$set("print")

将这两行添加到上面的最小工作示例中没有任何作用(当我删除设置块中的所有其他选项并且仅包含这两行时,语法高亮显示正常)。

或者,如果添加主题不起作用,是否可以重新定义默认列表样式,以便确切地类似于主题(类似于 hpesoj626 在他的第一个答案中所建议的,但随后使用 R 语法突出显示所有关键字、数字、逗号......)?我尝试根据 Carsten Heinz 的 listings 包驱动程序手册(lstdrvs.pdf)写下所有定义这里),但未能成功。

答案1

我能够使主题工作如下:

<<echo=FALSE>>=

knit_theme$set("biogoo")
@


<<results='asis', echo=FALSE>>=

x <-1:10
y <- x^2
@

相关内容