Become an expert in R — Interactive courses, Cheat Sheets, certificates and more!
Get Started for Free

protect_math

Protect math expressions in pairs of backticks in Markdown


Description

For Markdown renderers that do not support LaTeX math, we need to protect math expressions as verbatim code (in a pair of backticks), because some characters in the math expressions may be interpreted as Markdown syntax (e.g., a pair of underscores may make text italic). This function detects math expressions in Markdown (by heuristics), and wrap them in backticks.

Usage

protect_math(x)

Arguments

x

A character vector of text in Markdown.

Details

Expressions in pairs of dollar signs or double dollar signs are treated as math, if there are no spaces after the starting dollar sign, or before the ending dollar sign. There should be spaces before the starting dollar sign, unless the math expression starts from the very beginning of a line. For a pair of single dollar signs, the ending dollar sign should not be followed by a number. With these assumptions, there should not be too many false positives when detecing math expressions.

Besides, LaTeX environments (\begin{*} and \end{*}) are also protected in backticks.

Value

A character vector with math expressions in backticks.

Note

If you are using Pandoc or the rmarkdown package, there is no need to use this function, because Pandoc's Markdown can recognize math expressions.

Examples

library(xfun)
protect_math(c("hi $a+b$", "hello $$\\alpha$$", "no math here: $x is $10 dollars"))
protect_math(c("hi $$", "\\begin{equation}", "x + y = z", "\\end{equation}"))

xfun

Miscellaneous Functions to Support Packages Maintained by 'Yihui Xie'

v0.22
MIT + file LICENSE
Authors
Yihui Xie [aut, cre, cph] (<https://orcid.org/0000-0003-0645-5666>), Wush Wu [ctb], Daijiang Li [ctb], Xianying Tan [ctb], Salim Brüggemann [ctb] (<https://orcid.org/0000-0002-5329-5987>), Christophe Dervieux [ctb]
Initial release

We don't support your browser anymore

Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.