JavaScript display engine for LaTeX, MathML, and AsciiMath mathematical notation in browsers and Node.js
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
MathJax supports three mathematical notation formats: TeX/LaTeX, MathML, and AsciiMath. Each input processor provides conversion to various output formats with extensive customization options.
Process TeX and LaTeX mathematical notation with support for packages, macros, and environments.
/**
* Convert TeX to SVG output
* @param tex - TeX/LaTeX string to convert
* @param options - Conversion options
* @returns SVG element containing the rendered mathematics
*/
function tex2svg(tex: string, options?: ConversionOptions): Element;
/**
* Convert TeX to CommonHTML output
* @param tex - TeX/LaTeX string to convert
* @param options - Conversion options
* @returns HTML element containing the rendered mathematics
*/
function tex2chtml(tex: string, options?: ConversionOptions): Element;
/**
* Convert TeX to MathML
* @param tex - TeX/LaTeX string to convert
* @param options - Conversion options
* @returns MathML string representation
*/
function tex2mml(tex: string, options?: ConversionOptions): string;
/**
* Convert TeX to SVG (Promise-based)
* @param tex - TeX/LaTeX string to convert
* @param options - Conversion options
* @returns Promise resolving to SVG element
*/
function tex2svgPromise(tex: string, options?: ConversionOptions): Promise<Element>;
/**
* Convert TeX to CommonHTML (Promise-based)
* @param tex - TeX/LaTeX string to convert
* @param options - Conversion options
* @returns Promise resolving to HTML element
*/
function tex2chtmlPromise(tex: string, options?: ConversionOptions): Promise<Element>;
/**
* Convert TeX to MathML (Promise-based)
* @param tex - TeX/LaTeX string to convert
* @param options - Conversion options
* @returns Promise resolving to MathML string
*/
function tex2mmlPromise(tex: string, options?: ConversionOptions): Promise<string>;
/**
* Reset TeX input processor
* @param args - Reset arguments
*/
function texReset(...args: any[]): void;Usage Examples:
// Basic TeX conversion
const svg = MathJax.tex2svg('E = mc^2');
const html = MathJax.tex2chtml('\\frac{x^2}{2}');
const mml = MathJax.tex2mml('\\sum_{i=1}^n x_i');
// With display options
const displayMath = MathJax.tex2svg('\\int_0^\\infty e^{-x} dx', {
display: true,
em: 16,
ex: 8
});
// Inline math
const inlineMath = MathJax.tex2chtml('x^2 + y^2 = z^2', {
display: false
});
// Promise-based conversion
const result = await MathJax.tex2svgPromise('\\begin{matrix} a & b \\\\ c & d \\end{matrix}');Process MathML (Mathematical Markup Language) with support for both presentation and content MathML.
/**
* Convert MathML to SVG output
* @param mathml - MathML string to convert
* @param options - Conversion options
* @returns SVG element containing the rendered mathematics
*/
function mml2svg(mathml: string, options?: ConversionOptions): Element;
/**
* Convert MathML to CommonHTML output
* @param mathml - MathML string to convert
* @param options - Conversion options
* @returns HTML element containing the rendered mathematics
*/
function mml2chtml(mathml: string, options?: ConversionOptions): Element;
/**
* Convert MathML to SVG (Promise-based)
* @param mathml - MathML string to convert
* @param options - Conversion options
* @returns Promise resolving to SVG element
*/
function mml2svgPromise(mathml: string, options?: ConversionOptions): Promise<Element>;
/**
* Convert MathML to CommonHTML (Promise-based)
* @param mathml - MathML string to convert
* @param options - Conversion options
* @returns Promise resolving to HTML element
*/
function mml2chtmlPromise(mathml: string, options?: ConversionOptions): Promise<Element>;
/**
* Reset MathML input processor
* @param args - Reset arguments
*/
function mmlReset(...args: any[]): void;Usage Examples:
// Basic MathML conversion
const mathml = '<math><mfrac><mi>x</mi><mi>y</mi></mfrac></math>';
const svg = MathJax.mml2svg(mathml);
const html = MathJax.mml2chtml(mathml);
// Complex MathML
const complexMml = `
<math display="block">
<mrow>
<mi>x</mi>
<mo>=</mo>
<mfrac>
<mrow>
<mo>-</mo>
<mi>b</mi>
<mo>±</mo>
<msqrt>
<msup><mi>b</mi><mn>2</mn></msup>
<mo>-</mo>
<mn>4</mn>
<mi>a</mi>
<mi>c</mi>
</msqrt>
</mrow>
<mrow>
<mn>2</mn>
<mi>a</mi>
</mrow>
</mfrac>
</mrow>
</math>
`;
const result = MathJax.mml2svg(complexMml, { display: true });
// Promise-based conversion
const asyncResult = await MathJax.mml2chtmlPromise(mathml);Process AsciiMath notation, a simple text-based format for mathematical expressions.
/**
* Convert AsciiMath to SVG output
* @param ascii - AsciiMath string to convert
* @param options - Conversion options
* @returns SVG element containing the rendered mathematics
*/
function asciimath2svg(ascii: string, options?: ConversionOptions): Element;
/**
* Convert AsciiMath to CommonHTML output
* @param ascii - AsciiMath string to convert
* @param options - Conversion options
* @returns HTML element containing the rendered mathematics
*/
function asciimath2chtml(ascii: string, options?: ConversionOptions): Element;
/**
* Convert AsciiMath to SVG (Promise-based)
* @param ascii - AsciiMath string to convert
* @param options - Conversion options
* @returns Promise resolving to SVG element
*/
function asciimath2svgPromise(ascii: string, options?: ConversionOptions): Promise<Element>;
/**
* Convert AsciiMath to CommonHTML (Promise-based)
* @param ascii - AsciiMath string to convert
* @param options - Conversion options
* @returns Promise resolving to HTML element
*/
function asciimath2chtmlPromise(ascii: string, options?: ConversionOptions): Promise<Element>;
/**
* Reset AsciiMath input processor
* @param args - Reset arguments
*/
function asciimathReset(...args: any[]): void;Usage Examples:
// Basic AsciiMath conversion
const svg = MathJax.asciimath2svg('x^2 + y^2 = z^2');
const html = MathJax.asciimath2chtml('sum_(i=1)^n x_i');
// Complex expressions
const integral = MathJax.asciimath2svg('int_0^oo e^(-x) dx');
const matrix = MathJax.asciimath2chtml('[[a,b],[c,d]]');
const fraction = MathJax.asciimath2svg('(x^2)/(2a)');interface TexOptions {
/** Extension packages to load */
packages?: string[];
/** Custom macro definitions */
macros?: Record<string, string | [string, number]>;
/** Custom environment definitions */
environments?: Record<string, any>;
/** Process backslash escapes in text */
processEscapes?: boolean;
/** Process LaTeX environments */
processEnvironments?: boolean;
/** Process equation references */
processRefs?: boolean;
/** Pattern for digit recognition */
digits?: RegExp;
/** Equation tag format */
tags?: 'none' | 'ams' | 'all';
/** Tag placement side */
tagSide?: 'right' | 'left';
/** Tag indentation */
tagIndent?: string;
/** Use label IDs for references */
useLabelIds?: boolean;
/** Inline math delimiters */
inlineMath?: Array<[string, string]>;
/** Display math delimiters */
displayMath?: Array<[string, string]>;
/** Skip tags for certain elements */
skipTags?: string[];
/** Ignore HTML classes */
ignoreClass?: RegExp | string;
/** Process HTML classes */
processClass?: RegExp | string;
}Configuration Example:
MathJax.config.tex = {
packages: ['base', 'ams', 'color', 'physics'],
macros: {
R: '{\\mathbb{R}}',
C: '{\\mathbb{C}}',
bold: ['{\\mathbf{#1}}', 1],
vec: ['{\\boldsymbol{#1}}', 1]
},
environments: {
braced: ['\\left\\{', '\\right\\}']
},
inlineMath: [['$', '$'], ['\\(', '\\)']],
displayMath: [['$$', '$$'], ['\\[', '\\]']],
processEscapes: true,
tags: 'ams',
tagSide: 'right'
};MathML input supports the MML3 extension for MathML 3.0 features.
Available MML Extensions:
[mml]/mml3 - MathML 3.0 features and elementsExtension Usage:
// Load MML3 extension
MathJax.config.loader.load.push('[mml]/mml3');
// Configure MML3 options
MathJax.config.mml = {
packages: ['base', 'mml3']
};interface MMLOptions {
/** Parsing mode */
parseAs?: 'html' | 'xml';
/** Force reparsing of MathML */
forceReparse?: boolean;
/** Parse error handler */
parseError?: (error: Error) => void;
/** Verify MathML tree structure */
verifyTree?: boolean;
}Configuration Example:
MathJax.config.mml = {
parseAs: 'html',
forceReparse: true,
verifyTree: true,
parseError: (error) => {
console.warn('MathML parse error:', error.message);
}
};interface AsciiMathOptions {
/** Fix phi symbol rendering */
fixphi?: boolean;
/** Use display style for all expressions */
displaystyle?: boolean;
/** Decimal separator character */
decimalsign?: string;
}Configuration Example:
MathJax.config.asciimath = {
fixphi: true,
displaystyle: false,
decimalsign: '.'
};MathJax provides 30+ TeX extensions for specialized mathematical notation:
ams - AMS math environments and symbolsamscd - Commutative diagramscolor - Color support for text and backgroundsnewcommand - Define custom commands and environmentsmhchem - Chemistry notation and equationsphysics - Physics notation and operatorsbraket - Dirac bra-ket notationcancel - Cancel expressions with linesbbox - Bounding boxes and backgroundsboldsymbol - Bold mathematical symbolsenclose - Enclose expressions with lines/boxestextmacros - Text formatting commandsunicode - Unicode character supportverb - Verbatim text renderingExtension Usage:
// Load extensions
MathJax.config.loader.load.push('[tex]/ams', '[tex]/color', '[tex]/mhchem');
// Configure extension options
MathJax.config.tex = {
packages: ['base', 'ams', 'color', 'mhchem'],
color: {
padding: '2px',
borderWidth: '1px'
}
};
// Use extension features
const coloredMath = MathJax.tex2svg('\\color{red}{x^2} + \\color{blue}{y^2}');
const chemistry = MathJax.tex2svg('\\ce{H2O + CO2 -> H2CO3}');
const physics = MathJax.tex2svg('\\bra{\\psi}\\hat{H}\\ket{\\psi}');// Configure error handling for TeX
MathJax.config.tex.formatError = (jax, error) => {
return jax.formatError(error);
};
// Configure error handling for MathML
MathJax.config.mml.parseError = (error) => {
console.error('MathML parsing failed:', error.message);
return error.message;
};
// Global error handling
MathJax.config.options.compileError = (doc, math, error) => {
console.error('Math compilation failed:', error.message);
math.typesetRoot.innerHTML = '<span style="color:red">[Math Error]</span>';
};// Validate TeX input
function validateTeX(tex) {
try {
MathJax.tex2mml(tex);
return true;
} catch (error) {
console.error('Invalid TeX:', error.message);
return false;
}
}
// Validate MathML input
function validateMathML(mathml) {
try {
MathJax.mml2svg(mathml);
return true;
} catch (error) {
console.error('Invalid MathML:', error.message);
return false;
}
}// Define custom TeX macros
MathJax.config.tex.macros = {
// Simple substitution
R: '{\\mathbb{R}}',
// Macro with parameters
norm: ['{\\left\\|#1\\right\\|}', 1],
// Multi-parameter macro
frac: ['{\\dfrac{#1}{#2}}', 2],
// Conditional macro
abs: ['{\\left|#1\\right|}', 1]
};
// Define custom environments
MathJax.config.tex.environments = {
braced: ['\\left\\{', '\\right\\}'],
bracketed: ['\\left[', '\\right]']
};// Control which elements to process
MathJax.config.tex.processClass = 'tex2jax_process';
MathJax.config.tex.ignoreClass = 'tex2jax_ignore';
// Custom delimiters
MathJax.config.tex.inlineMath = [
['$', '$'],
['\\(', '\\)'],
['\\begin{math}', '\\end{math}']
];
MathJax.config.tex.displayMath = [
['$$', '$$'],
['\\[', '\\]'],
['\\begin{displaymath}', '\\end{displaymath}']
];Reset input processors to clear caches and state:
// Reset TeX processor
MathJax.texReset();
// Reset MathML processor
MathJax.mmlReset();
// Reset AsciiMath processor
MathJax.asciimathReset();interface ConversionOptions {
/** Display math (true) vs inline math (false) */
display?: boolean;
/** Em size in pixels */
em?: number;
/** Ex height in pixels */
ex?: number;
/** Container width for line breaking */
containerWidth?: number;
/** Scale factor for output */
scale?: number;
/** Font family for measurements */
family?: string;
/** Input format name */
format?: string;
/** Processing end state */
end?: number;
/** Font family for mtext elements */
mtextFamily?: string;
/** Font family for merror elements */
merrorFamily?: string;
/** Line width for line breaking */
lineWidth?: number;
/** Enable automatic line breaking */
linebreaks?: boolean;
}Optimization Examples:
// Optimize for performance
const options = {
em: 16,
ex: 8,
containerWidth: 1280,
scale: 1.0
};
// Batch processing
const expressions = ['x^2', 'y^2', 'z^2'];
const results = expressions.map(expr => MathJax.tex2svg(expr, options));
// Async batch processing
const asyncResults = await Promise.all(
expressions.map(expr => MathJax.tex2svgPromise(expr, options))
);