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.
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.
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).
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With