一致的代码html内联并与knitr成块 [英] consistent code html inline and in chunks with knitr

查看:80
本文介绍了一致的代码html内联并与knitr成块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望段落中的代码与代码块中显示的代码一致.

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

例如:

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

最好内联使用<code>以外的东西,并获得与块代码相同的格式.

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

我正在使用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

谢谢

最大

推荐答案

您可以重新定义inline挂钩,并将内联代码编写为字符串.下面是一个最小的示例(请确保您使用的是所有R包的最新版本):

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>

关键是要通过highr::hi_html()突出显示语法,这是输出:

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

这篇关于一致的代码html内联并与knitr成块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆