CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mathjax

JavaScript display engine for LaTeX, MathML, and AsciiMath mathematical notation in browsers and Node.js

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

input-processing.mddocs/

Input Processing

MathJax supports three mathematical notation formats: TeX/LaTeX, MathML, and AsciiMath. Each input processor provides conversion to various output formats with extensive customization options.

Capabilities

TeX/LaTeX Input

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}');

MathML Input

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);

AsciiMath Input

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)');

Configuration Options

TeX Configuration

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 Extensions

MathML input supports the MML3 extension for MathML 3.0 features.

Available MML Extensions:

  • [mml]/mml3 - MathML 3.0 features and elements

Extension Usage:

// Load MML3 extension
MathJax.config.loader.load.push('[mml]/mml3');

// Configure MML3 options
MathJax.config.mml = {
  packages: ['base', 'mml3']
};

MathML Configuration

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);
  }
};

AsciiMath Configuration

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: '.'
};

TeX Extensions

MathJax provides 30+ TeX extensions for specialized mathematical notation:

Core Extensions

  • ams - AMS math environments and symbols
  • amscd - Commutative diagrams
  • color - Color support for text and backgrounds
  • newcommand - Define custom commands and environments

Specialized Extensions

  • mhchem - Chemistry notation and equations
  • physics - Physics notation and operators
  • braket - Dirac bra-ket notation
  • cancel - Cancel expressions with lines
  • bbox - Bounding boxes and backgrounds
  • boldsymbol - Bold mathematical symbols

Formatting Extensions

  • enclose - Enclose expressions with lines/boxes
  • textmacros - Text formatting commands
  • unicode - Unicode character support
  • verb - Verbatim text rendering

Extension 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}');

Error Handling

Input Processing Errors

// 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>';
};

Input Validation

// 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;
  }
}

Advanced Features

Custom Macros and Environments

// 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]']
};

Processing Control

// 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}']
];

Performance Optimization

Input Processor Reset

Reset input processors to clear caches and state:

// Reset TeX processor
MathJax.texReset();

// Reset MathML processor  
MathJax.mmlReset();

// Reset AsciiMath processor
MathJax.asciimathReset();

Conversion Options

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))
);

docs

accessibility.md

document-rendering.md

extensions.md

index.md

initialization.md

input-processing.md

output-formats.md

tile.json