Re: [knitr] knitr, background, code decoration

1,689 views
Skip to first unread message

Carl Boettiger

unread,
Mar 18, 2013, 12:41:32 PM3/18/13
to Eric Green, knitr
I don't think you want to use any of the LaTeX based output when generating markdown (even though you are converting it to latex and then pdf later). You cannot mix LaTeX code into markdown output -- the result would not be valid markdown.  

If you want to set background as a knitr option, make sure to use the tex or sweave format in R.  If you would rather work in markdown, then how you convert the markdown to pdf is really a pandoc issue that is independent of your knitr setup.  (You can set the background of your latex code blocks by editing the template.latex file you pass to pandoc.) Remember that knitr is not pandoc -- it is designed to output in the same language as the input, not to take markdown input and generate latex output.  

Sorry if this wasn't the answer you were hoping for and good luck!


On Mon, Mar 18, 2013 at 7:34 AM, Eric Green <epg...@gmail.com> wrote:
I am writing in RMarkdown, knitting to md, and converting the md to pdf via Pandoc with a latex template I defined. Here is how the following chunk looks in my pdf:

```{r mock-structure, results='asis', include=TRUE, tidy=TRUE, background="#F7F7F7"}

set.seed(18495)
# clusters, sites, medical providers, and intitial encounters
(c <- k.clusters)                                       # total number of clusters (defined earlier)
spc <- sample(1:4, size = c, TRUE)                      # number sites per cluster
s <- sum(spc)                                           # total number of sites
mps <- sample(2:10, size = s, TRUE)                     # number of medical providers per site
m <- sum(mps)                                           # total number of medical providers
N <- sample(0:50, size = m, TRUE)                       # number of initial encounters per provider
i <- sum(N)                                             # total number of initial encounters
```

I'd like it to look more like this example from the knitr manual.

Specifically, I would like to change the code decoration and add the background. I thought including background="#F7F7F7" in the chunk options would do it, but no luck. 

I also tried defining the following to use a theme, but no luck. I'm not sure I'm using it correctly. 

require(knitr)
thm <- knit_theme$get("print")
knit_theme$set(thm)
opts_knit$set(out.format = "latex")

I verified that I have the framed latex package installed, and I included it in my latex template preamble. Does anyone notice obvious errors? Am I doing something incorrectly on the Rmd side? Is this a latex template problem?

Any examples out there from folks with the same setup? Rstudio Rmd to md to pdf via Pandoc?

Thanks
Eric

--
You received this message because you are subscribed to the Google Groups "knitr" group.
To unsubscribe from this group and stop receiving emails from it, send an email to knitr+un...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 



--
Carl Boettiger
UC Santa Cruz
http://www.carlboettiger.info/

Eric Green

unread,
Mar 18, 2013, 2:10:11 PM3/18/13
to kn...@googlegroups.com
Thanks, Carl. I think your suggestion to modify how code chunks are handled in my latex template points me in the correct direction. I was initially confused because all of the other code chunk options in Rstudio seem to pass along to Pandoc (rmd to md to pdf), but I could not get the "background" option to work. 

On a side note, I'm not sure I follow your comment about mixing LaTex code and markdown. In my Rmd file, I mix Rmarkdown (i.e., titles and body text) with R code chunks and LaTex code for tables and figures. This all passes fine to Pandoc to create the pdf. I think I am just misunderstanding your point, but I follow your overall message.

Thanks
Eric

Carl Boettiger

unread,
Mar 18, 2013, 6:50:00 PM3/18/13
to Eric Green, knitr

On Mon, Mar 18, 2013 at 11:10 AM, Eric Green <epg...@gmail.com> wrote:

Thanks, Carl. I think your suggestion to modify how code chunks are handled in my latex template points me in the correct direction. I was initially confused because all of the other code chunk options in Rstudio seem to pass along to Pandoc (rmd to md to pdf), but I could not get the "background" option to work. 

Correct, many options are identical for all output formats (e.g. cache, comment, echo, includes, dependson, warning, etc); background happens to be unique to LaTeX.

The difficulty is that there isn't one agreed upon environment to represent code blocks in LaTeX. Knitr creates its own custom latex environment, knitrout, when used in tex format with the background option. Various syntax highlighting packages for LaTeX have invented their own environments, e.g. "minted".

Pandoc happens to use the environments "Shaded" and "Highlighted" for code blocks. We can set custom colors for these by (re)defining them in the latex template file as I mentioned earlier, e.g. see the header of this template

Though Pandoc already comes built in with a bunch of toggles for its own highlighting. e.g. if you want a faint background to your code block you might simply prefer something like pandoc --highlight-style=tango


On a side note, I'm not sure I follow your comment about mixing LaTex code and markdown. In my Rmd file, I mix Rmarkdown (i.e., titles and body text) with R code chunks and LaTex code for tables and figures. This all passes fine to Pandoc to create the pdf. I think I am just misunderstanding your point, but I follow your overall message.

Good point -- telling R to generate LaTeX tables with results="asis" is kind of a hack that will mix LaTeX and and markdown in the output. It is a hack because the knitr doesn't know you are generating special latex code, it just knows you want the output of the function call to be rendered "asis". That would be sensible if the document was already in LaTeX.

Think about the file that results -- it has a funny mixture of markdown and latex. Luckily in your case pandoc is smart enough (or stupid enough) to just ignore the latex code it sees when it expected markdown. That behavior cannot be guaranteed though -- for instance, here is a little example where we generate a latex table in a markdown file that will cause pandoc to choke:

For your workflow, you would do better to generate pandoc.tables (from the pander package) in your R markdown so that you have always have a sane (pandoc-flavored) markdown file to pass to pandoc, rather than some unpredictable chimera.


Overall, I think it is good to try and abstract styling from content (the way markdown does), but funny things can happen once you start trying to tune the styling from within your content file (the R markdown file).  Much better to let the markdown be markdown and tune the appearance by using the external tools (latex template files, CSS files, pandoc highlighter options, etc).  


Hope this helps.  

Carl

Eric Green

unread,
Mar 18, 2013, 8:19:32 PM3/18/13
to Carl Boettiger, knitr
Thanks for some very helpful clarifications. I appreciate your linking to the latex template and pointing me to pandoc's own highlighting; saved me a lot of time.

On mixing LaTex and markdown, I wonder if you see any problems with this approach (see .Rmd). You and I are generating tables differently. This approach seems to work, but I don't know if it is foolproof. 

I am a pretty new convert to reproducible research. I gravitated toward RMarkdown because I did not want to learn a bunch of LaTex at the frontend. I learned quickly that I needed to learn how to create LaTex tables because R packages like xtable weren't flexible enough.

I'll check out pander and pandoc.tables. 

Thanks again for your thoughts about my workflow.

E

Eric Green

unread,
Mar 18, 2013, 9:20:20 PM3/18/13
to kn...@googlegroups.com, Eric Green
Carl, 

One additional question. Should your latex template produce a shaded code region. I see you include "\newenvironment{Shaded}{}{}". I tried your template, but my report looks the same (no shaded region). I'm not sure if you meant to point me to a working example of shading, or get me started on modifying the template.

Thanks
Eric

Carl Boettiger

unread,
Mar 18, 2013, 9:57:28 PM3/18/13
to Eric Green, knitr

Eric,

Correct, there's no shading in that example, I just meant it as a way of customizing the shaded environment. You can check out the tex files pandoc creates using the various options to --highlight-style for more examples. For instance, the "tango" style creates a shaded background by generating latex header that looks like this:

\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{248,248,248}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{{#1}}}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{{#1}}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{{#1}}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{{#1}}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.00,0.00,0.81}{{#1}}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{{#1}}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.31,0.60,0.02}{{#1}}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{{#1}}}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{{#1}}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.94,0.16,0.16}{{#1}}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.00,0.00,0.00}{{#1}}}
\newcommand{\RegionMarkerTok}[1]{{#1}}
\newcommand{\ErrorTok}[1]{\textbf{{#1}}}
\newcommand{\NormalTok}[1]{{#1}}

Clearly you can customize these templates and pass them to pandoc to generate a syntax scheme that is different than one of the built-in themes.

Eric Green

unread,
Mar 18, 2013, 10:52:16 PM3/18/13
to Carl Boettiger, knitr
Perfect, Carl. I get it now. Thanks for taking the time to explain it to me.

Michael Reinhard

unread,
Jun 10, 2014, 5:04:07 PM6/10/14
to kn...@googlegroups.com, epg...@gmail.com
Hi Carl, 

I had the same problem as Eric had and though your answer was a little over my head, I gather that basically you can't do it from R-Markdown. But if that is the case, why do they have the "background=" option in the drop down menu within the little {r} thing? Also, you mentioned that it could be set as an option in knitr. How would I get access to the knitr options? The only thing I see is the little ball of yarn. 

Thanks, 

Michael

Carl Boettiger

unread,
Jun 12, 2014, 10:31:06 PM6/12/14
to Michael Reinhard, knitr, Eric Green
Hi Michael,

You can find the knitr documentation for options here: http://yihui.name/knitr/options Note that the description for background describes it purely as a LaTeX feature.  I suspect that RStudio is just making all chunk options available and not filtering out ones designed for LaTeX only if you're using Rmd-style chunks, but I guess you could ask them.  Not many chunks are specific in that way.  

You can nevertheless make the background whatever you want in HTML using CSS.  The usual strategy is to adapt some existing CSS templates.  You might want to take a look at RStudio's new rmarkdown package, which integrates with knitr but also provides some CSS templates built in for starters. You'll see a nice variety of preset code backgrounds, for instance. http://rmarkdown.rstudio.com/html_document_format.html

Cheers,

Carl


For more options, visit https://groups.google.com/d/optout.



--
Carl Boettiger
UC Santa Cruz
Reply all
Reply to author
Forward
0 new messages