I'm using RBookdown with multiple chapters such as this minimal example.
In order to have color fonts in both html and pdf formats section 5.1.1 here provides the colorize function
colorize <- 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
}
This is great and I want to use it, but I don't know where to put it. If I put it inside the YAML header like so
---
title: "A Minimal Book Example"
author: "Yihui Xie"
date: "`r Sys.Date()`"
site: bookdown::bookdown_site
output: bookdown::gitbook
documentclass: book
bibliography: [book.bib, packages.bib]
biblio-style: apalike
link-citations: yes
github-repo: rstudio/bookdown-demo
description: "This is a minimal example of using the bookdown package to write a book. The output format for this example is bookdown::gitbook."
```{r}
colorize <- 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
}
```
---
this is clearly the wrong path because of error message
Error in yaml::yaml.load(..., eval.expr = TRUE) :
Scanner error: while scanning for the next token
However, if I try to put the colorize function within the body of an Rmd file such as
# Prerequisites
```{r}
colorize <- 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
}
```
This is a _sample_ book written in **Markdown** with `r colorize("desired red text", "red")`.
this appears somewhat more promising as (1) it does compile and (2) the desired text is red. However, the colorize function actually appears in the book (since it's in the body of the markdown) and the colorize function only works within the same chapter in which it is placed.
Obviously the goal is to have the colorize function work while not actually appearing in the rendered book, and we also want the color to work across all chapters.
Here is my current solution.
Create a file called _myfunctions.R which contains the colorize function (no tick marks, just the R code below). Put this file in the same directory as the chapter files.
colorize <- 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
}
Now, in every chapter .Rmd file, put the following code so that your functions are sourced into the chapter.
```{r echo=FALSE}
source('_myfunctions.R')
```