Is there a way to use a custom highlighting style in rmarkdown?
Manual is a bit silent regarding that and the closest to that is to make a full blown custom css file for everything, that would however work only for html_document and not for pdf_document (see https://bookdown.org/yihui/rmarkdown/html-document.html#appearance-and-style )
The newer versions of Pandoc support this:
http://pandoc.org/MANUAL.html#syntax-highlighting
but when anything else but one of the default pandoc styles is specified, rmarkdown throws an error.
For example, when I download zenburn.css from highlight.js library, modify it and want to use it:
```
title: Some title
output:
html_document:
theme: readable
highlight: zenburn.css
```
I get:
Error in match.arg(highlight, html_highlighters()) :
'arg' should be one of “default”, “tango”, “pygments”, “kate”, “monochrome”, “espresso”, “zenburn”, “haddock”, “textmate”
Calls: ... -> pandoc_html_highlight_args -> match.arg
Execution halted
For posterity, since this took more time than it should:
The problem
Answers from #martin_schmelzer is correct (didn't test #tarleb's solution, since rmarkdown doesn't supposedly play well with Pandoc > 2.0 see: https://github.com/rstudio/rmarkdown/issues/1471 ). However, when you write echo=TRUE on chunk, the output is code is not tagged as R code and because of that different rules apply for it. In HTML it means that it has white background and with PDF it is formatted through verbatim environment only. For example, the markdown of following:
```{r, echo=TRUE}
foo = "bar"
foo
```
will be:
```r
foo = "bar"
foo
```
```
## [1] "foo"
```
And while the first chunk will be highlighted, the second will follow only in text color, but background will always be white. This is very problematic with darker themes, since they often have very light text color and this does not play nicely with white background. See: https://eranraviv.com/syntax-highlighting-style-in-rmarkdown/ for overview of rmarkdown highlighting styles.
HTML solution
This is made more complicated with switch between highlight.js and pandoc highlighting. If highlighting is not specified, highlight.js is used with associated tags. There the highlighting is done through external css and .js library, which are then (I presume) hashed into the HTML to make it stand-alone. So no luck there.
If some highlighting style is used however, then pandoc highlighting is used. I.e.,:
---
title = "Foo"
output:
html_document:
theme: readable
highlight: zenburn
---
In this case, there IS solution. Looking at the HTML output, there is this structure:
<style typetext/css">
pre:not([class]) {
background-color: white;
}
</style>
This means that whenever there is no style in specific code chunk (applies only to the "echo" chunks since by default rmarkdown assumes R), the background is white. This behaviour can be changed just by including following chunk in the .Rmd file:
```{css, echo = FALSE}
pre:not([class]) {
color: #333333;
background-color: #cccccc;
}
```
and their behaviour can be fully specified accordingly. Here the color and background as reverse of the zenburn style. The output looks like this:
Before:
After:
PDF solution
With PDF, it is a little bit easier to find the problem, but little bit more complicated to solve it. If one looks at the .tex file, you can see that while all the chunks with an actual code have a lot of going on around them, the echo chunks are wrapped only in a simple verbatim environment. The result looks like this:
While it is more readable than the HTML output, since it does not share the text color defined by highlighting style, it kind of blends into the text and creates and breaks the feeling of uniform style across outputs. The solution is, as mentioned in previous answer, to use:
---
title: "Foo"
output:
pdf_document:
highlight: zenburn
includes:
in_header: highlight_echo.tex
---
And a following construct that utilize package framed which is already included:
\usepackage{xcolor}
\definecolor{backgroundecho}{HTML}{cccccc}
\definecolor{textecho}{HTML}{333333}
\let\oldverbatim=\verbatim
\let\oldendverbatim=\endverbatim
\makeatletter
\renewenvironment{verbatim}{
\def\FrameCommand{
\hskip-\fboxsep
\color{textecho}
\colorbox{backgroundecho}
}
\MakeFramed{\#setminipage}
\oldverbatim
}
{
\oldendverbatim
\vskip-2em\#minipagefalse % The size required for this negative space is probably in some variable
\endMakeFramed
}
\makeatother
This redefine the verbatim environment to have colored background and colored text. The result is unified formatting of the "echo" chunks:
So thanks again #tarleb and #martin_schmelzer, I wouldn't be able to solve it without you!
It appears that you are trying to use a CSS file as a highlight style. This won't work (in general), as pandoc expects a highlighting styles to be defined using a special JSON format. To use a modified zenburn, one will have to create a new style file via pandoc --print-highlight-style zenburn > myzenburn.style, and then modify the new file myzenburn.style.
To use the new style, one must circumvent R Markdown by passing the necessary options directly to pandoc.
output:
html_document:
theme: readable
pandoc_args: --highlight-style=myzenburn.style
However, this will only work for non-HTML output formats, as knitr interferes whenever highlight.js can be used.
At least for HTML documents, you can simply include your customized styles using the css YAML option:
---
title: Some title
output:
html_document:
theme: readable
css: zenburn.css
---
Concerning PDF documents, you could check the intermediate TeX file. There you will find a block of commands that look like
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.96,0.35,0.01}{\textit{#1}}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.93,0.29,0.53}{\textbf{#1}}}
These are the lines that define the code highlighting. The first one for example defines the color for comments. You could write a header.tex in which you redefine these commands using \renewcommand
\renewcommand{\CommentTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{\textit{#1}}}
\renewcommand{\KeywordTok}[1]{\textcolor[rgb]{0.13,0.29,0.53}{\textbf{#1}}}
and include it in your document right before the body.
Here is an example in which we alter the highlighting of comments and keywords within the body:
---
title: Some title
output:
pdf_document:
keep_tex: true
---
```{r}
# This is a test
head(mtcars)
```
\renewcommand{\CommentTok}[1]{\textcolor[rgb]{0.96,0.35,0.01}{\textit{#1}}}
\renewcommand{\KeywordTok}[1]{\textcolor[rgb]{0.93,0.29,0.53}{\textbf{#1}}}
```{r}
# This is a test
head(mtcars)
```
Related
I need to get Quarto to put figure captions above the figure, rather than the default (below).
Following the documentation I used this:
---
title: "Test title"
format: docx
fig-cap-location: top
---
```{r}
#| label: fig-test
#| fig-cap: This caption should be above the figure
plot(cars)
'``
However, this renders like so:
I see that some people have resorted to LaTeX customisations or knit hooks, however I'm also failing at those (and I don't understand why the simple YAML marker I used, that is recommended in the documentation, isn't working).
Edit: as Mael pointed out, fig-cap-location is not an option for docx outputs. The Quarto documentation has since been amended to clarify this.
If you check the list of MS Word options, fig-cap-location is not actually one of them (compared to e.g., PDF options), so this option is just not available with a docx output.
I am preparing a manuscript for publication and need a way to change (remove actually) the background color of code chunks in my PDF file (generated through Latex).
Reproducible example:
---
title: TestFile
output:
pdf_document: null
---
```{r,echo=TRUE}
test=c(1,2,3)
print(test)
```
```{r,echo=TRUE}
test=c(1,2,3)
print(test)
Another option, is to use Pandoc Syntax Highlighting styles, which is very simple and has very nice options. Compared to the LaTeX option you used, this is perhaps less flexible, but has the advantage of changing not only the background of code chunks, but also the font colour.
To do this, you only have to add the highlight style you want to the YAML. For example, adding the zenburn highlight:
output:
pdf_document:
highlight: zenburn
Will produce this:
Instead of this:
I hope this helps, but let me know if not.
I think I've found a solution. This is a purely latex solution, but it does the trick for what I need (which is outputting to PDF via latex) using the package xcolor. [PDF output] https://i.stack.imgur.com/yEADg.png
Reproducible Example:
---
title: TestFile
output:
pdf_document: null
header-includes: \usepackage{xcolor}
---
\definecolor{shadecolor}{RGB}{255,255,255}
```{r,echo=TRUE}
test=c(1,2,3)
print(test)
```
I'm having some trouble to compile an entire document from many Rmd files by using the bookdown approach.
If I knit individual .Rmd files then 'preamble.tex' included in YAML options is taken into account.
If I render the book (with both approaches described here), then 'preamble.tex' is ignored.
To make things concrete, consider the following mwe:
preamble.tex:
\usepackage{times}
index.Rmd:
---
title: "My paper"
site: "bookdown::bookdown_site"
output:
bookdown::pdf_document2:
includes:
in_header: "preamble.tex"
---
01-intro.Rmd:
# Introduction
This chapter is an overview of the methods that we propose to solve an **important problem**.
Then, by knitting 'index.Rmd' or '01-intro.Rmd' the font indicated in 'preamble.tex' is used.
However when rendering with bookdown::render_book('index.Rmd',"bookdown::pdf_book", new_session = T) it is simply ignored.
What is more, in my actual project there are other output options that end up ignored. For example, I use toc: false and it works when knitting single files, but fails when rendering the document.
In this simple example it would be okay to use a single file, but my actual project has many chapters with R chunks within each of them. Thus, building a single file doesn't seem a good idea.
I appreciate any hints on what I am missing here.
Thanks in advance.
What you are missing here is that in your YAML header, preamble.tex is included for the bookdown::pdf_document2 output format and not bookdown::pdf_book, the format you pass to the output_format argument in bookdown::render_book(). For this reason, other YAML options (like toc: true) do not work either.
Running
bookdown::render_book('index.Rmd', "bookdown::pdf_document2", new_session = T)
instead should work.
I recently asked
Changing the font size of figure captions in RMarkdown HTML output
and I got a very nice answer which uses this CSS method. I wanted to try the same, but this time with Word output. If you don't want to read my former question, I summarize the issue here: I'd like to make the font size of all figure captions in my R Markdown document smaller. The final output is Word,this time, and I'm working in R Studio. To load the picture, I use the include_graphics function from knitr, because I've been told it's the best way (see here). My .Rmd file is:
---
title: "ppp"
author: "ppp"
date: "`r Sys.Date()`"
output:
word_document:
fig_caption: yes
html_document:
fig_caption: yes
---
<style>
p.caption {
font-size: 0.8em;
}
</style>
```{r setup, include=FALSE}
library(knitr)
opts_chunk$set(echo = FALSE)
```
```{r foo, fig.cap="$f_{p}$ as a function of $g$ for various values of $r=\\frac{\\rho_{w}}{\\rho_{a}}$"}
# All defaults
include_graphics("download.jpg")
```
This is regular text.
The corresponding output is:
Clearly, this CSS method doesn't work (I guess it's something related to HTML, so it doesn't render in Word). In Word I can manually change the font size for each caption, but I'd rather set some global R Markdown parameter. Is that possible?
Almost as easy as in the HTML case. The following applies to the workflow using LibreOffice. But in Word it should be almost the same:
Produce your docx output file.
Open it in LibreOffice (or Word, or Pages, ...)
In LibreOffice, right-click the caption and choose Edit Style (in Word you can open the styles pane with Ctrl+Shift+Alt+S)
In the menu that popped up you can modify the style for Image Captions
When you are done editing the style, click Apply and just save the file as a docx called template.docx
Finally, add a style reference in the YAML header of your Rmd document like
title: "ppp"
author: "ppp"
date: "July 4, 2017"
output:
word_document:
reference_docx: template.docx
fig_caption: yes
And the captions should be smaller now according to how you changed the style in your reference document.
When using knitr and rmarkdown together to create a word document you can use an existing document to style the output.
For example in my yaml header:
output:
word_document:
reference_docx: style.docx
fig_caption: TRUE
within this style i have created a default table style - the goal here is to have the kable table output in the correct style.
When I knit the word document and use the style.docx the tables are not stylized according to the table.
Using the style inspector has not been helpful so far, unsure if the default table style is the incorrect style to modify.
Example Code:
```{r kable}
n <- 100
x <- rnorm(n)
y <- 2*x + rnorm(n)
out <- lm(y ~ x)
library(knitr)
kable(summary(out)$coef, digits=2, caption = "Test Captions")
```
I do not have a stylized document I can upload for testing unfortunately.
TL;DR: Want to stylise table output from rmarkdown and knitr automatically (via kable)
Update: So far I have found that changing the 'compact' style in the docx will alter the text contents of the table automatically - but this does not address the overall table styling such as cell colour and alignment.
Update 2: After more research and creation of styles I found that knitr seems to have no problem accessing paragraph styles. However table styles are not under that style category and don't seem to apply in my personal testing.
Update 3: Dabbled with the ReporteRs package - whilst it was able to produce the tables as a desired the syntax required to do so is laborious. Much rather the style be automatically applied.
Update 4: You cannot change TableNormal style, nor does setting a Table Normal style work. The XML approach is not what we are looking for. I have a VBA macro that will do the trick, just want to remove that process if possible.
This is essentially a combination of the answer that recommends TableNormal, this post on rmarkdown.rstudio.com and my own experiments to show how to use a TableNormal style to customize tables like those generated by kable:
RMD:
---
output:
word_document
---
```{r}
knitr::kable(cars)
```
Click "Knit Word" in RStudio. → The document opens in Word, without any custom styles yet.
In that document (not in a new document), add the required styles. This article explains the basics. Key is not to apply direct styles but to modify the styles. See this article on support.office.com on Style basics in Word.
Specifically, to style a table you need to add a table style. My version of Word is non-English, but according to the article linked above table styles are available via "the Design tab, on the Table Tools contextual tab".
Choose TableNormal as style name and define the desired styles. In my experiments most styles worked, however some did not. (Adding a color to the first column and making the first row bold was no problem; highlighting every second row was ignored.) The last screenshot in this answer illustrates this step.
Save the document, e.g. as styles.docx.
Modify the header in the RMD file to use the reference DOCX (see here; don't screw up the indentation – took me 10 minutes find this mistake):
---
output:
word_document:
reference_docx: styles.docx
---
Knit to DOCX again – the style should now be applied.
Following the steps I described above yields this output:
And here a screenshot of the table style dialog used to define TableNormal. Unfortunately it is in German, but maybe someone can provide an English version of it:
As this does not seem to work for most users (anyone but me …), I suggest we test this systematically. Essentially, there are 4 steps that can go wrong:
Wrong RMD (unlikely).
Differences in the initially generated DOCX.
Differences in how the TableNormal style is saved in the DOCX.
Differences in how the reference DOCX is used to format the final DOCX.
I therefore suggest using the same minimal RMD posted above (full code on pastebin) to find out where the results start do differ:
My initially generated DOCX.
The same document with TableNormal added: reference.docx
The final document.
The three files are generated on the following system: Windows 7 / R 3.3.0 / RStudio 0.99.896 / pandoc 1.15.2 / Office 2010.
I get the same results on a system with Windows 7 / R 3.2.4 / RStudio 0.99.484 / pandoc 1.13.1 / Office 2010.
I suppose the most likely culprits are the pandoc and the Office versions. Unfortunately, I cannot test other configurations at the moment. Now it would be interesting to see the following: For users where it does not work, what happens …
… if you start from my initial.docx?
If that does not work, what if you use my reference.docx as reference document?
If nothing works, are there eye-catching differences in the generated XML files (inside the DOCX container)? Please share your files and exact version information.
With a number of users running these tests it should be possible to find out what is causing the problems.
This was actually a known issue. Fortunately, it was solved in v2.0 or later releases of pandoc.
And I have tested the newer version, and found that there is a newly-added hidden style called "Table". Following #CL.'s suggestions to change "Table" style in reference.docx will be okay now.
In addition, look at this entry of pandoc's v2.0 release notes:
Use Table rather than Table Normal for table style (#3275). Table Normal is the default table style and can’t be modified.
As of 2021, I could not get any of the other suggested answers to work.
However, I did discover the {officedown} package, which, amongst other things, supports the styling of tables in .docx documents. You can install {officedown} with remotes::install_github("davidgohel/officedown")
To use {officedown} to render .Rmd to .docx you must replace
output:
word_document
in your document header with
output:
officedown::rdocx_document
In addition to this the {officedown} package must be loaded in your .Rmd.
As with the word_document output format, {officedown} allows us to use styles and settings from template documents, again with the reference_docx parameter.
With a reference document styles.docx, a minimal example .Rmd may look like:
---
date: "2038-01-19"
author: "The Reasonabilists"
title: "The end of time as we know it"
output:
officedown::rdocx_document:
reference_docx: styles.docx
---
```{r setup, include = FALSE}
# Don't forget about me: I'm important!
library("officedown")
```
{officedown} allows us to go one step further and specify the name of the table style to use in the document's front matter. This table style could be a custom style we created in styles.docx, or it could be one of Word's in-built styles you prefer.
Let's say we created a style My Table:
We could tell {officedown} to use this table style in our front matter as:
output:
officedown::rdocx_document:
reference_docx: styles.docx
tables:
style: My Table
Putting this altogether, knitting the minimal .Rmd:
---
date: "2038-01-19"
author: "The Reasonabilists"
title: "The end of time as we know it"
output:
officedown::rdocx_document:
reference_docx: styles.docx
tables:
style: My Table
---
```{r setup, include = FALSE}
# Don't forget about me: I'm important!
library(officedown)
```
```{r}
head(mtcars)
```
Resulting in a .docx document which looks like:
TableNormal doesn't work for me too.
On my Dutch version of Word 2016 (Office 365), I found out that I could markup tables with the style Compact.
Input (refdoc.docx contains the Compact style):
---
title: "Titel"
subtitle: "Ondertitel"
author: "`r Sys.getenv('USERNAME')`"
output:
word_document:
toc: true
toc_depth: 2
fig_width: 6.5
fig_height: 3.5
fig_caption: true
reference_docx: "refdoc.docx"
---
And RMarkdown:
# Methoden {#methoden}
```{r}
kable(cars)
```
Output:
You need to have a reference_docx: style.docx which has "Table" style in it. (see #Liang Zhang's explanation and links above).
Create a basis reference document using pandoc (source). In command line (or cmd.exe on Windows) run:
pandoc -o custom-reference.docx --print-default-data-file reference.docx
In this newly created reference.docx file, find the table created (a basic 1 row table with a caption).
While the table is selected, click "Table Design" and find "Modify Table Style":
Modify the style of the table as you wish and use this reference document in your RMD document (see the first answer by #CL.).
Using this reference document, you can also change the table and figure caption styles.
I was able to get my word output to use a default table style that I defined in a reference .docx.
Instead of 'TableNormal', the table style it defaulted to was 'Table'.
I discovered this by knitting an rmarkdown with a kable.
---
date: "December 1, 2017"
output:
word_document:
reference_docx: Template.docx
---
`r knitr::kable(source)`
Then I took a look at that generated document's XML to see what style it had defaulted to.
require(XML)
docx.file <- "generated_doc.docx"
## unzip the docx converted by Pandoc
system(paste("unzip", docx.file, "-d temp_dir"))
document.xml <- "temp_dir/word/document.xml"
doc <- xmlParse(document.xml)
tblStyle <- getNodeSet(xmlRoot(doc), "//w:tblStyle")
tblStyle
I defined the 'Table' style to put some color and borders in the reference docx. This works for one standard table style throughout the document, I haven't found a way to use different styles throughout.
This stayed true even after I opened the reference doc and edited it.