How to: A scenebreak in bookdown - r

I'm trying to write a novel using bookdown: HTML, EPUB, as well as PDF (pdfLaTeX). I'm using the indent mode, so paragraphs begin with an indent. I have the following custom LaTeX command, called \scenebreak, which:
Leaves an empty line between paragraphs when the scene changes within a chapter.
Introduces a ding, if the scene break is at the end of a page, or the beginning of a page.
Resets indent for the paragraph that follows the break (the paragraph that follows the break starts flush left).
Here's the LaTeX:
% scene breaks
\renewcommand{\pfbreakdisplay}{%
\scriptsize\ding{86}}
\newcommand{\scenebreak}{\pfbreak*\noindent}
\newcommand{\forceindent}{\leavevmode{\indent}}
When introducing the scenebreak in LaTeX, I call it so
Text here
\scenebreak
New scene begins here.
In HTML, this is how I've done it:
<div style='text-align:center;'>•</div>
I'm aware that a block in bookdown is like a LaTeX environment.
Is a similar setup possible with commands/macros?

I don't really understand your question, but if you are trying to write out different content depending on the different output format, here is what you could do:
```{r echo=FALSE}
knitr::asis_output(if (knitr:::is_latex_output()) {
"\\scenebreak"
} else {
"<div style='text-align:center;'>•</div>"
})
```
If you have to do this multiple times, create a function and call the function instead, e.g., insert this code chunk in the beginning of your book:
```{r, include=FALSE}
scenebreak = function() {
knitr::asis_output(if (knitr:::is_latex_output()) {
"\\scenebreak"
} else {
"<div style='text-align:center;'>•</div>"
})
}
```
Then use the function scenebreak() where a break is needed:
```{r echo=FALSE}
scenebreak()
```

Related

Highlight text inline. R-markdown with reference .docx

I need to be able to highlight all text in an r-markdown document that has been inserted using an inline code chunk. E.G r TEXT.
This is to enable editing of the automated Word document creation.
I have tried using
.highlight {
background-color: lightpink;
border: 3px solid red;
font-weight: bold;
}
r sprintf("<span class='highlight'>%s</span>",PNAME)
AND
r text_spec(TEXT, color = "red")
However, I suspect these are not working due to the reference .docx that I am using over-riding the styles.
Is there a way to still use the reference doc and have the highlighting??
Thanks in advance.
Silas
Using officedown::rdocx_document: default as the output type, we can use ftext and fp_text function from {officer} package to highlight text that were inserted using inline r code chunk.
---
title: "Inline code styling"
output:
officedown::rdocx_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(officer)
ft <- officer::fp_text(shading.color = "yellow")
word_spec <- function(x, prop = ft) ftext(text = toString(x) ,prop = ft)
```
## Inline code highlighting for word document
We can highlight text in an r-markdown document that has been inserted using an inline code for output type word document too.
- `r word_spec("text in inline code is highlighted")`
- The sum of 2 + 2 is `r word_spec(2 + 2)`
- The sequence from 1 to 10 is `r word_spec(1:10)`
And the rendered word document looks like this,

CSS selector for font color in flextable with shadow host on

I'm unsuccessfully trying to set the font color for flextable generated in r markdown using a css stylesheet.
I can accomplish this when I turn off shadow host, but not with it on. (Just turning it off removes other desirable features.) Here's a short r markdown file demonstrating the difference.
---
title: "Untitled"
output: html_document
---
<style>
div.flextable-shadow-host * {
color: pink;
}
div.tabwid * {
color: pink;
}
</style>
# ignores CSS above
```{r, echo=FALSE}
library(flextable)
flextable(head(mtcars))
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
I want the css external to the r code because I have a button selector on the website the user can change the overall style (e.g., dark mode or not).
When using shadow, the table is assembled outside of HTML. Only the id connects the table to HTML. However, flextable has functions for setting the color. Why not just use one of the many built-in methods to change the color?
For example:
# ignores CSS above
```{r liberator,include=F}
library(flextable)
library(tidyverse)
```
```{r tbler, echo=FALSE}
flextable(head(mtcars)) %>%
color(color = "pink", part = "all")
```
# accepts CSS above
```{r, echo=FALSE}
ft <- flextable(head(mtcars))
htmltools_value(ft, ft.shadow = FALSE)
```
There are many things you can do with flextable styling. You can see more customization options here.
Update: Based on your comments
Okay, this works to change the color of a flextable.
This works if there is only one flextable in the script.
I have the color of the text set to #b21E29 (a shade of red). You can change that as you see fit.
These will SKIP non-shadow flextables
Add this chunk anywhere in your RMD script. This requires no additional libraries or any other customization in your R code.
```{r js_ing,results="asis",engine="js",echo=F}
// extract the styles that are set for the flextable
letMe = document.querySelector('div.flextable-shadow-host').shadowRoot.querySelector('div>style');
// replace color style
// preceding ';' so that 'background-color' doesn't change
letMe.innerHTML = letMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
```
If you have more than one flextable with shadow on, you can use one of the two following chunks instead. In the first--all the same color; in the second--each table has a different color.
These work if there is more than one flextable in the script.
Pay attention to the comments so you can see what to use when depending on your desired output.
All the same color:
```{r moreJs_ing,results="asis",engine="js",echo=F}
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// to set all shadow flextables to the same font color:
for(i = 0, n = letMe.length; i < n; i++){
showMe = letMe[i].shadowRoot.querySelector('div>style');
showMe.innerHTML = showMe.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
}
```
Each with there own color:
```{r evenMoreJs_ing,results="asis",engine="js",echo=F}
//alternatively to set each to a different color
// make sure you only include one of these options!
// collect all of the flextables with shadow
letMe = document.querySelectorAll('div.flextable-shadow-host');
// first table in script
showFirst = letMe[0].shadowRoot.querySelector('div>style');
showFirst.innerHTML = showFirst.innerHTML.replace(/;(color:.+?);/g, ';color:#b21e29 !important;');
// second table in script
showSecond = letMe[1].shadowRoot.querySelector('div>style');
showSecond.innerHTML = showSecond.innerHTML.replace(/;(color:.+?);/g, ';color:#003b70 !important;');
// change the indices for each table, keep in mind the first table is [0], not [1]
```
If you aren't sure where you want to go with these, add all three and and include=F as a chunk option to the two you aren't using at that moment in time.

Define color of newthought() with Tufte style when rendering to pdf

I have no problem defining color of newthought() with Tufte style when rendering to HTML, as follows:
<font color = "blue">`r newthought('The Lab Supervisor')`</font> ...
However, it does not work out when rendering to pdf.
I learned to define color when rendering to both HTML and pdf by the following code:
em <- function(x, color) {
if (knitr::is_latex_output()) {
sprintf("\\textcolor{%s}{%s}", color, x)
} else if (knitr::is_html_output()) {
sprintf("<span style='color: %s;'>%s</span>", color,
x)
} else x
}
Then I apply in-line R expression as follows:
``` `r em("The Lab Supervisor", "blue")` ```
Is there any solution that I could combine both `r newthought()`and `r em()` so that The Lab Supervisor is set to small caps in blue when rendering to pdf?
I just worked it with your exact code. It worked in both pdf and HTML. You just combine the functions as you would in any other set of function calls.
(I used the tufte template.)
```{r func}
em <- function(x, color) {
if (knitr::is_latex_output()) {
sprintf("\\textcolor{%s}{%s}", color, x)
} else if (knitr::is_html_output()) {
sprintf("<span style='color: %s;'>%s</span>", color,
x)
} else x
}
```
r newthought(em('In his later books', "blue"))^[Beautiful Evidence], Tufte starts each section with a bit of vertical space, a non-indented paragraph, and sets the first few words of the sentence in small caps. To accomplish this using this style, call the newthought() function in tufte in an inline R expression `r ` as demonstrated at the beginning of this paragraph.^[Note you should not assume tufte has been attached to your R session. You should either library(tufte) in your R Markdown document before you call newthought(), or use tufte::newthought().]
The pdf:
The HTML:

Wrapping plots in another html container within an Rmd file

I have a situation where, for display purposes, I need to wrap an outputted plot in a <div> container.
At the most basic level, this is what I would like to do:
```{r fig.width=7, fig.height=6,results='asis',echo=FALSE}
cat('<div>')
plot(cars)
cat('</div>')
```
However, the output document looks like this:
![plot of chunk unnamed-chunk-2](figure/unnamed-chunk-2.png)
Is there a workaround if you need to "wrap" output?
The same behaviour only seems to occur when it's wrapping the plot. Otherwise, including closed tags works as expected:
```{r fig.width=7, fig.height=6,results='asis',echo=FALSE}
cat('<div>')
cat('</div>')
plot(cars)
cat('<h1>Hello</h1>')
```
Yet wrapping the image seems to break it. I'm also noticing that <img> is wrapped in <p> is it possible to stop this behaviour?
Here is one way to do it.
First, we create a chunk hook to wrap chunk output inside a tag.
We pass wrap = div as chunk option to wrap inside div.
Set out.extra = "" to fool knitr into outputting html for plot output. Note that this is required only for div tag and not for span, as markdown is parsed inside span tag.s
DONE!
Here is a gist with Rmd, md and html files, and here is the html preview
## knitr Chunk Hook to Wrap
```{r setup, echo = F}
knit_hooks$set(wrap = function(before, options, envir){
if (before){
paste0('<', options$wrap, '>')
} else {
paste0('</', options$wrap, '>')
}
})
```
```{r comment = NA, echo = F, wrap = 'div', out.extra=""}
plot(mtcars$mpg, mtcars$wt)
```

How to hide code in RMarkdown, with option to see it

I'm writing an RMarkdown document in which I'd like to re-run some chunks (5 to 9).
There's no need to display these chunks again, so I considered using
```{r echo=FALSE}
to make the rerun chunks invisible, as described in another stackoverflow question. This is fine, and outputs the desired results (improved fit of second iteration - see this solution implemented here).
In an ideal world, however, the code would be expandable so the user could see exactly what's going on if they want to for educational purposes and clarity (e.g. see link to Greasemonkey solution here) rather than hidden as in my second rpubs example. The solution may look something like this, but with a shorter surrounding box to avoid distraction:
for (i in 1:nrow(all.msim)){ # Loop creating aggregate values (to be repeated later)
USd.agg[i,] <- colSums(USd.cat * weights0[,i])
}
for (j in 1:nrow(all.msim)){
weights1[which(USd$age <= 30),j] <- all.msim[j,1] /USd.agg[j,1]
weights1[which(USd$age >= 31 & USd$age <= 50),j] <- all.msim[j,2] /USd.agg[j,2]
weights1[which(USd$age >= 51),j] <- all.msim[j,3] /USd.agg[j,3] ##
}
# Aggregate the results for each zone
for (i in 1:nrow(all.msim)){
USd.agg1[i,] <- colSums(USd.cat * weights0[,i] * weights1[,i])
}
# Test results
for (j in 1:nrow(all.msim)){
weights2[which(USd$sex == "m"),j] <- all.msim[j,4] /USd.agg1[j,4]
weights2[which(USd$sex == "f"),j] <- all.msim[j,5] /USd.agg1[j,5]
}
for (i in 1:nrow(all.msim)){
USd.agg2[i,] <- colSums(USd.cat * weights0[,i] * weights1[,i] * weights2[,i])
}
for (j in 1:nrow(all.msim)){
weights3[which(USd$mode == "bicycle"),j] <- all.msim[j,6] /USd.agg2[j,6]
weights3[which(USd$mode == "bus"),j] <- all.msim[j,7] /USd.agg2[j,7]
weights3[which(USd$mode == "car.d"),j] <- all.msim[j,8] /USd.agg2[j,8]
weights3[which(USd$mode == "car.p"),j] <- all.msim[j,9] /USd.agg2[j,9]
weights3[which(USd$mode == "walk"),j] <- all.msim[j,10] /USd.agg2[j,10]
}
weights4 <- weights0 * weights1 * weights2 * weights3
for (i in 1:nrow(all.msim)){
USd.agg3[i,] <- colSums(USd.cat * weights4[,i])
}
# Test results
plot(as.vector(as.matrix(all.msim)), as.vector(as.matrix(USd.agg3)),
xlab = "Constraints", ylab = "Model output")
abline(a=0, b=1)
cor(as.vector(as.matrix(all.msim)), as.vector(as.matrix(USd.agg3)))
#rowSums(USd.agg3[,1:3]) # The total population modelled for each zone, constraint 1
#rowSums(USd.agg3[,4:5])
#rowSums(USd.agg3[,6:10])
I'm happy with the echo=F solution, but would be even happier with an expandable code snippet one.
Edit: all RPubs examples except the first have now been removed, to avoid clogging their excellent publication system with essentially the same document.
This has been made much easier with the rmarkdown package, which did not exist three years ago. Basically you just turn on "code folding": https://bookdown.org/yihui/rmarkdown/html-document.html#code-folding. You no longer have to write any JavaScript.
E.g.
---
title: "Habits"
output:
html_document:
code_folding: hide
---
Also see https://bookdown.org/yihui/rmarkdown-cookbook/fold-show.html for more control over which code blocks to be fold or unfold.
If you add an html tag before your code you can use CSS selectors to do clever things to bits of the output - markdown handily passes the HTML through:
<style>
div.hidecode + pre {display: none}
</style>
<div class="hidecode"></div>
```{r}
summary(cars)
```
Here my CSS style rule matches the first <pre> tag after a <div class=hidecode> and sets it to be invisible. Markdown writes the R chunk with two <pre> tags - one for the R and one for the output, and this CSS catches the first one.
Now you know how to match the code and output blocks in CSS, you can do all sorts of clever things with them in Javascript. You could put something in the <div class=hidecode> tag and add a click event that toggles the visibility:
<style>
div.hidecode + pre {display: none}
</style>
<script>
doclick=function(e){
e.nextSibling.nextSibling.style.display="block";
}
</script>
<div class="hidecode" onclick="doclick(this);">[Show Code]</div>
```{r}
summary(cars)
```
The next step in complexity is to make the action toggle, but then you might as well use jQuery and get real funky. Or use this simple method. Let's do it with a button, but you also need a div to get your hooks into the R command PRE block, and the traversal gets a bit complicated:
<style>
div.hideme + pre {display: none}
</style>
<script>
doclick=function(e){
code = e.parentNode.nextSibling.nextSibling.nextSibling.nextSibling
if(code.style.display=="block"){
code.style.display='none';
e.textContent="Show Code"
}else{
code.style.display="block";
e.textContent="Hide Code"
}
}
</script>
<button class="hidecode" onclick="doclick(this);">Show Code</button>
<div class="hideme"></div>
```{r}
summary(cars)
```
( Note: I thought you could wrap R chunks in <div> tags:
<div class="dosomething">
```{r}
summary(cars)
```
</div>
but that fails - anyone know why?)

Resources