Mathpix-markdown-it is an open source implementation of the mathpix-markdown spec written in Typescript. It relies on the following open source libraries: MathJax v3 (to render math with SVGs), markdown-it (for standard Markdown parsing)
npm install mathpix-markdown-it


mathpix-markdown is a superset of Markdown that adds helpful syntax for the STEM community, such as advanced equation, table, and chemistry support. Wherever possible, we borrow syntax from LaTeX. In other cases (such as chemistry) we invent new syntax that is backward compatible with Markdown.
Here are the key benefits over plain Markdown:
- better equation support via LaTeX syntax (powered by MathJax), including equation numbering and referencing conventions from LaTeX
- better support for tables, via the LaTeX tabular syntax, which allows for complex, nested tables often seen in scientific publications
- advanced figure referencing via LaTeX syntax
- support for abstracts, author lists, and linkable sections; these are a fact of life for academic publications
- support for chemistry diagrams represented with SMILES markup, compatible with popular chemistry tools like ChemDraw
!Editing an MMD file in VS Code
Click here for the full syntax reference.
Mathpix Markdown is an open format with multiple implementations:
- you can use this Github repo and the mathpix-markdown-it npm library to render STEM content on your website
- you can use the VS Code plugin (see picture above) to edit mmd files
- use can use our web editor Snip Notes to edit, export, and publish mmd files (with exports to pdf and docx formats)
- you can use our experimental static site generator Spectra to edit local mmd files and see changes in real time
Mathpix Markdown addresses these limitations by adding support for the following standard Latex syntax elements which are already familiar to the scientific community:
- inline math via \(
- block math via \[ or $$
- tables via \begin{tabular} ... \end{tabular}
- figures and figure captions via \begin{figure} \caption{...} ... \end{figure}
- lists: unordered lists via \begin{itemize} ... \end{itemize} and ordered lists via \begin{enumerate} ... \end{enumerate}
- numbered and unnumbered equation enviornments \begin{elem} ... \end{elem} and \begin{elem} ... \end{elem} where elem=equation|align|split|gather
- equation, table, and figure references via \label, \ref, \eqref, \tag
- text formatting options \title{...}, \author{...}, \begin{abstract}...\end{abstract}, \section{Section Title}, \subsection{Section Title}, \subsubsection{Section Title}, \textit{italicized text}, \textbf{bold text}, \url{link}
- chemistry equation via or
~~~
``smiles`
OC(=O)c1cc(Cl)cs1
~~~
- images (Markdown). Parse and render additional parameters such as width, height, alignment:
~~~
!foo{ width=50% }
!foo{ width="36px" }
!image{width="20px",height="20px"}
!image{width="20px",height="20px",right}
!image{width="20px",height="20px", align="left"}
~~~
!Image properties
`tex
\newtheorem{theorem}{Theorem}
\newtheorem{lemma}[theorem]{Lemma}
\begin{theorem}
Let \(f\) be a function whose derivative exists in every point, then \(f\)
is a continuous function.
\end{theorem}
\begin{lemma}
Given two line segments whose lengths are \(a\) and \(b\) respectively there
is a real number \(r\) such that \(b=ra\).
\end{lemma}
\begin{proof}
To prove it by contradiction try and assume that the statement is false,
proceed from there and at some point you will arrive to a contradiction.
\end{proof}
`

`tex
Footnote marker without text. Auto increment counter to 1 \footnotemark{} should be 1.
Footnote marker with text. Auto increment counter to 2 \footnotemark{} be 2. \footnotetext{text should be 2}
Auto increment counter to 3 \footnote{text should be 3}
Auto increment counter to 4 \footnote{text should be 4}
Footnote marker without text. Auto increment counter to 5 \footnotemark{} should be 5.
Footnote marker with text. Auto increment counter to 6 \footnotemark{} should be 6. \footnotetext{text should be 6}
Auto increment counter to 7 \footnote{text should be 7}
Auto increment counter to 8 \footnote{text should be 8}
`

`tex
Underline text: \underline{Underlined text!}
Underline text: \uline{Underlined text!}
Double underline text: \underline{\underline{Double underlined text!}}
Double underline text: \uuline{Double underlined text!}
Wavy underlined text: \uwave{This text is underlined with a wavy line!}
Dashed underline text: \dashuline{Dashed Underline}
Dotted underline text: \dotuline{Dotted Underline}
Strikethrough text: \sout{Text with a horizontal line through its center!}
Struck with Hatching text: \xout{Text with hatching pattern!}
`

`tex
\begin{lstlisting}[language=C, mathescape]
/ the following code computes $\displaystyle\sum_{i=1}^{n}i$ /
for (i = 1; i <= limit; i++) {
sum += i;
}
\end{lstlisting}
`

mathpix-markdown-it is an open source implementation of the mathpix-markdown spec written in Typescript.
It relies on the following open source libraries:
- MathJax v3 (to render math with SVGs)
- markdown-it (for standard Markdown parsing)
npm usage:
`bash`
$ npm install mathpix-markdown-it
yarn usage:
`bash`
$ yarn add mathpix-markdown-it
We provide React components which make rendering of mathpix-markdown-it easy for React applications:
Full example
`js
import {MathpixMarkdown, MathpixLoader} from 'mathpix-markdown-it';
class App extends Component {
render() {
return (
...
);
}
}
`
#### Example of render() method usage
`js
import * as React from 'react';
import { MathpixMarkdownModel as MM } from 'mathpix-markdown-it';
class App extends React.Component {
componentDidMount() {
const elStyle = document.getElementById('Mathpix-styles');
if (!elStyle) {
const style = document.createElement("style");
style.setAttribute("id", "Mathpix-styles");
style.innerHTML = MM.getMathpixFontsStyle() + MM.getMathpixStyle(true);
document.head.appendChild(style);
}
}
render() {
const html = MM.render('$x = \\frac { - b \\pm \\sqrt { b ^ { 2 } - 4 a c } } { 2 a }$');
return (
export default App;
`
#### Example of markdownToHTML() method usage
`js
class ConvertForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '\\[\n' +
'y = \\frac { \\sum _ { i } w _ { i } y _ { i } } { \\sum _ { i } w _ { i } } , i = 1,2 \\ldots k\n' +
'\\]',
result: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
event.preventDefault();
this.setState({result: MM.markdownToHTML(this.state.value)})
}
render() {
return (
$3
#### Example of Latex to mathml/asciimath/tsv conversion
Rendering methods have the ability to convert
Latex representation to such formats as: mathml, asciimath, tsv`js
const options = {
outMath: { //You can set which formats should be included into html result
include_mathml: true,
include_asciimath: true,
include_latex: true,
include_svg: true, // sets in default
include_tsv: true,
include_table_html: true, // sets in default
}
};
const html = MathpixMarkdownModel.markdownToHTML($x^x$, options);
`markdownToHTML() returns an HTML string that will contain the formats specified in the options.For
Latex formulas, the result will be:
`html
..
`For
tabular, the result will be:
`html
...
`Then calling the
parseMarkdownByHTML(html) method will return all formats as a list from the incoming html string.For
Latex formulas:
`js
[
{
"type": "mathml",
"value": ""
},
{
"type": "asciimath",
"value": "x^(x)"
},
{
"type": "latex",
"value": "x^x"
},
{
"type": "svg",
"value": "..."
}
]
`For
tabular:
`js
[
{
"type": "html",
"value": "...
"
},
{
"type": "tsv",
"value": "... "
}
]
`#### Example of outMath option usage
For
Latex formulas:
`js
const options = {
outMath: {
include_mathml: false,
include_asciimath: true,
include_latex: false,
}
};
const latex = $x^x$;
const html = MathpixMarkdownModel.markdownToHTML(latex, options);
const parsed = MathpixMarkdownModel.parseMarkdownByHTML(html, false);
`html:
`html
`parsed:
`js
[
{
"type": "asciimath",
"value": "x^(x)"
},
{
"type": "svg",
"value": "..."
}
]
`For
tabular:
`js
const options = {
outMath: {
include_table_html: false,
include_tsv: true,
}
};
const latex = \\begin{tabular}{ l c r };
const html = MathpixMarkdownModel.markdownToHTML(latex, options);
const parsed = MathpixMarkdownModel.parseMarkdownByHTML(html, false);
``html
`parsed:
`js
[
{
type: 'tsv',
value: '1\t2\t3\n4\t5\t6\n7\t8\t9'
}
]
`
$3
#### parseMarkdownByHTML(html: string, include_sub_math: boolean = true)
##### By default, the include_sub_math option is enabled, and as a result will contain formats for the nested table and math.
`js
const options = {
outMath: {
include_asciimath: true,
include_mathml: true,
include_latex: true,
include_svg: true,
include_tsv: true,
include_table_html: true
}
};
const latex = \\begin{tabular}{ l c r };
const html = MathpixMarkdownModel.markdownToHTML(latex, options);
const parsed = MathpixMarkdownModel.parseMarkdownByHTML(html);
`parsed:
`js
[
{
type: 'html',
value: '..
'
},
{ type: 'tsv', value: '1\tx^(1)\t3\n4\ty^(1)\t6\n7\tz^(1)\t9' },
{ type: 'mathml', value: '' },
{ type: 'asciimath', value: 'x^(1)' },
{ type: 'latex', value: 'x^1' },
{ type: 'svg', value: '' },
{ type: 'mathml', value: '' },
{ type: 'asciimath', value: 'y^(1)' },
{ type: 'latex', value: 'y^1' },
{ type: 'svg', value: '' },
{ type: 'mathml', value: '' },
{ type: 'asciimath', value: 'z^(1)' },
{ type: 'latex', value: 'z^1' },
{ type: 'svg', value: '' }
]
`##### If you set the include_sub_math option in the false, then as a result, will not contain formats for all the nested table and math.
`js
const options = {
outMath: {
include_asciimath: true,
include_mathml: true,
include_latex: true,
include_svg: true,
include_tsv: true,
include_table_html: true
}
};
const latex = \\begin{tabular}{ l c r };
const html = MathpixMarkdownModel.markdownToHTML(latex, options);
const parsed = MathpixMarkdownModel.parseMarkdownByHTML(html, false);
`parsed:
`js
[
{
type: 'html',
value: '..
'
},
{
type: 'tsv',
value: '1\tx^(1)\t3\n4\ty^(1)\t6\n7\tz^(1)\t9'
}
]
`
NodeJS
$3
#### Example of mathpix-markdown-it usage in the node application
#### Example of Latex to mathml/asciimath/tsv conversion in the node application
`js
const {MathpixMarkdownModel} = require('mathpix-markdown-it'); const htmlMM = MathpixMarkdownModel.render(text, options);
const mathpixStyles = MathpixMarkdownModel.getMathpixStyleOnly();
`
Before using mathpix-markdown-it in node applications, you should define global variables`js
const Window = require('window');
const window = new Window();
global.window = window;
global.document = window.document;const jsdom = require("jsdom");
const { JSDOM } = jsdom;
global.DOMParser = new JSDOM().window.DOMParser;
`#### Simple example of mathpix-markdown-it usage in node app.
It prints html to the console for string
\\(ax^2 + bx + c = 0\\)1. Install packages:
`bash
$ npm install mathpix-markdown-it jsdom window
`2. Node app.js:
`js
const {MathpixMarkdownModel} = require('mathpix-markdown-it');const Window = require('window');
const window = new Window();
global.window = window;
global.document = window.document;
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
global.DOMParser = new JSDOM().window.DOMParser;
const text =
\\(ax^2 + bx + c = 0\\);
const options = {
htmlTags: true,
width: 800
};
const htmlMM = MathpixMarkdownModel.markdownToHTML(text, options);console.log(htmlMM);
`3. Start:
`bash
node app.js
`4. Result:
`html
`Using mathpix-markdown-it in web browsers
If you are loading
mathpix-markdown-it from a CDN into a web page, there is no
need to install anything. Simply use a script tag that loads
mathpix-markdown-it from the CDN. E.g.,` html
`$3
* Example of render function usage (View Demo)
* Example of markdownToHTML function usage(View Demo)
Accessibility math
By default, math is not accessibility.
In order for math to become accessibility, need to load the library speech-rule-engine for semantic interpretation.
$3
`js
import { MathpixMarkdownModel } from "mathpix-markdown-it";
import { loadSre } from "mathpix-markdown-it/lib/sre/sre-browser";const html = MathpixMarkdownModel.markdownToHTML("$x^y$", {
accessibility: {
sre: loadSre()
},
});
`
$3
`js
const { MathpixMarkdownModel } = require('mathpix-markdown-it');
const { loadSreAsync } = require('mathpix-markdown-it/lib/sre/sre-node');(async() => {
const html = MathpixMarkdownModel.markdownToHTML("$x^y$", {
accessibility: {
sre: await loadSreAsync()
},
});
})
` _If the accessibility option is specified, then
assistive-mml into mjx-container will be added for math_$3
`html
`The math will then be read by screen readers as
x Superscript y
Context menu for export math
The context menu for selecting math export options is only available for browser libraries
In the rendering options, specify the export formats that should be displayed in the menu:
`js
const html = MM.markdownToHTML("$x^y$", {
outMath: {
include_error: true,
// Show in context menu:
include_asciimath: true,
include_latex: true,
include_mathml: true,
include_mathml_word: true,
}
});
`Then we can use:
`js
import {
addListenerContextMenuEvents,
removeListenerContextMenuEvents,
} from "mathpix-markdown-it/lib/contex-menu";
`addListenerContextMenuEvents - listens for events to invoke and create the context menu
removeListenerContextMenuEvents - stop listening to these events
Documentation
React components
| React components | props | description |
|-------------------|---------|------------------------------------|
|
MathpixLoader | | Loads styles |
| MathpixMarkdown | props | Renders input text to html element |The
MathpixMarkdown React element accepts the following props: $3
| prop | type
default | description |
|--------------------------|------------------------------|------------------------------------------------------------------------------------------------------------------------|
| text | sting | string that will be converted |
| alignMathBlock | string center | aligns math-block by this params |
| display | string block | block - the whole space, inline-block - renders in its actual size |
| showTimeLog | boolean false | shows execution time in console |
| isDisableFancy | boolean false | true - disables processing of special characters (Example: + item, - item ) |
| disableRules | array of strings [] | You can pass a list of rules for markdown rendering that should be disabled but only if isDisableFancy is not true.|
| | | Example: disableRules = ['replacements'] will disable fancy characters processing. |
| htmlTags | boolean;false | Enables HTML tags in source |
| htmlDisableTagMatching | boolean;false | Allows to turn off the validation that checks for matching opening and closing HTML tags |
| xhtmlOut | boolean;false | Uses / to close single tags () |
| breaks | boolean;true | Converts \n in paragraphs into |
| typographer | boolean;false | Enables some language-neutral replacement + quotes beautification (Example: (c) (C) (r) (R) (tm) (TM) (p) (P) +-) |
| linkify | boolean;false | Autoconverts URL-like text to links |
| width | number;1200 | Sets text container width |
| outMath | TOutputMath;{} | Sets options to output html |
| mathJax | TOutputMathJax;{} | Sets options to output MathJax |
| smiles | ISmilesOptions;{} | Sets options to output chemistry equation |
| parserErrors | ParserErrors;{} | Sets options to output parser errors for equations and tabular |
| codeHighlight | CodeHighlight;{} | Sets options to highlight code block |
| footnotes | Footnotes;{} | Sets options to footnotes |
MathpixMarkdownModel methods
| | returns | description | |
|----------------------------------------------------|---------|---------------------------------------------------------------------------------------------------------------------------|---------|
| Style methods: | | | |
| loadMathJax() | boolean | Adds a style element into the head of the document and returns true. In case of an error, returns false. |example|
| getMathpixStyleOnly() | string | returns styles as a string. | |
| getMathpixStyle(true) | string | returns styles as a string including styles for container. |example|
| getMathpixFontsStyle() | boolean | returns fonts styles as a string. |example|
| Render methods: | | | |
| markdownToHTML(str, options: TMarkdownItOptions) | string | Renders input text to html element as a string. |example|
| render(str, options: optionsMathpixMarkdown) | string | Renders input text to HTML element as a string and wraps it in a container. Should be used to render the entire document.|example|
| Parser methods: | | | |
| parseMarkdownByHTML(htmlString) | Array | parses input html string and returns array of formats. |examples|
| parseMarkdownByElement(htmlElement) | Array | parses input html element and returns array of formats. | |
$3
| | type
default | description |
|---------------------------------------|------------------------------|------------------------------------------------------------------------------------------------------------------------|
| isDisableFancy | boolean false | true - disables processing of special characters (Example: + item, - item ) |
| disableRules | array of strings [] | You can pass a list of rules for markdown rendering that should be disabled but only if isDisableFancy is not true.|
| | | Example: disableRules = ['replacements'] will disable fancy characters processing. |
| htmlTags | boolean;false | Enables HTML tags in source |
| htmlDisableTagMatching | boolean;false | Allows to turn off the validation that checks for matching opening and closing HTML tags |
| xhtmlOut | boolean;false | Uses / to close single tags () |
| breaks | boolean;true | Converts \n in paragraphs into |
| typographer | boolean;true | Enables some language-neutral replacement + quotes beautification (Example: (c) (C) (r) (R) (tm) (TM) (p) (P) +-) |
| linkify | boolean;true | Autoconverts URL-like text to links |
| width | number;1200 | Sets text container width |
| lineNumbering | boolean;false | Sets line numbers. Recommended for synchronization with a text editor. |
| outMath | TOutputMath;{} | Sets options to output html |
| mathJax | TOutputMathJax;{} | Sets options to output MathJax |
| htmlSanitize | THtmlSanitize;{} | Sets html output options (if htmlTags=true). Cleans up user html input. |
| | | Removes script tags and stuff. Removes broken and malicious html. Set to false to disable |
| smiles | ISmilesOptions;{} | Sets options to output chemistry equation |
| htmlWrapper | THtmlWrapper;{} | Sets options for output full html page |
| accessibility | TAccessibility;{} | Sets options to accessibility |
| nonumbers | boolean;false | Sets options to prevent equations, tables, figure from being numbered |
| showPageBreaks | boolean;false | Hidden tags will be shown in html like page break |
| centerImages | boolean;true | Center align images by default |
| centerTables | boolean;true | Center align tables by default |
| validateLink | function;null | The function (url: string) => void to override md link validator |
| enableCodeBlockRuleForLatexCommands | boolean;false | By default, if latex commands are indented (4 spaces / 1 tab) they do not become Code Blocks. |
| parserErrors | ParserErrors;{} | Sets options to output parser errors for equations and tabular |
| codeHighlight | CodeHighlight;{} | Sets options to highlight code block |
| footnotes | Footnotes;{} | Sets options to footnotes |
| copyToClipboard | boolean;false | Added copy to clipboard button for code chunks. To handle events, import the function addListenerCopyToClipboardEvents() from "mathpix-markdown-it/lib/copy-to-clipboard";|
| renderOptions | RenderOptions;{} | Sets options to enable render rules |$3
| | type
default | description |
|---------------------------------------|------------------------------|------------------------------------------------------------------------------------------------------------------------|
| alignMathBlock | string center | aligns math-block |
| display | string block | block - the whole space, inline-block - renders in its actual size |
| showTimeLog | boolean false | shows execution time in console |
| isDisableFancy | boolean false | true - disables processing of special characters (Example: + item, - item ) |
| disableRules | array of strings [] | You can pass a list of rules for markdown rendering that should be disabled but only if isDisableFancy is not true.|
| | | Example: disableRules = ['replacements'] will disable fancy characters processing. |
| htmlTags | boolean;false | Enables HTML tags in source |
| htmlDisableTagMatching | boolean;false | Allows to turn off the validation that checks for matching opening and closing HTML tags |
| xhtmlOut | boolean;false | Uses / to close single tags () |
| breaks | boolean;true | Converts \n in paragraphs into |
| typographer | boolean;true | Enables some language-neutral replacement + quotes beautification (Example: (c) (C) (r) (R) (tm) (TM) (p) (P) +-) |
| linkify | boolean;true | Autoconverts URL-like text to links |
| width | number;1200 | Sets text container width |
| outMath | TOutputMath;{} | Sets options to output html |
| mathJax | TOutputMathJax;{} | Sets options to output MathJax |
| htmlSanitize | THtmlSanitize;{} | Sets html output options (if htmlTags=true). Cleans up user html input. |
| | | Removes script tags and stuff. Removes broken and malicious html. Set to false to disable |
| smiles | ISmilesOptions;{} | Sets options to output chemistry equation |
| nonumbers | boolean;false | Sets options to prevent equations, tables, figure from being numbered |
| showPageBreaks | boolean;false | Hidden tags will be shown in html like page break |
| centerImages | boolean;true | Center align images by default |
| centerTables | boolean;true | Center align tables by default |
| validateLink | function;null | The function (url: string) => void to override md link validator |
| enableCodeBlockRuleForLatexCommands | boolean;false | By default, if latex commands are indented (4 spaces / 1 tab) they do not become Code Blocks. |
| parserErrors | ParserErrors;{} | Sets options to output parser errors for equations and tabular |
| codeHighlight | CodeHighlight;{} | Sets options to highlight code block |
| footnotes | Footnotes;{} | Sets options to footnotes |
| copyToClipboard | boolean;false | Added copy to clipboard button for code chunks. To handle events, import the function addListenerCopyToClipdoardEvents() from "mathpix-markdown-it/lib/copy-to-clipboard";|
| renderOptions | RenderOptions;{} | Sets options to enable render rules |$3
| | type
default | description |
|--------------------------|------------------------------|-------------------------------------------------------------------------------------------------------------------|
| include_mathml | boolean false | outputs mathml |
| include_mathml_word | boolean false | outputs mathml_word |
| include_asciimath | boolean false | outputs asciimath |
| include_linearmath | boolean false | outputs linearmath |
| include_latex | boolean true | outputs latex |
| include_svg | boolean true | outputs svg |
| include_tsv | boolean false | outputs tsv |
| include_csv | boolean false | outputs csv |
| include_table_html | boolean true | outputs html table |
| include_table_markdown | boolean false | outputs markdown table |
| include_smiles | boolean false | outputs smiles |
| tsv_separators | {column: '\t', row: '\n'} | Separators for tsv tables |
| csv_separators | {column: ',', row: '\n', toQuoteAllFields: false} | Separators for csv tables. If toQuoteAllFields=true - all fields will be enclosed in double quotes|
| not_catch_errors | boolean false | Do not catch math rendering errors |
| include_error | boolean false | outputs error |
| include_speech | boolean false | outputs speech | {column: ' ', row: ' | Separators for Markdown tables |
| table_markdown | {math_as_ascii: false, math_inline_delimiters: ['$','$']}| By default, math goes into Markdown tables as latex and is enclosed in $...$ delimiters. If math_as_ascii is set to true, then math will be represented as asciimath | $3
| | type
default | description |
|----------------------|------------------------------|--------------------------------------------------------------------------------------------------------------------|
| mtextInheritFont | boolean false | true to make mtext elements use surrounding font |
$3
| | type
default | description |
|-------------------------------------|----------------------------|-------------------------------------------------------------------------------------------------------------------------|
| disallowedTagsMode | string discard | discard (the default) - disallowed tags are discarded. |
| | | escape - the disallowed tags are escaped rather than discarded. Any text or subtags is handled normally. |
| | | recursiveEscape - the disallowed tags are escaped rather than discarded, and the same treatment is applied |
| | | to all subtags, whether otherwise allowed or not. |
| allowedTags | Array | List of allowed HTML tags. See default options. |
| allowedAttributes | Record | Defines allowed attributes for specific tags. Example: { a: ['href', 'name', 'target'], img: ['src'] }. |
| allowedIframeHostnames | Array | List of allowed hostnames for