Quantcast
Viewing all articles
Browse latest Browse all 22

How to use latex math in Rmd to display properly on GitHub Pages

Working on our PH525x online course material, Rafa and I wanted to base all lecture material in Rmd files, as these are easy for students to load into RStudio to walk through the code. Additionally, the rendered markdown files can be displayed nicely on GitHub Pages (which uses Jekyll to turn markdown in HTML). All we needed to do is copy the markdown files into the /pages directory and they already look pretty great when viewed on github.com (also we borrowed the theme from Karl Broman’s simple site template). By adding MathJax to the header of the GitHub Page template, we also render latex math formula from the original Rmd files.

Below I go over the issues we encountered with including math, but you can jump to the bottom if you just want our solution.

Redcarpet

While RStudio would render latex math in the HTML preview using MathJax, we would run into problems when rendering the markdown with the Redcarpet markdown parser. For example:

in RStudio:

Image may be NSFW.
Clik here to view.
rstudio1

using the Redcarpet markdown parser with Jekyll:

Image may be NSFW.
Clik here to view.
redc

What happened is that Redcarpet doesn’t recognize the `$` for the inline math, and it goes inside and sees the underscores, and adds italics to the text between them. I came up with some hacks for dealing with Redcarpet and latex math, but in the end, there was not a comprehensive solution to use Redcarpet with latex math.

Kramdown

We then tried out an alternate markdown parser called Kramdown. The Kramdown parser recognizes `$$` for inline or display math and won’t interpret symbols which are in between two `$$`. There are still some issues with trying to use `$` for inline math, for example:

in RStudio:

Image may be NSFW.
Clik here to view.
kram1

and the opposite effect using the Kramdown markdown parser with Jekyll:

Image may be NSFW.
Clik here to view.
kram2

But if we use `$$` for inline math, everything is fine in the rendered HTML from Jekyll.

The only remaining problem is that `$$` is recognized by RStudio as display math, so the helpful preview is no longer rendering nicely:

Image may be NSFW.
Clik here to view.
display



Our solution

We use the Kramdown parser with GitHub-flavored markdown to support the backtick fenced code blocks (see our config file):

markdown: kramdown

kramdown:
  input: GFM

We use `$` for display math in our Rmd files, and then we use a series of sed commands to convert `$` in the markdown files to `$$`. These md’s can be previewed locally with Jekyll and pushed to GitHub pages. It’s definitely a hack but it works.

Example Rmd

Example rendered HTML page




Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 22

Trending Articles