I am playing around with Quarto and really like it. One feature is to change the color of inline text with the following below syntax (the word chemical will show up in red color)
[chemical]{style="color: red"}
My question is how to change the color of the text if we assign a color to name rather than the color code or built in color code? The below will not work
var="#28A569"
[chemical]{style="color: var"}
Not sure whether Quarto offers a more straightforward approach. But one option would be to use some inline code or following the R Markdown Cookbook use a small custom function.
---
title: "Untitled"
format: html
---
[chemical]{style="color: #28A569"}
```{r, echo=FALSE}
var <- "#28A569"
```
`r sprintf('[chemical]{style="color: %s"}', var)`
```{r}
colorize <- function(x, color) {
sprintf('[%s]{style="color: %s"}', x, color)
}
```
`r colorize("chemical", var)`
An easy option would be to do this using CSS variable.
---
title: CSS variable in Inline Style
format: html
engine: knitr
---
```{css, echo=FALSE}
:root {
--color1: #28A569;
--color2: yellow;
}
```
[chemical]{style="color: var(--color1);"}
[This has colored background]{style="background-color: var(--color1);"}
[This has yellow background]{style="background-color: var(--color2);"}
I would like to apply a style to Quarto chunk output.
The first thing I made was to embed some CSS properties in a class .output in the Quarto document and then referenced it with :
```{r class.output="output"}
```
It worked, but I think it's not very efficient because I have to write it within each doc.
So I wrote a class .output with some CSS properties in a custom.scss file, but now
```{r class.output="output"}
```
doesn't work.
So where and how have I to declare it?
Many thanks!
Using a CSS style file to define CSS properties for quarto chunk output should suffice unless you want to build a custom theme (and in that case, you should use SCSS)
So write the CSS properties for a class selector in a styles.css file and use css YAML key to refer to this styles.css from a quarto document file.
style.css
.output {
color: green;
background-color: black;
}
quarto-doc.qmd
---
title: "Output-style"
format:
html:
css: styles.css
---
```{r}
#| class-output: output
x = "hello quarto"
print(x)
1 + 1
```
You can add options to executable code like this
```{r}
#| class-output: output
2 * 2
```
Now for the case of SCSS, to refer to a scss file, you need to use theme yaml key instead of css.
custom_style.scss
/*-- scss:rules --*/
.output {
color: green;
background-color: black;
}
quarto-doc.qmd
---
title: "Output-style"
format:
html:
theme: output_style.scss
---
```{r}
#| class-output: output
x = "hello quarto"
print(x)
1 + 1
```
And the output is similar as the above.
I am making a book via bookdown.
I know it is possible to omit headings from the Table of Contents by adding the attributes {.unlisted .unnumbered}, as shown in Section 4.18 of the R Markdown Cookbook.
However, how can I add arbitrary content to the Table of Contents?
If I only needed to add this for the PDF output, I could use (e.g.) the LaTeX command \addcontentsline, but I need this to show in the HTML contents sidebar as well.
For example, if you set up a new default bookdown project from RStudio, it includes the file 01-intro.Rmd.
The first few lines are
# Introduction {#intro}
You can label chapter and section titles using `{#label}` after them, e.g., we can reference Chapter \#ref(intro). If you do not manually label them, there will be automatic labels anyway, e.g., Chapter \#ref(methods).
Figures and tables with captions will be placed in `figure` and `table` environments, respectively.
I need to be able to create arbitrary divs that are added to the table of contents, like so:
# Introduction {#intro}
You can label chapter and section titles using `{#label}` after them, e.g., we can reference Chapter \#ref(intro). If you do not manually label them, there will be automatic labels anyway, e.g., Chapter \#ref(methods).
::: {#arbitrary-header <some other attribute?>}
Figures and tables with captions will be placed in `figure` and `table` environments, respectively.
:::
Which would add the sentence "Figures and tables with captions will be placed in figure and table environments, respectively." in both the LaTeX Table of Contents and the sidebar on the HTML output.
The context of this problem is that I need to place a header inside another custom div that formats the content within a colorbox to make it stand out.
Otherwise, I could of course just add another heading via ## before the sentence above.
We could use an R function that prints a colored box and adds the title to the TOC depending on the output format. For gitbook output, this is easily done using HTML and markdown. For pdf_book we may use a LaTeX environment for colored boxes like tcolorbox.
Here is the function (define in a code block in .Rmd file):
block_toc <- function(title, level, content, output) {
if(output == "html") {
title <- paste(paste(rep("#", level), collapse = ""), title, "{-}")
cat('<div class = "myblock">', title, '<p>', content, '</p>\n</div>', sep = "\n")
} else {
level <- c("part", "chapter", "section")[level]
cat('\\addcontentsline{toc}{', level, '}{', title, '}',
'\n\\begin{mybox}\n\\textbf{\\noindent ', title, '}\n\\medskip\n\n', content,
'\n\n\\end{mybox}', sep = "")
}
}
Depending on the output format, block_toc() concatenates and prints the code for the blocks and, of course, also ensures that the title is added to the TOC. You can set the level of the TOC where the box title is added using level.
Use block_toc() like this in a chunk:
```{r, results='asis', echo=F, eval=T}
block_toc(
title = "Central Limit Theorem",
level = 2
content = "The CLT states that, as $n$ goes to infinity,
the sample average $\\bar{X}$ converges in distribution
to $\\mathcal{N}(\\mu,\\sigma^2/n)$.",
output = knitr::opts_knit$get("rmarkdown.pandoc.to")
)
```
output = knitr::opts_knit$get("rmarkdown.pandoc.to") will get and pass the current output format to the function when building the book.
Some styles for appealing boxes
Add to preamble.tex (for colored box in PDF output -- include file in YAML header). This will define a tcolorbox environment for generating blue boxes.
\usepackage{tcolorbox}
\definecolor{blue}{HTML}{D7DDEF}
\definecolor{darkblue}{HTML}{2B4E70}
\newtcolorbox{mybox}{colback=blue, colframe=darkblue}
Add to style.css (styles for HTML colored box) or include in a ```{css} code chunk:
.myblock {
background-color: #d7ddef;
border: solid #2b4e70;
border-radius: 15px;
}
.myblock p, .myblock h2, .myblock h3 {
padding: 5px 5px 5px 20px;
margin-top: 0px !important;
}
For HTML output (gitbook) this yields
and for LaTeX output (pdf_book) it looks like this
with a corresponding entry at the section level in the TOC.
Maybe this solution?
CSS-file:
k1 {
font-family: 'Times New Roman', Times, serif;
font-size: 12pt;
text-align: justify;
}
#TOC {
color:black;
background-color: white;
position: fixed;
top: 0;
left: 0;
width: 250px;
padding: 10px;
overflow:auto;
margin-left: -5px;
}
body {
max-width: 800px;
margin-left:300px;
line-height: 20px;
}
div#TOC li {
list-style:none;
}
h2#toc-title {
font-size: 24px;
color: Red;
}
Rmd-file:
---
title: "Arbitrary elements"
author: "Me"
date: "`r Sys.Date()`"
output:
bookdown::html_document2:
toc: true
css: "arb.css"
toc-title: "Contents"
---
# My question is it: "..."
# Introduction of our story ...
# It was a strange person ...
## The Flame was in his body ...
# <k1> Figures and tables with captions will be placed in `figure` and `table` environments, respectively. </k1> {-}
## Where is the love, friends?
We'll be using a Lua filter for this, as those are a good way to modify R Markdown behavior. The "Bookdown Cookbook" has an excellent overview and includes a description of how to use Lua filters.
The way we are doing this is to side-step the normal TOC generator and rewrite it in Lua. Then we add our new TOC as a meta value named table-of-contents (and toc, for compatibility), which is enough to be included in the output.
So first let's dump the code to create a normal TOC:
_ENV = pandoc
local not_empty = function (x) return #x > 0 end
local section_to_toc_item
local function to_toc_item (number, text, id, subcontents)
if number then
text = Span({Str(number),Space()} .. text, {class='toc-section-number'})
end
local header_link = id == '' and text or Link(text, '#' .. id)
local subitems = subcontents:map(section_to_toc_item):filter(not_empty)
return List{Plain{header_link}} ..
(#subitems == 0 and {} or {BulletList(subitems)})
end
section_to_toc_item = function (div)
-- bail if this is not a section wrapper
if div.t ~= 'Div' or not div.content[1] or div.content[1].t ~= 'Header' then
return {}
end
local heading = div.content:remove(1)
local number = heading.attributes.number
-- bail if this is not supposed to be included in the toc
if not number and heading.classes:includes 'unlisted' then
return {}
end
return to_toc_item(number, heading.content, div.identifier, div.content)
end
-- return filter
return {
{ Pandoc = function (doc)
local sections = utils.make_sections(true, nil, doc.blocks)
local toc_items = sections:map(section_to_toc_item):filter(not_empty)
doc.meta['table-of-contents'] = {BulletList(toc_items)}
doc.meta.toc = doc.meta['table-of-contents']
return doc
end
},
}
The code makes a few minor simplifications, but should produce an identical TOC for most documents. Now we can go on and modify the code to our liking. For example, to include divs with the class toc-line, the section_to_toc_item could be modified by adding this code at the start of the function:
section_to_toc_item = function (div)
if div.t == 'Div' and div.classes:includes('toc-line') then
return to_toc_item(nil, utils.blocks_to_inlines(div.content), div.identifier)
end
⋮
end
Modify the code as you see fit.
Also, if you want to exclude the extra TOC lines from the normal output, you'll have to filter them out. Let the script return a second filter to do that:
return {
{ Pandoc = function (doc) ... end },
{ Div = function (div) return div.classes:includes 'toc-line' and {} or nil end }
}
I know how to change R markdown style with a custom css file. However, when the changes are minor, I prefer internal or even inline css, to save trouble from managing two files. I googled and haven't find a solution for this. Below is a simple example of changing style with an external css file. Is there a way to do it with internal or inline css?
The R markdown file:
---
title: "test"
output:
html_document:
css: test.css
---
## Header 1 {#header1}
But how to change style with internal css?
The test.css file:
#header1 {
color: red;
}
Markdown accepts raw HTML and passes it through unaltered, so define your "styled" elements as HTML:
<h2 style="color: red;">Header 1</h2>
Of course, some tools don't actually allow the raw HTML to be passed through (for security reasons or because the final output is not HTML), so your mileage may vary.
Depending on the Markdown implementation you are using, you may be able to define styles in the attribute list (if it supports arbitrary keys):
## Header 1 {style="color: red;"}
However, that is the least likely to work.
And remember, HTML <style> tags do not need to be in the document <head> to work. If you can use raw HTML, you can include a <style> element in the body of your document (as pointed out by #user5219763 in a comment):
---
title: "test"
output:
html_document
---
<style>
#header1 {
color: red;
}
</style>
## Header 1 {#header1}
But how to change style with internal css?
If you don't want to create an external .css file, but would like to define several styles and would rather keep your code less crowded, another possibility is to use a css chunk at the beginning of your R markdown:
---
title: "test"
output: html_document
---
```{css, echo = FALSE}
#header1 {
color: red;
}
```
## Header 1 {#header1}
In the css chunk, you can control multiple styles, as you would do in an external .css file.
Another, sort of hacky option is to specify a css file in the script, then create it in the first chunk.
e.g. the first 18 lines of your .Rmd file:
---
title: "Something Important"
output:
html_document:
css: mystyle.css
---
```{r b, echo=F}
writeLines("td, th { padding : 6px }
th { background-color : coral ;
color : white;
border : 1px solid white; }
td { color : black ;
border : 1px solid skyblue }
h1, h2, h3, h4, h5, p { font-family: consolas; ",
con = "mystyle.css")
```
In the above, I first reference the file mystyle.css in the header block of markdown. Then, I create the file using writeLines(), and save it to the file specified with con = ....
Personally, I think the best option is to just throw your code in between some <script></script> tags if it's a one-off R script.
However, if you do want to create an external file, but don't want to edit a separate file, the above method provides a workaround. It just feels odd.
In knitr I want to add a (small) data frame as a table using the kable package:
---
output: html_document
---
```{r}
knitr::kable(mtcars[1:5,1:5], format="html")
```
This returns a compact table as above, while changing it to format="markdown"returns a nice table but spanning the whole page:
I have found the knitr manual but it does not cover the extra formatting options for each format. How can I change the size of a knitr table or even better, where can I get this information from?
The general approach would be to use your own custom CSS and include that in the YAML at the start of the document.
You can actually sort of do this from within your document, but I would suggest editing your CSS outside of the document and working from there.
Here's a minimal example:
---
title: "Test"
date: "24 October 2015"
output:
html_document:
css: mystyle.css
---
```{r, results='asis'}
writeLines("td, th { padding : 6px } th { background-color : brown ; color : white; border : 1px solid white; } td { color : brown ; border : 1px solid brown }", con = "mystyle.css")
dset1 <- head(ToothGrowth)
knitr::kable(dset1, format = "html")
```
This should:
Create a file named "mystyle.css" with your relevant CSS styling.
Produce something that looks something like the following.