My R Markdown (.Rmd) file looks like this:
---
title: Foo
author: Marius Hofert
header-includes:
- \\usepackage{bm}
output:
pdf_document
vignette: >
I don't think Mathjax (which is what Pandoc uses in HTML output) can \usepackage{}
. I work around this by having 2 files: one called preamble-mathjax.tex
, one called preamble-latex.tex
My YAML metadata is set up like this (for rmarkdown
):
output:
html_document:
includes:
before_body: preamble-mathjax.tex
pdf_document:
includes:
in_header: preamble-latex.tex
And preamble-mathjax.tex
has (note surrounding \( \)
so that mathjax parses as a maths block)
\(
\newcommand{\bm}[1]{\boldsymbol{\mathbf{#1}}}
\)
while preamble-latex.tex
has:
\usepackage{bm}
So that whenever I use \bm{..}
in my document, it works whether I compile to HTML or PDF. (stacking the boldsymbol
with the mathbf
so that both greek letters and normal letters are made bold, and bold letters remain upright as they would if you used \bm
).
Peripheral to your question:
Eventually you may wish to have a third file, preamble-both.tex
, with macros that are not package-specific (supposing the relevant preamble-*
has already been included) e.g.
\newcommand{\bX}{\bm{X}} % bold X
\newcommand{\R}{\mathbb{R}} % real numbers
And then you include this with both output formats. This saves you from writing all your macros twice, once for html_document and again for pdf_document. However, MathJax requires the macros to be surrounded by \(
and \)
, whereas LaTeX will error out if this is the case.
The only way I've found to work around this is to have a file bracket-start.txt
containing just \(
and a file bracket-end.txt
containing just \)
, so that my YAML is:
output:
html_document:
includes:
before_body: [preamble-mathjax.tex, bracket-start.txt, preamble-both.tex, bracket-end.txt]
pdf_document:
includes:
in_header: preamble-latex.tex
before_body: preamble-both.tex
which is pretty unwieldy, but it works (there is the Pandoc latex_macros extension, but it has never worked for me)