在
LyX
/LaTeX
文档中,我使用 knitr
来包含 (R
) 代码块。
我想通过内联重复其中的部分来解释该块下面的代码。
如何实现相同的内联文本格式(无需评估)?
Yihui 在 rmarkdown
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}
以下对我有用:
\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)
res <- gsub("\\^", "\\\\textasciicircum{}", res)
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
@
%
And some more inline code \Sexpr{ I("2^3") } and \Sexpr{ 2^3 }
\end{document}
我删除了
knitr:::pandoc_to
并将 highr:::cmd_pandoc_latex
替换为 highr:::cmd_latex
,因为您没有使用 pandoc
。结果: