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

knitr-like (inline) code formatting

LyX/LaTeX 文档中,我使用 knitr 来包含 (R) 个代码块。

我想通过内联重复其中的部分来解释代码块下方的代码。

如何实现内联文本的相同格式(无需评估)?

一辉在 and another 上有一个问答,但是当我尝试使用 rmarkdown 答案中的代码时,它在 LyX.[=22 中抛出错误=]

我得到的错误是:

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