Bookdown - Reference tag from another math environment broken - r-markdown

It seems i can't reference equations, lemas, etc when inside math.
In the following example the tag eq:test cant be referenced inside the align, but it works fine outside.
---
title: "Test"
site: bookdown::bookdown_site
documentclass: article
---
If
\begin{equation}
A = B
(\#eq:test)
\end{equation}
then
\begin{align*}
A \ &= B &&, \text{ by } \#ref(eq:test) \\ % this will not work
&= C
\end{align*}
But here \#ref(eq:test) it works.
I want to know if this is currently not possible or i'm missing some special notation to make it work.

Try with latex command \label{} and \eqref{}.
\label, \eqref works smoothly for pdf output as expected. For html output, we need to configure the Tex component of mathjax through the tex block as instructed here.
---
title: "Test"
output:
bookdown::pdf_document2:
documentclass: article
bookdown::html_document2: default
---
```{=html}
<script>
MathJax = {
tex: {
tags: 'all'
}
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-chtml.js"></script>
```
If
\begin{equation}
A = B \label{test-eq1}
\end{equation}
then
\begin{align*}
A \ &= B &&, \text{ by } \eqref{test-eq1} \\
&= C
\end{align*}
But here \eqref{test-eq1} it works.
pdf output
html output

Related

Change default behavior of callout blocks in Quarto

In Quarto, I'd like to change the default behavior of a single callout block type so that it will
always automatically have the same caption (e.g. "Additional Resources")
always be folded (collapse="true")
Let's say I want this for the tip callout block type while the others (note, warning, caution, and important) should not be affected.
In other words, I want the behavior/output of this:
:::{.callout-tip collapse="true"}
## Additional Resources
- Resource 1
- Resource 2
:::
by only having to write this:
:::{.callout-tip}
- Resource 1
- Resource 2
:::
Update:
I have actually converted the following lua filter into a quarto filter extension collapse-callout, which allows specifying default options for specific callout blocks more easily. See the github readme for detailed instructions on installation and usage.
As #stefan mentioned, you can use pandoc Lua filter to do this more neatly.
quarto_doc.qmd
---
title: "Callout Tip"
format: html
filters:
- custom-callout.lua
---
## Resources
:::{.custom-callout-tip}
- Resource 1
- Resource 2
:::
## More Resources
:::{.custom-callout-tip}
- Resource 3
- Resource 4
:::
custom-callout.lua
local h2 = pandoc.Header(2, "Additional Resources")
function Div(el)
if quarto.doc.isFormat("html") then
if el.classes:includes('custom-callout-tip') then
local content = el.content
table.insert(content, 1, h2)
return pandoc.Div(
content,
{class="callout-tip", collapse='true'}
)
end
end
end
Just make sure that quarto_doc.qmd and custom-callout.lua files are in the same directory (i.e. folder).
After a look at the docs and based on my experience with customizing Rmarkdown I would guess that this requires to create a custom template and/or the use of pandoc Lua filters.
A more lightweight approach I used in the past would be to use a small custom function to add the code for your custom callout block to your Rmd or Qmd. One drawback is that this requires a code chunk. However, to make your life a bit easier you could e.g. create a RStudio snippet to add a code chunk template to your document.
---
title: "Custom Callout"
format: html
---
```{r}
my_call_out <- function(...) {
cat(":::{.callout-tip collapse='true'}\n")
cat("## Additional Resources\n")
cat(paste0("- ", ..., collapse = "\n\n"))
cat("\n:::\n")
}
```
```{r results="asis"}
my_call_out(paste("Resource", 1:2))
```
Blah blah
```{r results="asis"}
my_call_out("Resource 3", "Resource 4")
```
Blah blah

Difference in PDFs when manually generated with Knit-Button vs rmarkdown::render() - e.g. section numbers not always included

I try to generate multiple reports (1 per group) with rmarkdown::render(), but it produces no section numbers.
I use the following file-structure for this in case you want to reproduce the sample (I tried to simplify each file and use only necessary code to reproduce the error):
*) groups.R: defines groups and subgroups in a nested list (all groups stored in a list and each group is a list itself)
groups <- list(
list(c("subgroup1","subgroup2"),"maingroup1"),
list(c("subgroup3","subgroup4"),"maingroup2")
)
*) main.Rmd: template for the reports
---
output:
pdf_document:
number_sections: true
classoption: a4paper
geometry: left=2cm,right=1cm,top=1.5cm,bottom=1cm,includeheadfoot
fontfamily: helvet
fontsize: 11pt
lang: en
header-includes:
- \usepackage{lastpage}
- \usepackage{fancyhdr}
- \pagestyle{fancy}
- \fancyhf{}
- \fancyhead[R]{\fontsize{9}{11} \selectfont \leftmark}
- \fancyhead[L]{\fontsize{9}{11} \selectfont Special report xxx}
- \fancyfoot[R]{\fontsize{9}{0} \selectfont Page \thepage\ of
\pageref{LastPage}}
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(echo =
FALSE,comment=NA,warning=FALSE,message=FALSE)
```
\thispagestyle{empty}
\tableofcontents
\newpage
\setcounter{page}{1}
# Introduction
Some text...
```{r results="asis"}
source("graphics.R")
```
*) graphics.R: generates graphics for each subgroup (sections/section numbers are produced with cat() for each subgroup)
load("actgroup.RData")
source("template_graphics.R")
for (g in 1:length(act.group[[1]][[1]])) {
subgroup.name <- act.group[[1]][[1]][g]
cat("\\clearpage")
cat("\n# ",subgroup.name, "\n")
template_graphics(cars)
cat("\n\n")
cat("\\clearpage")
template_graphics(iris)
cat("\n\n")
cat("\\clearpage")
template_graphics(airquality)
cat("\n\n")
cat("\\clearpage")
cat("\n")
}
*) template_graphics.R: template for plotting
template_graphics <- function(data) {
plot(data)
}
*) loop.R: used for generating all reports as PDF - 1 per group
setwd("YOUR DIRECTORY HERE")
library(rmarkdown)
source("groups.R")
for(i in 1:length(groups)) {
act.group = list(groups[[i]])
save(act.group,file="actgroup.RData")
rmarkdown::render("main.Rmd",
output_format=pdf_document(),
output_file=paste0("Special Report ",act.group[[1]][[2]],".pdf"),
output_dir="~/Reports")
}
The problem is, that the final documents do not show the section numbers. When I knit manually in main.Rmd (pressing knit-Button), the section numbers are printed.
Version rmarkdown::render
Version knit-Button
I thought that pressing the knit-Button also starts the rendering-process with rmarkdown::render()? So it's surprising that the reports are not identical?
In advance I installed tinytex::install_tinytex(). The used latex-packages in main.Rmd were automatically installed during the first time rendering.
I am not sure what the problem is. I use R 4.1.0 and RStudio 2022.02.2.
Thanks for your help!!
The behaviour of pdf_document() as the output-format in rmarkdown::render caused the missing section-numbers.
In my YAML-header in main.Rmd I chose to keep the section numbers with number_sections: true. If this should also be rendered when using rmarkdown::render, it has to be an argument in the function:
pdf_document(number_sections=TRUE)
The code of loop.R produces now pdfs with section numbers:
library(rmarkdown)
source("groups.R")
for(i in 1:length(groups)) {
act.group = list(groups[[i]])
save(act.group,file="actgroup.RData")
rmarkdown::render("main.Rmd",
output_format=pdf_document(number_sections=TRUE),
output_file=paste0("Special Report ",act.group[[1]][[2]],".pdf"),
output_dir="~/Reports")
}
More information on pdf_document() can be found here:
https://pkgs.rstudio.com/rmarkdown/reference/pdf_document.html
Alternatively, fill in just a text-reference as output-format: output_format="pdf_document". When set like this, the options of the YAML-Header are not overwritten and the numbers are also included.

Rmd change docx template depending on params value

I think that you can pass variables to a YAML element, something like
---
output: html_document
params:
set_title: "My Title!"
title: "`r params$set_title`"
---
(as suggested here). This, however, works for output: html_document but not for bookdown::word_document2. Also, I would like to change the template of my bookdown::word_document2 output, depending on a switch, which I can set in the YAML itself, something like
---
title: ""
params:
include_signature: false
include_footer: true
file: !r if(params$include_footer){system.file("assets/template_footer.docx")}else{system.file("assets/template.docx")}
output:
bookdown::word_document2:
reference_docx: "`r params$file`"
number_sections: false
---
This, however, fails with the error message
Error in yaml::yaml.load(..., eval.expr = TRUE) :
Parser error: while parsing a block mapping at line 8, column 5 did not find expected key at line 8, column 61
Calls: <Anonymous> ... parse_yaml_front_matter -> yaml_load -> <Anonymous>
In addition: Warning message:
In yaml::yaml.load(yaml, handlers = knit_params_handlers(evaluate = evaluate), :
an error occurred when handling type 'r'; using default handler
Execution halted
I have tried other possible versions, eg
params:
include_footer: true
output:
bookdown::word_document2:
reference_docx: !expr ifelse(params$include_footer,system.file("assets/template_footer.docx"),system.file("assets/template.docx"))
(or even other variations, where !expr is replaced by r or !r but nothing seems to have made a difference.
Am I missing something obvious (eg that this is only possible in html_document output), or is this particular trick impossible?
Thanks
Gianluca

RMarkdown not rendering Stan code chunk as code

When I knit the following RMarkdown document:
title: "Reprex"
author: "Jeremy Colman"
date: "17/07/2018"
output:
html_document: default
pdf_document: default
word_document: default
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{stan, output.var='priors', eval = FALSE, tidy = FALSE}
parameters {
real<lower = 0> qtilde1;
}
model {
qtilde1 ~ gamma(38.9, 0.67);
}
```
The Stan code chunk is rendered as ordinary text, including the three reverse single quotes and word stan from the chunk header. I cannot show that in this post because stackoverflow tells me, correctly but unhelpfully, "Your post appears to contain code that is not properly formatted as code". That sums up my problem!
Code chunks in R are rendered correctly.
Your
```{stan output.var='priors', eval = FALSE, tidy = FALSE}
needs to be flush-left, but you have a leading space before the ```

How can I render markdown to html with Blackfriday in Go?

I have a struct like this:
type Page struct {
Content string
}
then I read a markdown file and assign to a variable:
data, err := ioutil.ReadFile("a.md")
lines = string(data)
page.Content = markdownRender([]byte(lines))
The markdown file is like this:
##Hello World
###Holo Go
and then I put it into markdown render function and return a string value:
func markdownRender(content []byte) string {
htmlFlags := 0
htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
renderer := blackfriday.HtmlRenderer(htmlFlags, "", "")
extensions := 0
extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
extensions |= blackfriday.EXTENSION_TABLES
extensions |= blackfriday.EXTENSION_FENCED_CODE
extensions |= blackfriday.EXTENSION_AUTOLINK
extensions |= blackfriday.EXTENSION_STRIKETHROUGH
extensions |= blackfriday.EXTENSION_SPACE_HEADERS
return string(blackfriday.Markdown(content, renderer, extensions))
}
and finally I call the page.Content in a html template and generate a static html:
{{.Content}}
but in the generated html it shows in the browser (I tried it in the chrome and safari) is like this (not the source code, it just shows in the page):
<p>##Hello World ###Holo Go </p>
but I want it like this
Hello World
Holo Go
So, how can I do this?
First, your markdown input is not quite right -- headings should have whitespace separating the #s from the text. You can verify this using blackfriday-tool:
$ echo ##Hello | blackfriday-tool
<p>##Hello</p>
$ echo ## Hello | blackfriday-tool
<h2>Hello</h2>
Second, if you feed the HTML output from blackfriday into a html/template, it is going to be automatically escaped for safety.
If you trust the markdown input and blackfriday's HTML output, then you can tell the template system to trust the content by wrapping it in a html/template HTML value:
type Page struct {
Content template.HTML
}
err = t.ExecuteTemplate(w, "page", Page{Content: template.HTML(s)})
See http://play.golang.org/p/eO7KDJMlb8 for an example.