类似knitr(内联)的代码格式

时间:2018-06-06 08:20:41

标签: r latex knitr

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}

1 个答案:

答案 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。结果:

enter image description here