Search code examples
htmlr-markdownknitrmathjax

How to configure R Markdown to use the "textmacros" MathJax extension for HTML rendering?


I'd like to configure my R Markdown document to use the textmacros MathJax extension for HTML rendering (knitting) in RStudio. I was unsuccessful in trying to apply the instructions provided at https://docs.mathjax.org/en/latest/input/tex/extensions/textmacros.html in a include: in_header: file specified in my YAML header (see the example below).

I'm using RStudio 2022.12.0 Build 353 (version available in my workplace).

Context
My goal is to get similar rendering with LaTeX text commands (e.g., \text{} or \texttt{}) whether I Knit to PDF or Knit to HTML with MathJax. E.g., while $\texttt{my\_var}$ renders to my_var in PDF, it renders to my\_var in HTML with MathJax by default. Using the textmacros extension would (supposedly) render it to my_var in HTML as well.

Note: HTML rendering with webtex works fine in this case, but I'd like to have the option to use mathjax as well.

Example

R Markdown document:

---
title: "My Doc"
output:
  html_document:
    #math_method: webtex
    math_method: mathjax
    includes:
      in_header: header.html
  pdf_document:
    latex_engine: pdflatex
---

Test formula: $\texttt{my\_var} * 2 + 1$

header.html file (source: https://docs.mathjax.org/en/latest/input/tex/extensions/textmacros.html):

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({ 
    loader: {load: ['[tex]/textmacros']},
    tex: {packages: {'[+]': ['textmacros']}}
  });
</script>

The following solution (without the textmacros extension) would work but it is less than ideal to say the least...

---
title: "My Doc"
output:
  html_document:
    math_method: mathjax
  pdf_document:
    latex_engine: pdflatex
---

```{asis, echo=knitr::is_html_output()}
Test formula: $\texttt{my_var} * 2 + 1$
```
```{asis, echo=(knitr::is_html_output() == FALSE)}
Test formula: $\texttt{my\_var} * 2 + 1$
```

Thanks for your help.


Solution

  • I believe the answer to question Mathjax \text{} with greek letters inside applies to my issue as well. My version of RStudio (2022.12.0 Build 353) uses MathJax 2.7.2 while the textmacros extension was introduced in MathJax 3.