在LyX
/ LaTeX
文档中,我使用knitr
来包含(R
)代码块。
我想通过重复内联的部分来解释我在块下面的代码。
如何实现内联文本的相同格式化(无评估)?
Yihui在doing this in rmarkdown
和另一个another answer by him that it should be similar in LaTeX
上有一个问题和答案,但是当我尝试使用rmarkdown
答案中的代码时,它会在LyX
中引发错误}。
我得到的错误是:
Error in if (knitr:::pandoc_to() != "latex") return(code) :
argument is of length zero
当我删除if (knitr ....
行时,我会得到一个输出文档,但行代码的格式为普通文本。
有什么想法?
编辑:根据要求提供MWE
\documentclass{article}
\begin{document}
<<include=FALSE>>=
local({
hi_pandoc = function(code) {
if (knitr:::pandoc_to() != 'latex') return(code)
if (packageVersion('highr') < '0.6.1') stop('highr >= 0.6.1 is required')
res = highr::hi_latex(code, markup = highr:::cmd_pandoc_latex)
sprintf('\\texttt{%s}', res)
}
hook_inline = knitr::knit_hooks$get('inline')
knitr::knit_hooks$set(inline = function(x) {
if (is.character(x) && inherits(x, 'AsIs')) hi_pandoc(x) else hook_inline(x)
})
})
@
Test inline R code: \Sexpr{ I("plot(cars, main = 'A scatterplot.')") }.
Normal inline code \Sexpr{pi}.
A code block:
<<>>=
plot(cars, main = 'A scatterplot.')
1 + 2 # a comment
@
\end{document}
答案 0 :(得分:2)
以下适用于我:
\documentclass{article}
\begin{document}
<<include=FALSE>>=
local({
hi_pandoc = function(code) {
if (packageVersion('highr') < '0.6.1') stop('highr >= 0.6.1 is required')
res = highr::hi_latex(code, markup = highr:::cmd_latex)
sprintf('\\texttt{%s}', res)
}
hook_inline = knitr::knit_hooks$get('inline')
knitr::knit_hooks$set(inline = function(x) {
if (is.character(x) && inherits(x, 'AsIs')) hi_pandoc(x) else hook_inline(x)
})
})
@
Test inline R code: \Sexpr{ I("plot(cars, main = 'A scatterplot.')") }.
Normal inline code \Sexpr{pi}.
A code block:
<<>>=
plot(cars, main = 'A scatterplot.')
1 + 2 # a comment
@
\end{document}
我删除了knitr:::pandoc_to
,并将highr:::cmd_pandoc_latex
替换为highr:::cmd_latex
,因为您没有使用pandoc
。结果: