Chemical formulas in Markdown with KaTeX mhchem: \ce and \pu
Write chemical formulas and reactions in Markdown with $\ce{...}$ for inline text and $$\ce{...}$$ for display equations, using KaTeX's mhchem extension. Plain math mode such as $H_2SO_4$ sets element letters in math italics and requires manual underscores and braces on every subscript and ion charge. \ce switches to upright Roman element symbols automatically, formats stoichiometry coefficients, charges, and reaction arrows from plain ASCII input, and pairs with \pu{...} for physical units.
Why plain LaTeX math gets chemistry wrong
Under the IUPAC Green Book (Quantities, Units and Symbols in Physical Chemistry) and ISO 80000, italic and upright letters carry distinct meanings. Physical quantities sit in italic type ($H$ for enthalpy, $V$ for volume, $T$ for temperature), whereas chemical element symbols sit in upright Roman type ($\mathrm{H}$ for hydrogen, $\mathrm{V}$ for vanadium, $\mathrm{C}$ for carbon).
Typing $H_2SO_4$ in ordinary TeX math slants every atom like an algebraic product, and a single redox equation turns into a thicket of \mathrm, braces, and manual spacing:
Plain math:
$$2\,\mathrm{MnO_4^-} + 5\,\mathrm{H_2O_2} + 6\,\mathrm{H^+} \longrightarrow 2\,\mathrm{Mn^{2+}} + 5\,\mathrm{O_2}\uparrow + 8\,\mathrm{H_2O}$$
With mhchem:
$$\ce{2MnO4- + 5H2O2 + 6H+ -> 2Mn^2+ + 5O2 ^ + 8H2O}$$
The \ce form stays readable in plain Markdown and compiles to the same upright symbols, staggered subscripts, charges, and gas arrow.
Formulas, ions, hydrates, and isotopes with \ce
Inside \ce{...}, position decides whether a number is a coefficient or a subscript. Numbers at the start of a species (2H2O, 1/2 O2) become stoichiometric coefficients followed by a thin space; digits right after an element or closing parenthesis (H2SO4, Al2(SO4)3) drop into subscripts without _.
| Notation | Write inside $...$ |
Output |
|---|---|---|
| Fraction coefficient | \ce{1/2 O2} |
Stacked fraction before upright $\mathrm{O_2}$ |
| Simple ions | \ce{Na+}, \ce{Cl-} |
Upright symbol with + or minus charge |
| Multi-valent ion | \ce{Fe^3+}, \ce{Cr2O7^2-} |
^ separates subscript digits from charge |
| Coordination complex | \ce{[Ag(NH3)2]+} |
Brackets preserved with outer + |
| Crystal hydrate | \ce{CuSO4.5H2O} |
. or * draws a centered dot |
| Isotope prescripts | \ce{^{14}_6C}, \ce{^{235}U} |
Right-aligned mass and atomic numbers |
| Covalent bonds | \ce{CH3-CH=CH-C#CH} |
- single, = double, # triple bond |
Keep the caret in \ce{SO4^2-} and \ce{Fe^3+}. Without ^ after SO4, 4 and 2 collide; \ce{SO4^2-} keeps 4 as the subscript and 2- as the charge. For weak or delocalized interactions, \bond{~} draws a triple-dash resonance bond and \bond{...} draws a three-dot hydrogen bond.
Reaction arrows, conditions, states, and precipitates
mhchem turns ASCII arrow sequences into stretchy reaction arrows, provided you leave a space on both sides of the arrow. Without spaces, a hyphen after an atom is read as a covalent bond or minus charge rather than the start of ->.
$$
\ce{N2 (g) + 3H2 (g) <=>[\text{Fe catalyst}][\pu{450 °C}, \pu{20 MPa}] 2NH3 (g)}
$$
$$
\ce{Ag+ (aq) + Cl- (aq) -> AgCl (s) v}
\qquad
\ce{2KClO3 (s) ->[\ce{MnO2}][\Delta] 2KCl (s) + 3O2 ^}
$$
| Arrow or marker | Syntax | Meaning |
|---|---|---|
| Forward reaction | -> |
Yields |
| Reverse reaction | <- |
Leftward reaction arrow |
| Resonance | <-> |
Double-headed single arrow |
| Equilibrium | <=> |
Reversible harpoons |
| Shifted equilibrium | <=>> or <<=> |
Longer upper or lower harpoon |
| Labels above and below | ->[above][below] |
Stretches arrow to fit reagents, \Delta, or \text{...} |
| Gas evolution | ^ or (^) |
Upward arrow (\uparrow), preceded by a space |
| Precipitate | v or (v) |
Downward arrow (\downarrow), preceded by a space |
Two spacing rules prevent ninety percent of reaction typos:
- Put a space before
vand^. Writing\ce{BaSO4v}attaches an italic or uprightvto the formula;\ce{BaSO4 v}or\ce{BaSO4 (v)}outputs $\mathrm{BaSO_4}\downarrow$. Likewise, leave a space before state labels such as(s),(l),(g), and(aq)when you want a small typographic gap before the parentheses. - Watch mode inside arrow brackets. Inside
->[...][...],mhchemstays in chemistry mode by default, so[H2SO4]or[\ce{MnO2}]renders upright formulas and[\Delta]draws the heat triangle. Wrap English or Chinese words such as[\text{heat}][\text{cat.}]in\text{...}somhchemdoes not parse word letters as element symbols or oxidation numerals.
Physical units and scientific notation with \pu
mhchem ships a second macro, \pu{...} (physical units), which applies SI spacing and upright unit symbols without manual \mathrm or \, commands.
Standard enthalpy of formation: $\Delta_{\mathrm{f}} H^\circ = \pu{-285.8 kJ/mol}$ at $\pu{25 °C}$ ($\pu{298.15 K}$).
Molar heat capacity: $\pu{75.3 J // mol K}$, activation energy: $\pu{1.23e4 J*mol^-1}$.
\pu turns 1.23e4 or 1.23*10^4 into $1.23 \times 10^4$, inserts a non-breaking thin space between the number and unit, formats J*mol^-1 with a centered dot between compound units, converts a single / into an inline slash (\pu{J/mol}), and converts // into a stacked fraction (\pu{J // mol K}). Both literal °C and ^oC render a degree circle next to an upright C.
How MiaoYan renders mhchem offline and where tools differ
Since V4.12.0, MiaoYan bundles KaTeX 0.16.47 together with mhchem.min.js inside the app on Mac, iPhone, and iPad, covering both the note preview (⌘3 or ⌘\ split view) and presentation slides (⌥⌘P). No CDN request is made when opening a chemistry note offline.
Under the hood, three details in MiaoYan's pipeline keep chemical notation from breaking:
- Pre-parser math shielding. Before
cmark-gfmparses Markdown,protectMarkdownMathshields$...$,$$...$$,\(...\), and\[...\]outside code spans and fences. Without that shield, underscores in\ce{^{14}_6C}or asterisks in\pu{1.2*10^4 J}can be consumed as Markdown italics before KaTeX runs. See LaTeX math in Markdown for delimiter pairing rules. - Brace-aware currency guard. MiaoYan ignores prose prices like
$5while tracking nested{...}braces inside inline math, so numbers and symbols inside complex$\ce{...}$expressions are never split early. - Error isolation (
guardKaTeXRender). Upstreammhchemthrows plain JavaScript arrays such as["ExtraCloseMissingOpen", ...]on a stray closing brace rather thankatex.ParseError. Uncaught, that stops KaTeX'sauto-renderloop and leaves every later formula in the note unrendered. MiaoYan converts those array throws intokatex.ParseError, so one unfinished\ce{...}shows its raw source while every other equation on the page still renders.
When notes leave MiaoYan, check what the target loads:
- GitHub.com renders
$...$and$$...$$via MathJax withmhchemenabled, so\ce{...}works in READMEs and issues. Wrap inline formulas with underscores in$`\ce{...}`$or$$blocks so GFM emphasis leaves them alone. - Browser tools without
mhchem. Core KaTeX omits\ceunlessmhchem.min.jsis loaded alongside it. MiaoYan's apps and its web Markdown viewer, Markdown to Word and Markdown slides tools loadmhchem.min.js, whereas third-party viewers that load barekatex.min.jsneed$\mathrm{H_2SO_4}$instead. - Targets without math. Email and RSS strip scripts; fall back to
H<sub>2</sub>SO<sub>4</sub>andSO<sub>4</sub><sup>2-</sup>, covered in Markdown superscript and subscript.
MiaoYan is on the App Store for Mac, iPhone, and iPad, with the Mac source on GitHub.
FAQ
Why does KaTeX say Undefined control sequence: \ce in some editors?
\ce and \pu live in mhchem.min.js rather than katex.min.js core. MiaoYan V4.12.0+ bundles both; elsewhere, load mhchem.min.js or write $\mathrm{H_2SO_4}$.
Why did \ce{Fe2+} turn 2 into a subscript instead of a 2+ charge?
Digits right after an element count as subscripts first (Fe2+ means $\mathrm{Fe_2^+}$). Write \ce{Fe^2+} with a caret whenever a charge has a number.
How do I write reaction conditions in plain words?
Wrap words in \text{...} inside arrow brackets, such as $$\ce{A + B <=>[\text{heat}][\text{cat.}] C}$$, so letters are not parsed as elements.
Can I align several chemical equations at their arrows?
Yes. Place & before each arrow inside aligned, for example $$\begin{aligned} \ce{C + O2 &-> CO2} \\ \ce{2CO + O2 &-> 2CO2} \end{aligned}$$.
