【问题标题】:knitr-like (inline) code formattingknitr-like (inline) 代码格式
【发布时间】:2018-06-06 08:20:40
【问题描述】:

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

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

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

亿辉在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}

【问题讨论】:

  • 请向我们提供minimal reproducible example
  • 它与 rmarkdown 的代码相同,但在 LyX 中,这有点冗长。我将在 LaTeX 中添加一些应该等效的内容。
  • 当我将 \Sexpr{r pi} 替换为 \Sexpr{pi} 时,您的 MWE 会编译。您想要更改生成的输出的哪一部分?
  • 啊,谢谢你发现它,它不适合我
  • plot(cars, ... 的格式是否类似于 knitr 块?

标签: r latex knitr


【解决方案1】:

以下对我有用:

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

【讨论】:

  • 太棒了!非常感谢。尽管这确实意味着我现在必须重新开始写作:-| :-D
  • 如果更高的 0.6.1 可以用于 CRAN 可能会有用
  • @Bastiaan 你可以在 GitHub 上打开一个问题并要求发布 CRAN。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-27
  • 1970-01-01
  • 2014-01-04
  • 2021-05-21
  • 1970-01-01
  • 1970-01-01
  • 2019-07-14
相关资源
最近更新 更多