consistent code html inline and in chunks with knitr

回眸只為那壹抹淺笑 提交于 2019-12-11 03:39:54

问题


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


回答1:


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:




回答2:


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



来源:https://stackoverflow.com/questions/18643863/consistent-code-html-inline-and-in-chunks-with-knitr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!