consistent code html inline and in chunks with kni

2019-07-19 15:26发布

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

标签: html r knitr
2条回答
贪生不怕死
2楼-- · 2019-07-19 16:11

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

查看更多
劳资没心,怎么记你
3楼-- · 2019-07-19 16:21

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

查看更多
登录 后发表回答