Search code examples
rlatexknitr

knitr-like (inline) code formatting


In a LyX/LaTeX document, I am using knitr to include (R) code chunks.

I would like to explain my code in below the chunk, by repeating sections of it inline.

How can I achieve the same formatting of text inline (without evaluation)?

There is a question and answer by Yihui on doing this in rmarkdown and another another answer by him that it should be similar in LaTeX, but when I try using the code from the rmarkdown answer, it throws up errors in LyX.

The error I get is:

Error in if (knitr:::pandoc_to() != "latex") return(code) : 
argument is of length zero

When I remove the if (knitr .... line, I get an output document, but the line code is formatted as normal text.

Any thoughts?

EDIT: upon request a 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}

Solution

  • The following works for me:

    \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}
    

    I removed the knitr:::pandoc_to and replaced highr:::cmd_pandoc_latex with highr:::cmd_latex since you are not using pandoc. Result:

    enter image description here