topepo
topepo

Reputation: 14331

consistent code html inline and in chunks with knitr

I would like the code in paragraphs to be consistent with the code shown in code chunks.

For example:

<p>
The formula method for a linear model 
is <code>lm(y~x, data = dat)</code>. 
For our data the results are:
</p>
<!--begin.rcode 
    lm(y~x, data = dat)
    end.rcode-->

It would be nice to use something besides <code> inline and get the same formatting as the chunk's code.

I'm using knitr:

> sessionInfo()
R version 3.0.1 (2013-05-16)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets 
[6] methods   base     

other attached packages:
[1] knitr_1.2

loaded via a namespace (and not attached):
[1] digest_0.6.3   evaluate_0.4.3 formatR_0.7   
[4] stringr_0.6.2  tools_3.0.1

Thanks,

Max

Upvotes: 3

Views: 627

Answers (2)

Yihui Xie
Yihui Xie

Reputation: 30174

You can redefine the inline hook, and write your inline code as character strings. Below is a minimal example (make sure you are using the latest versions of all R packages):

<!DOCTYPE html>
<html>
<head>
  <title>Highlight inline R code</title>
</head>
<body>
<!--begin.rcode
    library(knitr)
    hook_inline = knit_hooks$get('inline')
    knit_hooks$set(inline = function(x) {
      if (is.character(x)) highr::hi_html(x) else hook_inline(x)
    })
    end.rcode-->

<p>
The formula method for a linear model 
is <code><!--rinline 'lm(y~x, data = dat)' --></code>. 
For our data the results are:
</p>
<!--begin.rcode eval=FALSE
    lm(y~x, data = dat)
    end.rcode-->

</body>
</html>

The key is to do syntax highlighting via highr::hi_html(), and here is the output:

highlight inline R code

Upvotes: 3

sgibb
sgibb

Reputation: 25736

You could try <!--rinline deparse(substitute(lm(y~x, data = dat))) -->. (Seems that the syntax highlighting isn't working).

Upvotes: 0

Related Questions