Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change code block color in knitr/markdown

I'm working on a markdown document in Rstudio that compares Perl and R. What I'd like to be able to do is have different code block background colors depending on the language used. For example

R code block

```{r}
dog <- 1
cat <- 2
dog + cat
```

Perl code block

```{r, engine='perl'}
$dog = 1;
$cat = 2;
print $dog + $cat;
```

If you generate an html file using knitr with the above code, the r code block has a solid grey background while the output from the code block has a white/transparent background.

However, the Perl code block and output has a white/transparent background which looks confusing. My hope is that there's an elegant way to do this in markdown/knitr.

like image 451
iantist Avatar asked Feb 04 '13 21:02

iantist


People also ask

How do you change the color in Markdown?

Markdown doesn't support color but you can inline HTML inside Markdown, e.g.: <span style="color:blue">some *blue* text</span>. As the original/official syntax rules state (emphasis added): Markdown's syntax is intended for one purpose: to be used as a format for writing for the web.

How do you Markdown a code block?

To produce a code block in Markdown, simply indent every line of the block by at least 4 spaces or 1 tab. For example, given this input: This is a normal paragraph: This is a code block. A code block continues until it reaches a line that is not indented (or the end of the article).


2 Answers

I talked to Rstudio support as per Yihui's suggestion. They pointed out that I could essentially tell R to use my own style sheet with the following R code:

options(rstudio.markdownToHTML = 
function(inputFile, outputFile) {      
require(markdown)
markdownToHTML(inputFile, outputFile, stylesheet='custom.css')   
}
)

'custom.css' must be in your working directory. I downloaded R studio's CSS sheet (link) to look for a section to modify. Within the style sheet there's a block of code

code.r, code.cpp {   background-color: #F8F8F8;}

As Yihui pointed out this would only support color coded blocks for R and C++. A quick change to the following includes perl: code.r, code.cpp, code.perl { background-color: #F8F8F8;} Or make a different color by adding the following below the code.r background block.

code.perl {
background-color: #B53389;
}
like image 135
iantist Avatar answered Sep 25 '22 12:09

iantist


I think that is a question for RStudio. At the moment, it seems to support two languages only (for syntax highlighting) -- R and C++; perhaps you can file a feature request to them, or you can render your markdown output with other tools like Pandoc, or just put the md files on Github which does syntax highlighting for Perl as well, e.g. example 028-engine-perl.md.

like image 42
Yihui Xie Avatar answered Sep 23 '22 12:09

Yihui Xie