Keeping R Markdown syntax highlighting when printing - r

I'm afraid the response will be: "Markdown is meant to be simple and it doesn't do that", but it (almost) never hurts to ask.
When writing an R Markdown document I can view the HTML file in a browser and it looks great. When I try to print it, either on paper or as PDF, the color in the figures is printed but not the syntax highlighting. Is there a way to maintain syntax highlighting when printing?
Example:
Minimal Example
=====
This text looks great in the file and the plot prints in color, but see commented code below.
```{r}
# this commented line will be green in the HTML file, but will be black when I print it
z <- cor(mtcars)
require(lattice) # 'require' will be blue in the HTML file, but will be black when I print it
levelplot(z)
```
I push the "Knit HTML" button in RStudio and open the HTML in Chrome or Safari and there are no problems. If I print from the HTML from the browser all the syntax highlighting is lost.

After doing your 'Knit' to your original example.Rmd you will have an example.md in your working path, then use pandoc...
# for pdf (you need to have latex installed)
system( "pandoc example.md -o example.pdf")
# for syntax-highlight persistant html
system("pandoc example.md -o example.html -s -S")

One solution that I also found is to knit to HTML, preview the html file in the browser, and then highlight everything and paste it into a MS Word document. From there you can export to PDF or print. It unfortunately does not copy all of the images to the Word document. But if all you need is the syntax highlighting, and not too worried about images or plots, then this solution is fairly straight forward. It actually copies the boxes of code a little better than the pandoc solution, but with the drawback of no images.

Related

Change Background color of RMarkdown PDF Code Chunk

I am trying to change the code chunk formatting options in a rmarkdown document that is generated as a pdf. I want the formatting for these code chunks to be different. I want similar to
class.source="bg-info", class.output="bg-warning"
for HTML documents.
Not sure if I understood your question correctly. Please always include an minimum working example (MWE) with your question for greater clarity. Since it is not outline exactly what is required, a general outline is provided.
To change the code chunk formatting options in a Rmarkdown document (PDF or HTML) you can use the built-in Pandoc Syntax Highlighting styles. You can change both the background of code chunks, and the font color. All you have to do is to add the highlight in YAML.
highlight specifies the syntax highlighting style. Some alternatives are default, tango, pygments, kate, monochrome, espresso, zenburn, haddock, breezedark, and textmate. You can also use null to prevent any highlighting. For example:
title: "A nice document"
output:
html_document:
highlight: haddock
You can change the the appearance of your code and output with some predefined CSS classes for backgrounds in HTML: "bg-primary", "bg-success", "bg-info", "bg-warning", and "bg-danger". Arbitrary class names and user-define custom CSS rules are also allowed. A detailed discussion can be found in Yihui Xie's R Markdown Cookbook.

Inline code in R markdown PDF file is not displayed correctly

My R markdown PDF file does not show inline code as it should. This only works correct when choosing HTML as output file.
Generally inline code should look like this. So when highlighting some words within my text, I want it to look like this.
E.g. I want to have this sentence in my PDF output:
A good way to pronounce %>%when reading code is then.
Instead I get what you see here:
The image shows how the inline code is displayed in my output. Only changed font and style, instead of grey background.
I use exactly the same code as I am using here at stack overflow: `` these signs before and after the text I want to highlight.
Any tip how to fix this? I need PDF output, and not HTML.
Thanks a lot!
Text like `this` is translated into the LaTeX command \texttt{this}. LaTeX commands can be changed, so we can modify the \texttt command to create a color box:
```{=latex}
\definecolor{codegray}{HTML}{cccccc}
\let\textttOrig\texttt
\renewcommand{\texttt}[1]{\textttOrig{\colorbox{codegray}{#1}}}
```
Add the above at the beginning of your Rmd document (right after the YAML header) to get a gray background for you inline code snippets.

Underline in RMarkdown to Microsoft Word

I am trying to figure out in RMarkdown how to underline some words. If I am knitting to HTML I can do this:
<u>These words are underlined</u>
Which works fine in that case. But the underlining is not persisted when I knit to Microsoft Word. I don't believe any changes have been made to RMarkdown to natively do it such as the commands for bold and italics. Any suggestions?
Thanks
Simply you can use the underline class [Your text]{.underline}, which pandoc innately supports, as like the small caps class [Your text]{.smallcaps}. This method also works for the production of other formats, such as HTML and PDF.
---
title: "Untitled"
output: word_document
---
[Underlined text]{.underline}
[Small Capital text]{.smallcaps}
For what it's worth ... (; As far as I get it, this is not possible by using HTML tags. The reason why HTML tags work when rendering to HTML is that the HTML code is not touched upon by rmarkdown, knitr or pandoc and simply passed through to the final HTML document as text. In case of HTML the browser knows what to do with this "text". But in Word or Latex it's simply text which will be displayed as is.
However, for Word output you could have a look at the officedown package which adds some addtional Word functionalities to rmarkdown via the officer officer package , e.g. the following example RMD shows how to get underlined text in Word:
---
title: "officedown template"
output: officedown::rdocx_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, fig.cap = TRUE)
library(officedown)
library(officer)
ft <- fp_text(underlined = TRUE)
```
This document presents most of the features of the package `r ftext("officedown", ft)`.
Just tried everything that came to my mind - seems to be not possible
(would be great to hear about actually working solutions)
I tried the following:
<u> text </u>
<ins> text </ins>
<span style="text-decoration:underline"> text </span>
$\text{\underline{LaTeX makes it possible}}$
$\underline{LaTeX makes it possible}$
While a most of these worked for html_document - none really worked for Rmarkdown to Word.
<u> - the obvious solution - didn't work.
<ins> which is also often suggested - didn't work.
html5 markup - didn't work
LaTeX - did not work
Might well be, that this just is not possible.
The problem has two parts:
1.) Getting Rmarkdown/pandoc to render the html when knitting to a word file. How to achieve this has been explained here: HTML tags in Rmarkdown to word document by user #tarleb (please consider upvoting that answer as it is the basis for mine).
2.) <u> for underlining has been more or less deprecated. However, the <u> tags simply have to be wrapped inside a <p> to work.
So this should achieve what you want:
---
output:
word_document:
md_extensions: +raw_html-markdown_in_html_blocks
pandoc_args: ['--lua-filter', 'read_html.lua']
---
<p><u>This text will be underlined.</u> This not anymore</p>
<u>But this will not.</u>
<p style="text-decoration: underline;">Neither will this.</p>
with a file read_html.lua in the same directory with this content:
function RawBlock (raw)
if raw.format:match 'html' and not FORMAT:match 'html' then
return pandoc.read(raw.text, raw.format).blocks
end
end
A workaround
RMarkdown is based on Pandoc, and Pandoc's Markdown does not natively support underline. Underline in Pandoc's Markdown is implemented by HTML tag <u>...</u>. However, <u>...</u> cannot be not converted into underline text in docx or pdf(tested with pandoc 2.10.1). A workaround is modifying the text style in MS Word.
Choose a substitute for <u>...</u>, such as ***...***.
---
output:
word_document: default
---
This is a regular paragraph.
***This paragraph is bold italic at first. It will be underlined later.***
Knit Rmarkdown document into docx
Replace bold italic text with underline text in Word.
Press Ctrl + H.
Set the text format in Format > Font.
Find Bold Italic text.
Replace with Regular Underline text.
Press Replace All
If you have used <u>...</u>, replace them with ***...***.
Press Ctrl + F.
check the regex option.
replace <u>(.+)<\/u> with ***$1*** .
Press All next to Replace.
Return to step 1 and step 2.
Advice
I recommend sticking to the native syntax of Rmarkdown and Pandoc's Markdown. Thought the syntax is limited, it works well with different output formats. Limited syntax is the power of Markdown! It is so simple that it can be converted into many different output formats. I also recommend following the concept of separation of content and style. It saves me from formatting contents repeatedly.

R: how to center output in R markdown

I know I can set fig.align = 'center' if I want to center my figure. But what if I want to center my output in a pdf document?
The following code worked for me.
\center Centered Text \center
And, if you need to put it in bold, as my case, you can use the underline (two at the beggining, two at the end):
\center __Centered Text__ \center
Hopefully it is not too late to add my answer.
You can use html tags in Rstudio Markdown documents.
To center a text you just need to:
<center> TEXT TO CENTER </center>
This works for me when knitting Rstudio Markdowns.
The option for centering a plot you generated by R code in Rmd file and that for an existing figure from a file elsewhere is different.
For the figures you generated in R, I think fig.align="center" is sufficient, even if you want a PDF output.
For <center> <\center> to work, you can only use an HTML output. If you still want PDF output, I think you can use include_graphics(your_img.png) from knitr package, and then you can use chunk options like fig.align="center". If you also want to change the size of this figure, please use something like out.width="50%", but not fig.width.
For more details, I found this article really useful tips and tricks for working with images and figures in r markdown documents.

How to produce HTML tables and accompanying CSS using R Markdown or HTML Sweave?

I previously asked a question about how to export a HTML table in R and have control over line borders.
I'm used to LaTeX where when you create a table, the formatting of the table is largely determined by the text and markup that appears at that point. This works well for Sweave, because your R code chunk can output LaTeX table markup at that point. I also understand that there are tools like xtable that can produce HTML markup for a table.
However, control over HTML tables seems to rely on style sheets, which are meant to appear in the header of the document and not in the location where the R code chunk is placed. Of course, I could just put content in the style sheet, but in scientific applications often there can be some quite specific table formatting that varies in some respects from table to table.
Thus, my question:
In general, how do you format an HTML table with literate programming like R Markdown or even from raw HTML if formatting of the output requires output to be created in a separate place in the document (i.e., CSS for the table in the header) to where the R code chunk is placed (i.e.,the table itself in the body)?
I can think of three ways without messing with your toolchain, all of them are kind of hacky.
Just output the <style> right in the body. This isn't technically valid, but it will work fine in any major browser.
Emit JavaScript that creates a <style> block at runtime and appends it to the head (here's one way). This will look a little gross in the HTML source and in the R code, but it will work and it will validate.
Use a scoped style block. This would be exactly what you are looking for, except that the scope attribute is new to HTML5 and not yet implemented in any major browser. However, if you base your styles on uniquely generated IDs (i.e. your rules are written such that even if they apply to the whole document they won't mess anything up), I imagine the browsers will just ignore the "scoped" attribute and everything will work properly--then this becomes effectively a version of option 1 that happens to validate!
(I would go with #3, personally.)
If you haven't already, it'd be worth starting a thread at the RStudio support forum about this; even though it's not strictly an RStudio issue, we're obviously doing a lot of work on the end-to-end scenario of publishing reports in R Markdown and would love to find out more about your specific examples. Tables are clearly going to be a big part of what people do with this reports and we know this is a weak spot right now, one that we do want to address in future versions.
An alternative method would be to use pander as R markdown backend (sorry for this marketing-like answer, but I do think my Pandoc.brew function could be really handy for this purpose).
It is similar to knitr (parsing/evaling R commands in a markdown formatted file) but using brew syntax for R code blocks (e.g. <%...%> for general R code - like loops etc. and <%=...%> for returning results in a block). But differs from brew as Pandoc.brew does not only cat results in a code block, but runs my pander generic method which transforms (quite q wide variety of) R objects to (IMHO) pretty Pandoc's markdown format.
So running Pandoc.brew on a markdown formatted file would result in a clean markdown file with all R code blocks run - and you do not have to deal with xtable and other tweaks (not even with plots as all R code blocks resulting in an image is rendered to a png file and linked in the markdown text file).
And about why I started to answer here: with pander you can pass special options to pandoc, e.g. adding a custom CSS stylesheet (or JS etc.) to your generated HTML's header, see details on Pandoc's homepage. Based on that you could easily add your CSS file(s) or even just a bunch of style parameter. This could be done in pander with Pandoc.convert's option. BTW you do not even have to use my forked brew function, you can generate your markdown file with e.g. knitr and call Pandoc with the above function.
pander adds some CSS/JS to generated HTML files, which would generate (IMHO) quite pretty output, but you can easily customize that and adding your own files there.
For example: you would get this HTML file based this markdown by default which was Pandoc.brewed from this quite short markdown syntax brew file. BTW my github page was also generated/automatically styled by my markdown parser. I would really appreciate if you would try it :)
NOTE: to try the above calls you would need Pandoc pre-installed, also you'd need an up-to-date version of both rapport, both pander. See installation details.
One option which doesn't completely solve the problem is to use gvisTable:
Here is a basic gvisTable:
```{r message=FALSE}
# install.packages("googleVis")
library(googleVis)
library(MASS)
data(Animals)
```
```{r results='asis'}
tab1 <- gvisTable(Animals,
options = list(width = 600, height = 650,
page = "enable",
pageSize = nrow(Animals)))
print(tab1, "chart")
```
?print.gvis explains some of the options for printing the gvis object.
In partiuclar the tag="chart" option is required for R Markdown documents as this means that the output is just what is required for the object, rather than a complete HTML page as is the default.
See the output of this and a little more here
Ok, hope I got it now. You should set some additional knitr options, and you could cat() the css dynamically if you like.
<!DOCTYPE html>
<head>
<style type="text/css">
.greenback {
background-color: teal;
color: white;
}
.greenback td {
border: dotted gray;
}
.bluescreen {
background-color: blue;
color: white;
}
.bluescreen td {
border: thick solid;
padding:2px;
margin:2px;
}
</style>
</head>
<body>
<table class="greenback">
<tr><td>Hello</td><td>Mars</td><tr>
<tr><td>World</td><td>Moon</td><tr>
</table>
Could use some xtable code here instead.
<!--begin.rcode
cat('
<table class="bluescreen">
<tr><td>Hello</td><td>Mars</td><tr>
<tr><td>World</td><td>Moon</td><tr>
</table>
')
end.rcode-->
</body>
</html>
Neil Saunders has a tutorial on customising CSS for HTML generated using RStudio. It shows how you can modify the built in style file and source this alternative file.

Resources