Skip to Content

Command-line program to update R Markdown code to use `$latex` delimter

UPDATE (13th June 2012): RStudio now supports a range of mathjax delimtiers including single dollar signs and double dollar signs without latex.

In 0.96 RStudio changed its Mathjax syntax from $<equation>$ to $latex <equation>$ for inline equations and from $$<equation>$$ to $$latex <equation>$$ for displayed equations.

Thus, in summary:

The revised syntax adds a latex qualifier to the $ or $$ equation begin delimiter.

I have some existing scripts that use the original $ delimiter and I would like to update them to use the new $latex delimiter.
I was thinking that sed or awk might be suitable.

Also dollars that appear in r code blocks like this should not be altered.

```{r ...}
x <- Data$asdf
```

Question

  • What would be a good simple command-line program perhaps using sed or awk to update my R Markdown code to use the newer mathjax delimiter in R Studio?

Working example 1

Original text:

$y = a + b x$ is the formula.
This is some text, and here is a displayed formula
$$y = a+ bx\\
x = 23$$
 
```{r random_block}
y <- Data$asdf
```
 
and some more text     
$$y = a+ bx\\
x = 23$$

after transformation becomes

$latex y = a + b x$ is the formula.
This is some text, and here is a displayed formula
$$latex y = a+ bx\\
x = 23$$
 
```{r random_block}
y <- Data$asdf
```
 
and some more text     
$$latex y = a+ bx\\
x = 23$$

Working example 2

`r opts_chunk$set(cache=TRUE)`
<!-- some comment -->
 
Some text
 
<!-- more -->
Observed data are $y_i$ where $i=1, \ldots, I$.  
$$y_i \sim N(\mu, \sigma^2)$$
 
Some text $\sigma^2$ blah blah $\tau$. 
 
$$\tau = \frac{1}{\sigma^2}$$
 
blah blah $\mu$ and $\tau$
 
$$\mu \sim N(0, 0.001)$$
$$\tau \sim \Gamma(0.001, 0.001)$$

should become

`r opts_chunk$set(cache=TRUE)`
<!-- some comment -->
 
Some text
 
<!-- more -->
Observed data are $latex y_i$ where $latex i=1, \ldots, I$.  
$$latex y_i \sim N(\mu, \sigma^2)$$
 
Some text $latex \sigma^2$ blah blah $latex \tau$. 
 
$$latex \tau = \frac{1}{\sigma^2}$$
 
blah blah $latex \mu$ and $latex \tau$
 
$$latex \mu \sim N(0, 0.001)$$
$$latex \tau \sim \Gamma(0.001, 0.001)$$